标签:
学习PHP之前需要先搭建PHP运行的环境(即服务器+PHP+数据库)来使PHP成功运行,具体环境搭建教程可参考pharen(http://www.cnblogs.com/pharen/archive/2012/02/06/2340628.html)的教程(亲测可用),教程中一些资源链接可能已经失效,下面给出部分资源链接:
PHP资源:http://windows.php.net/download#php-5.6
Apache(msi安装包)资源:http://archive.apache.org/dist/httpd/binaries/win32/
有几个要点需要注意(笔者作为菜鸡就被坑了):
(1)软件安装路径不要包含中文或者空格
(2)Apache版本要与PHP版本兼容,较老版本Apache无法支持新版本的PHP,例如:1、php5.2支持Apache2.0和Apache2.2;2、php5.3、php5.4同时支持Apache2.2和Apache2.4;3、php5.5只支持Apache2.4
(3)需要安装PHP编译器的运行环境,不同版本PHP需要的VC支持库版本也不同:
apache.org下载的Apache都是vc6版本,否则就根据不同文件说明安装不同的运行库。
vc11运行库x86/x64版本:http://www.microsoft.com/en-us/download/details.aspx?id=30679
vc10运行库x86版本:http://www.microsoft.com/en-us/download/details.aspx?id=5555
vc10运行库x64版本:http://www.microsoft.com/en-us/download/details.aspx?id=14632
vc9运行库x86版本:http://www.microsoft.com/en-us/download/details.aspx?id=5582
vc9运行库x64版本:http://www.microsoft.com/en-us/download/details.aspx?id=15336
常见问题参考资料连接如下:
(1)http://www.2cto.com/os/201312/264364.html
(2)http://jingyan.baidu.com/article/ceb9fb10d909c48cac2ba06c.html
php教程简要入门版可参见W3C(供入门菜鸟使用):
下面给出几个PHP学习粗浅的例子,仅供娱乐:
例子1:表单提交处理页面
formSubmit.php文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>php basis-1</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Wayne Ng" /> <meta name="description" content="basis-1" /> <meta name="revised" content="Wayne Ng,2016/2/16" /> <style> .errColor{color: red;} </style> </head> <body> <?php function process_input($data){ $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $name = $email = $website = $comment = $gender = ""; $nameErr = $emailErr = $genderErr = $websiteErr = ""; if($_SERVER["REQUEST_METHOD"] == "POST"){ //提取name信息 if(empty($_POST["name"])){ $nameErr = "名字是必须的"; } else{ $name = process_input($_POST["name"]); //检查名字是否仅包含字母和空格 if(!preg_match("/^[a-zA-Z ]*$/", $name)){ $nameErr = "名字只能包含英文字母和空格"; } } //提取email信息 if(empty($_POST["email"])){ $emailErr = "邮箱是必须的"; } else{ $email = process_input($_POST["email"]); //检查邮箱名字是否合法 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "无效的 email 格式!"; } } //提取website信息 if(empty($_POST["website"])){ $website = ""; } else{ $website = process_input($_POST["website"]); if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/% =~_|]/i",$website)) { $websiteErr = "无效的 URL"; } } //提取comment信息 if(empty($_POST["comment"])){ $comment = ""; } else{ $comment = process_input($_POST["comment"]); } //提取gender信息 if(empty($_POST["gender"])){ $genderErr = "性别是必须的"; } else{ $gender = process_input($_POST["gender"]); } } ?> <h2>PHP表单实例</h2> <p><span class="errColor">* 必填项目</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:    <input type="text" name="name" value="<?php echo $name;?>"/> <span class="errColor">*<?php echo $nameErr;?></span><br /> 邮箱:    <input type="text" name="email" value="<?php echo $email;?>"/> <span class="errColor">*<?php echo $emailErr;?></span><br /> 网址:    <input type="text" name="website" value="<?php echo $website;?>"/> <span class="errColor"><?php echo $websiteErr;?></span><br /> 评论:    <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea><br /> 性别:    <input type="radio" name="gender" <?php if(isset($gender) && $gender=="male") echo "checked";?> value="male">男 <input type="radio" name="gender" <?php if(isset($gender) && $gender=="female") echo "checked";?> value="female">女 <span class="errColor">*<?php echo $genderErr;?></span><br /><br /> <input type="submit" name="submit" value="提交表单"> </form> <?php echo "<h2>您提交的表单数据如下所示:</h2>"; echo "名字:  ".$name."<br />"; echo "邮箱:  ".$email."<br />"; echo "网址:  ".$website."<br />"; echo "评论:  ".$comment."<br />"; echo "性别:  ".$gender."<br />"; ?> </body> </html>
显示效果:
例子2:文件提交
FileSubmit.php文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>php basis-3</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Wayne Ng" /> <meta name="description" content="basis-3" /> <meta name="revised" content="Wayne Ng,2016/2/17" /> <style> .warning{color: red;} </style> </head> <body> <h2>文件上传</h2> <span class="warning">*文件大小必须小于100kb</span> <form method="post" action="/uploadFile.php" enctype="multipart/form-data"> <label for="file">文件名:</label> <input type="file" name="file" id="file" /><br /> <input type="submit" name="submit" value="提交" /> </form> </body> </html>
uploadFile文件:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php //限制上传文件大小(必须小于100kb) if($_FILES["file"]["size"] < 100 * 1024){ if($_FILES["file"]["error"] > 0){ echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else{ echo "上传文件:".$_FILES["file"]["name"] . "<br />"; echo "文件类型:".$_FILES["file"]["type"] . "<br />"; echo "文件大小:".round($_FILES["file"]["size"]/1024, 1) . "kb<br />"; echo "临时文件:".$_FILES["file"]["tmp_name"] . "<br />"; //检验同名文件是都已经存在 if(file_exists("upload/" . $_FILES["file"]["name"])){ echo $_FILES["file"]["name"] . "已经存在!"; } else{ move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "保存于:" . "upload/" . $_FILES["file"]["name"]; } } } else{ echo "文件大小必须小于100kb"; } ?>
效果显示:
例子3:文件读写操作
fileOperation.php文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>php basis-2</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Wayne Ng" /> <meta name="description" content="basis-2" /> <meta name="revised" content="Wayne Ng,2016/2/17" /> </head> <body> <?php function printFile($file){ while(!feof($file)){ echo fgets($file)."<br />"; } } $fileName = "spam.txt"; //查看原始文件内容 echo "文件原始内容:<br />"; $fileContent = fopen($fileName, ‘r‘) or die("Unable to open file!"); printFile($fileContent); fclose($fileContent); //文件末尾追加内容 $fileContent = fopen($fileName, ‘a+‘) or die("Unable to open file!"); fwrite($fileContent, "Maybe carrot doesn‘t tastes terrible.\n"); fclose($fileContent); //查看修改后文件内容 echo "文件修改后的内容:<br />"; $fileContent = fopen($fileName, ‘r‘) or die("Unable to open file!"); printFile($fileContent); fclose($fileContent); ?> </body> </html>
显示效果:
例子4:XML文件解析
game.xml文件:
<?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE game SYSTEM "game.dtd"> <!-- Date:2016/1/26 Writer:Wayne Ng Theme:MapleStory hero briefInstruction --> <game> <warrior> <hero> <name>英雄</name> <weapons>剑、斧、钝器</weapons> <skill>终极打击</skill> </hero> <hero> <name>圣骑士</name> <weapons>剑、钝器</weapons> <skill>神圣冲击</skill> </hero> <hero> <name>黑骑士</name> <weapons>长枪、矛</weapons> <skill>黑暗穿刺</skill> </hero> </warrior> <magician> <hero> <name>主教</name> <weapons>长杖、短仗</weapons> <skill>圣光普照</skill> </hero> <hero> <name>火毒法师</name> <weapons>长杖、短仗</weapons> <skill>末日火焰</skill> </hero> <hero> <name>冰雷法师</name> <weapons>长杖、短仗</weapons> <skill>冰咆哮</skill> </hero> </magician> <archer> <hero> <name>神射手</name> <weapons>弓</weapons> <skill>暴风箭雨</skill> </hero> <hero> <name>箭神</name> <weapons>弩</weapons> <skill>终极扫射</skill> </hero> </archer> <ranger> <hero> <name>侠盗</name> <weapons>短剑、短刀</weapons> <skill>暗杀</skill> </hero> <hero> <name>隐士</name> <weapons>拳套</weapons> <skill>四连镖</skill> </hero> <hero> <name>暗影双刀</name> <weapons>短剑、短刀</weapons> <skill>终极斩</skill> </hero> </ranger> </game>
expatParser.php文件:
<?php header("Content-type: text/html; charset=utf-8"); //初始化XML解析器 $parser = xml_parser_create(); //当遇到元素头部(如<body>)时回调函数 function start($parser, $element_name, $element_attrs){ switch($element_name){ case "WARRIOR": {echo "<h2>warrior</h2>";break;} case "MAGICIAN": {echo "<h2>magician</h2>";break;} case "ARCHER": {echo "<h2>archer</h2>";break;} case "RANGER": {echo "<h2>ranger</h2>";break;} case "NAME": {echo "名称: ";break;} case "WEAPONS": {echo "武器: ";break;} case "SKILL": {echo "技能: ";break;} } } //当遇到元素尾部(如</body>)时回调函数 function stop($parser, $element_name){ switch($element_name){ case"NAME": {echo "<br />";break;} case"WEAPONS": {echo "<br />";break;} case"SKILL": {echo "<br /><br />";break;} } } //当遇到元素包含字符数据时回调函数 function char($parser, $data){ echo $data; } //指定元素处理回调函数 xml_set_element_handler($parser, "start", "stop"); //指定数据处理回调函数 xml_set_character_data_handler($parser, "char"); $fp = fopen("game.xml", ‘r‘); //读取数据 while($data = fread($fp, 1024)){ xml_parse($parser, $data, feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } //释放xml解析器 xml_parser_free($parser); ?>
显示效果:
例子5:利用php的PDO接口访问MySQL数据库(具体使用数据在前面MySQL例子(http://www.cnblogs.com/yemajun/p/5189554.html)中已经给出)
process_db.php文件;
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <?php $connect = mysql_connect("localhost", "****", "**********");//***分别代表名字和密码 //连接MySQL数据库 if(!$connect){ die("Could not connect: ". mysql_error()); } else{ echo "Successed to connect MySQL."; } echo "<br />"; // 创建数据库(database) if(mysql_query("CREATE DATABASE my_db", $connect)){ echo "Success to create database."; } else{ echo "Error to create database: " . mysql_error(); } echo "<br />"; // 创建表(table) mysql_select_db("my_db", $connect); $table_sql = "CREATE TABLE Persons( firstName VARCHAR(15), lastName VARCHAR(15), Age INT );"; if(mysql_query($table_sql)){ echo "Success to create table."; } else{ echo "Error to create table: " . mysql_error(); } echo "<br />"; // 添加数据 $insert_sql = "INSERT INTO Persons VALUES(‘Wayne‘, ‘Ng‘, ‘26‘)"; if(mysql_query($insert_sql)){ echo "Success to insert data."; } else{ echo "Error to insert data: " . mysql_error(); } echo "<br />"; // 查询结果并显示于html表格中 mysql_select_db("game_db", $connect); $result = mysql_query("SELECT * FROM game"); echo"<h2>冒险岛游戏数据</h2> <table border=‘1‘> <tr> <th>ID</th> <th>JOB_NAME</th> <th>WEAPONS</th> <th>SKILLS</th> <th>HERO_TYPES</th> </tr> "; while($row = mysql_fetch_array($result)){ echo "<tr>"; echo "<td>" . $row["id"]."</td>"; echo "<td>" . $row["job_name"]."</td>"; echo "<td>" . $row["weapons"]."</td>"; echo "<td>" . $row["skills"]."</td>"; echo "<td>" . $row["hero_type"]."</td>"; echo "</tr>"; } echo "</table>"; //终止连接 mysql_close($connect); ?>
显示效果:
例子6:Ajax简单例子
suggestion.html文件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>php basis-3</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="author" content="Wayne Ng" /> <meta name="description" content="name suggestion" /> <meta name="revised" content="Wayne Ng,2016/2/17" /> </head> <body> <h2>名字提示</h2> <p>显示以该英文开头的英文名</p> <form> First Name: <input type="text" id="txt1" onkeyup="showHint(this.value)"/> </form> <p>Suggestion:<span id="txtHint"></span></p> </body> <script src="clientHint.js"></script> </html>
clientHint.js文件:
var xmlHttp; //从对应php脚本发送请求并获取信息 function showHint(str){ if(str.length == 0){ document.getElementById("txtHint").innerHTML=""; return; } xmlHttp=GetXmlHttpObject(); //获得xmlhttp对象 if(xmlHttp == null){ alert("浏览器不支持HTTP请求"); return; } var url="getHint.php"; url = url + "?q=" + str + "&sid=" + Math.random(); xmlHttp.onreadystatechange=stateChanged; xmlHttp.open("GET", url, true); xmlHttp.send(null); } //AJAX对应处理函数 function stateChanged(){ if(xmlHttp.readyState == 4 || xmlHttp.readyState == "complete"){ document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } } //创建对应HTTP对象 function GetXmlHttpObject(){ var xmlHttp = null; try{ //FireFox, Opera 8.0+, Safari xmlHttp = new XMLHttpRequest(); } catch(e){ //IE try{ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } return xmlHttp; }
getHint.php文件:
<?php // Fill up array with names $a[]="Anna"; $a[]="Brittany"; $a[]="Cinderella"; $a[]="Diana"; $a[]="Eva"; $a[]="Fiona"; $a[]="Gunda"; $a[]="Hege"; $a[]="Inga"; $a[]="Johanna"; $a[]="Kitty"; $a[]="Linda"; $a[]="Nina"; $a[]="Ophelia"; $a[]="Petunia"; $a[]="Amanda"; $a[]="Raquel"; $a[]="Cindy"; $a[]="Doris"; $a[]="Eve"; $a[]="Evita"; $a[]="Sunniva"; $a[]="Tove"; $a[]="Unni"; $a[]="Violet"; $a[]="Liza"; $a[]="Elizabeth"; $a[]="Ellen"; $a[]="Wenche"; $a[]="Vicky"; //从URL中获取q的参数 $q=$_GET["q"]; //从字典中查找以$q开头的英文,并生成结果 if (strlen($q) > 0) { $hint=""; for($i=0; $i<count($a); $i++) { if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q)))) { if ($hint=="") { $hint=$a[$i]; } else { $hint=$hint." , ".$a[$i]; } } } } //判断$hint是否为空,并返回对应结果 if ($hint == "") { $response="no suggestion"; } else { $response=$hint; } //输出响应 echo $response; ?>
显示效果:
修订于2016/2/20 By野马菌
自学php的几个例子(包含AMP(Apache、MySQL、PHP)环境搭建链接)
标签:
原文地址:http://www.cnblogs.com/yemajun/p/5203221.html