#安装需要的包,有依赖关系,自动帮你解决 yum install httpd mysql mysql-server php php-gd php-mbstring php-mysql #启动httpd service httpd start #设为开机启动 chkconfig httpd on #启动mysqld service mysqld start #设为开机启动 chkconfig mysqld on #在根目录下创建一个测试文件,写个phpinfo函数 vi /var/www/html/phpinfo.php
打开浏览器,输入http://ip/phpinfo.php,就可以看到phpinfo的输出页面了
phpinfo.php
<?
phpinfo();
?>
例子1:
表单处理(get)
welcome_get.html
<html> <body> <form action="welcome_get.php" method="get"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
welcome_get.php
<html> <body> Welcome <?php echo $_GET["name"]; ?><br> Your email address is: <?php echo $_GET["email"]; ?> </body> </html>
例子2:
表单处理(post)
welcome.html
<html> <body> <form action="welcome.php" method="post"> Name: <input type="text" name="name"><br> E-mail: <input type="text" name="email"><br> <input type="submit"> </form> </body> </html>
welcome.php
<html> <body> Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"]; ?> </body> </html>
例子3:
表单验证
<!DOCTYPE HTML> <html> <head> </head> <body> <?php // define variables and set to empty values $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { $name = test_input($_POST["name"]); $email = test_input($_POST["email"]); $website = test_input($_POST["website"]); $comment = test_input($_POST["comment"]); $gender = test_input($_POST["gender"]); } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP 验证实例</h2> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <br><br> 电邮:<input type="text" name="email"> <br><br> 网址:<input type="text" name="website"> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2>您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
例子4:
表单验证+必填字段:
<!DOCTYPE HTML> <html> <head> <style> .error {color: #FF0000;} </style> </head> <body> <?php // 定义变量并设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "姓名是必填的"; } else { $name = test_input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "电邮是必填的"; } else { $email = test_input($_POST["email"]); } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必选的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP 验证实例</h2> <p><span class="error">* 必需的字段</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> 电邮:<input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> 网址:<input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2>您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
例子5:
表单验证+必填字段+正则表达式验证:
<!DOCTYPE HTML> <html> <head> <style> .error {color: #FF0000;} </style> </head> <body> <?php // 定义变量并设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "姓名是必填的"; } else { $name = test_input($_POST["name"]); // 检查姓名是否包含字母和空白字符 if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "只允许字母和空格"; } } if (empty($_POST["email"])) { $emailErr = "电邮是必填的"; } else { $email = test_input($_POST["email"]); // 检查电子邮件地址语法是否有效 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "无效的 email 格式"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // 检查 URL 地址语法是否有效(正则表达式也允许 URL 中的斜杠) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "无效的 URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必选的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP 验证实例</h2> <p><span class="error">* 必需的字段</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> 电邮:<input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> 网址:<input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2>您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
例子6:
表单完整版本
<!DOCTYPE HTML> <html> <head> <style> .error {color: #FF0000;} </style> </head> <body> <?php // 定义变量并设置为空值 $nameErr = $emailErr = $genderErr = $websiteErr = ""; $name = $email = $gender = $comment = $website = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "姓名是必填的"; } else { $name = test_input($_POST["name"]); // 检查姓名是否包含字母和空白字符 if (!preg_match("/^[a-zA-Z ]*$/",$name)) { $nameErr = "只允许字母和空格"; } } if (empty($_POST["email"])) { $emailErr = "电邮是必填的"; } else { $email = test_input($_POST["email"]); // 检查电子邮件地址语法是否有效 if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) { $emailErr = "无效的 email 格式"; } } if (empty($_POST["website"])) { $website = ""; } else { $website = test_input($_POST["website"]); // 检查 URL 地址语法是否有效(正则表达式也允许 URL 中的斜杠) if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteErr = "无效的 URL"; } } if (empty($_POST["comment"])) { $comment = ""; } else { $comment = test_input($_POST["comment"]); } if (empty($_POST["gender"])) { $genderErr = "性别是必选的"; } else { $gender = test_input($_POST["gender"]); } } function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <h2>PHP 验证实例</h2> <p><span class="error">* 必需的字段</span></p> <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 姓名:<input type="text" name="name"> <span class="error">* <?php echo $nameErr;?></span> <br><br> 电邮:<input type="text" name="email"> <span class="error">* <?php echo $emailErr;?></span> <br><br> 网址:<input type="text" name="website"> <span class="error"><?php echo $websiteErr;?></span> <br><br> 评论:<textarea name="comment" rows="5" cols="40"></textarea> <br><br> 性别: <input type="radio" name="gender" value="female">女性 <input type="radio" name="gender" value="male">男性 <span class="error">* <?php echo $genderErr;?></span> <br><br> <input type="submit" name="submit" value="提交"> </form> <?php echo "<h2>您的输入:</h2>"; echo $name; echo "<br>"; echo $email; echo "<br>"; echo $website; echo "<br>"; echo $comment; echo "<br>"; echo $gender; ?> </body> </html>
例子7:
连接mysql并且输出数据:
<?php $conn=mysql_connect("localhost:3306", "root", "zhenchaowen"); mysql_query("set names 'utf8'"); if(!$conn){ die("could not connect to the database:</br>".mysql_error());//诊断连接错误 } $result=mysql_db_query("testdb001", "SELECT * FROM `customers`", $conn); // 获取查询结果 $row=mysql_fetch_row($result); echo '<font face="verdana">'; echo '<table border="1" cellpadding="1" cellspacing="2">'; // 显示字段名称 echo "</b><tr></b>"; for ($i=0; $i<mysql_num_fields($result); $i++) { echo '<td bgcolor="#000F00"><b>'. mysql_field_name($result, $i); echo "</b></td></b>"; } echo "</tr></b>"; // 定位到第一条记录 mysql_data_seek($result, 0); // 循环取出记录 while ($row=mysql_fetch_row($result)) { echo "<tr></b>"; for ($i=0; $i<mysql_num_fields($result); $i++ ) { echo '<td bgcolor="#00FF00">'; echo $row[$i]; echo '</td>'; } echo "</tr></b>"; } echo "</table></b>"; echo "</font>"; // 释放资源 mysql_free_result($result); // 关闭连接 mysql_close($conn); ?>
创建插入数据
<html> <body> <form action="insert.php" method="post"> Firstname: <input type="text" name="firstname" /> Lastname: <input type="text" name="lastname" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>
<?php $con = mysql_connect("localhost:3306", "root", "zhenchaowen"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("testdb001", $con); $sql="INSERT INTO Persons (FirstName, LastName, Age) VALUES ('$_POST[firstname]','$_POST[lastname]','$_POST[age]')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "1 record added"; mysql_close($con) ?>
删除数据
<?php $con = mysql_connect("localhost:3306", "root", "zhenchaowen"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("testdb001", $con); mysql_query("DELETE FROM Persons WHERE LastName='Griffin'"); mysql_close($con); ?>
更新数据
<?php $con = mysql_connect("localhost:3306", "root", "zhenchaowen"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("testdb001", $con); mysql_query("UPDATE Persons SET Age = '36' WHERE FirstName = 'Peter' AND LastName = 'Griffin'"); mysql_close($con); ?>
备注:测试前先检查下mysql连接设置:
/usr/bin/mysql -u root -p
例子8:(cookie处理)
创建cookie
<?php setcookie("user", "Alex Porter", time()+3600); ?> <html> <body> </body> </html>
获取cookie
<?php // Print a cookie echo $_COOKIE["user"]; // A way to view all cookies print_r($_COOKIE); ?>
<html> <body> <?php if (isset($_COOKIE["user"])) echo "Welcome " . $_COOKIE["user"] . "!<br />"; else echo "Welcome guest!<br />"; ?> </body> </html>
删除cookie
<?php // set the expiration date to one hour ago setcookie("user", "", time()-3600); ?>
例子9:(session处理)
开始session和存储session
<?php session_start(); // store session data $_SESSION['views']=1; ?> <html> <body> <?php //retrieve session data echo "Pageviews=". $_SESSION['views']; ?> </body> </html>
输出session中的数据
<?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views']=$_SESSION['views']+1; else $_SESSION['views']=1; echo "Views=". $_SESSION['views']; ?>
终结session
<?php
session_destroy();
?>
例子10:(文件上传)
<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
<?php if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?>
11.写文件:
<?php $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); $txt = "Bill Gates\n"; fwrite($myfile, $txt); $txt = "Steve Jobs\n"; fwrite($myfile, $txt); fclose($myfile); ?>
12.文件读取:
<!DOCTYPE html> <html> <body> <?php $myfile = fopen("upload/newfile.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("newfile.txt")); fclose($myfile); ?> </body> </html>
13.xml处理
13.1
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
<?php //Initialize the XML parser $parser=xml_parser_create(); //Function to use at the start of an element function start($parser,$element_name,$element_attrs) { switch($element_name) { case "NOTE": echo "-- Note --<br />"; break; case "TO": echo "To: "; break; case "FROM": echo "From: "; break; case "HEADING": echo "Heading: "; break; case "BODY": echo "Message: "; } } //Function to use at the end of an element function stop($parser,$element_name) { echo "<br />"; } //Function to use when finding character data function char($parser,$data) { echo $data; } //Specify element handler xml_set_element_handler($parser,"start","stop"); //Specify data handler xml_set_character_data_handler($parser,"char"); //Open XML file $fp=fopen("test.xml","r"); //Read data while ($data=fread($fp,4096)) { 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))); } //Free the XML parser xml_parser_free($parser); ?>
13.2
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
<?php $xmlDoc = new DOMDocument(); $xmlDoc->load("note.xml"); $x = $xmlDoc->documentElement; foreach ($x->childNodes AS $item) { print $item->nodeName . " = " . $item->nodeValue . "<br />"; } ?>
13.3
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note>
<?php $xml = simplexml_load_file("test2.xml"); echo $xml->getName() . "<br />"; foreach($xml->children() as $child) { echo $child->getName() . ": " . $child . "<br />"; } ?>
查看host绑定:
mysql> SELECT User, Host, Password FROM mysql.user; +-------------+-----------------------+-------------------------------------------+ | User | Host | Password | +-------------+-----------------------+-------------------------------------------+ | root | localhost | *232BC6F0ED82F0AD17B03A53D4062D2951F1A1E4 | | root | localhost.localdomain | *232BC6F0ED82F0AD17B03A53D4062D2951F1A1E4 | | root | 127.0.0.1 | *232BC6F0ED82F0AD17B03A53D4062D2951F1A1E4 | | demouser | localhost | *0756A562377EDF6ED3AC45A00B356AAE6D3C6BB6 | | zhenchaowen | 192.168.1.105 | *232BC6F0ED82F0AD17B03A53D4062D2951F1A1E4 | +-------------+-----------------------+-------------------------------------------+ 5 rows in set (0.01 sec) mysql>
php解析器测试:
[root@localhost cgi-bin]# php hello3.php PHP Deprecated: Comments starting with '#' are deprecated in /etc/php.ini on line 693 in Unknown on line 0 PHP Warning: Directive 'register_globals' is deprecated in PHP 5.3 and greater in Unknown on line 0 <font face="verdana"><table border="1" cellpadding="1" cellspacing="2"></b><tr></b><td bgcolor="#000F00"><b>id</b></td></b><td bgcolor="#000F00"><b>CompanyName</b></td></b><td bgcolor="#000F00"><b>ContactName</b></td></b></tr></b><tr></b><td bgcolor="#00FF00">1</td><td bgcolor="#00FF00">ssss</td><td bgcolor="#00FF00">sss</td></tr></b><tr></b><td bgcolor="#00FF00">2</td><td bgcolor="#00FF00">ddd</td><td bgcolor="#00FF00">dddd</td></tr></b></table></b></font>
经过上述的步骤,传说中的LAMP架构就这样搭建完成了
顺便提下
yum install httpd
安装的httpd配置在/etc/httpd/conf/httpd.conf 中
如:
ServerName localhost:80
Listen 192.168.1.112:80