基础语法
大小写敏感
用户定义的函数、类和关键词都对大小写不敏感。
(例如 if、else、echo 等等)
变量都对大小写敏感
变量作用域
local 函数
函数内部声明的变量拥有 LOCAL 作用域,只能在函数内部进行访问。
global 函数
函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。
static
关键字
lobal 在函数内访问全局变量
static 函数完成/执行后,不删除某个局部变量
echo 和 print 语句
echo - 能够输出一个以上的字符串
print - 只输出一个字符串,并且始终返回1
echo 是一个语言结构,有无括号均可使用。
拼接字符串
echo “This”, " string", " was", " made", " with multiple parameters.";
if …else
<?php
$t=date("H");
if ($t<"10") {
echo "Have a good morning!";
} elseif ($t<"20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
switch
<?php
$favfruit="orange";
switch ($favfruit) {
case "apple":
echo "Your favorite fruit is apple!";
break;
case "banana":
echo "Your favorite fruit is banana!";
break;
case "orange":
echo "Your favorite fruit is orange!";
break;
default:
echo "Your favorite fruit is neither apple, banana, or orange!";
}
?>
for
<?php
for ($x=0; $x<=10; $x++) {
echo "数字是:$x <br>";
}
?>
Foreach
<?php
$colors = array("red","green","blue","yellow");
foreach ($colors as $value) {
echo "$value <br>";
}
?>
数组
创建数组 - array()
array();
数组类型|索引 - 关联 - 多维
-
索引数组 - 带有数字索引的数组
-
关联数组 - 带有指定键的数组
<?php $age=array("Bill"=>"63","Steve"=>"56","Elon"=>"47"); echo "Elon is " . $age['Elon'] . " years old."; ?>
遍历关联数组 - foreach()
-
多维数组* - 包含一个或多个数组的数组
获得数组的长度 - count()
排序函数
- sort() - 以升序对数组排序
- rsort() - 以降序对数组排序
- asort() - 根据值,以升序对关联数组进行排序
- ksort() - 根据键,以升序对关联数组进行排序
- arsort() - 根据值,以降序对关联数组进行排序
- krsort() - 根据键,以降序对关联数组进行排序
全局变量
PHP 中的许多预定义变量都是“超全局的”,这意味着它们在一个脚本的全部作用域中都可用。在函数或方法中无需执行 global $variable; 就可以访问它们。
这些超全局变量是:
- $GLOBALS
- $_SERVER
- $_REQUEST
- $_POST
- $_GET
- $_FILES
- $_ENV
- $_COOKIE
- $_SESSION
$GLOBALS — 引用全局作用域中可用的全部变量
$GLOBALS 这种全局变量用于在 PHP 脚本中的任意位置访问全局变量(从函数或方法中均可)。
PHP 在名为 $GLOBALS[index] 的数组中存储了所有全局变量。变量的名字就是数组的键。
下面的例子展示了如何使用超级全局变量 $GLOBALS:
实例
<?php
$x = 75;
$y = 25;
function addition() {
$GLOBALS['z'] = $GLOBALS['x'] + $GLOBALS['y'];
}
addition();
echo $z;
?>
表单
表单验证
表单元素 - $_SERVER[“PHP_SELF”]
$_SERVER[“PHP_SELF”] 是一种超全局变量,它返回当前执行脚本的文件名。
htmlspecialchars() 函数
htmlspecialchars() 函数把特殊字符转换为 HTML 实体。这意味着 < 和 > 之类的 HTML 字符会被替换为 < 和 > 。这样可防止攻击者通过在表单中注入 HTML 或 JavaScript 代码(跨站点脚本攻击)对代码进行利用。
验证表单数据
#####(通过 PHP trim() 函数)去除用户输入数据中不必要的字符(多余的空格、制表符、换行)
#####(通过 PHP stripslashes() 函数)删除用户输入数据中的反斜杠(\)
<!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">
表单必填
验证输入字段
<?php
// 定义变量并设置为空值
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} 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 = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
显示错误信息
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
实例
<!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">
表单 URL/E-mail
验证名字
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "只允许字母和空格!";
}
**注释:**preg_match() 函数检索字符串的模式,如果模式存在则返回 true,否则返回 false。
验证 E-mail
$email = test_input($_POST["email"]);
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "无效的 email 格式!";
}
验证URL
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%
=~_|]/i",$website)) {
$websiteErr = "无效的 URL";
}
实例
<?php
// 定义变量并设置为空值
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// 检查名字是否包含字母和空格
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// 检查电邮地址语法是否有效
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
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 = "Invalid URL";
}
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>
完成表单验证
保留表中的值
Name: <input type="text" name="name" value="<?php echo $name;?>">
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
Website: <input type="text" name="website" value="<?php echo $website;?>">
Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>
Gender:
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male
完整实例
<!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">
PHP 高级
date()
- d - 表示月里的某天(01-31)
- m - 表示月(01-12)
- Y - 表示年(四位数)
- 1 - 表示周里的某天
- h - 带有首位零的 12 小时小时格式
- i - 带有首位零的分钟
- s - 带有首位零的秒(00 -59)
- a - 小写的午前和午后(am 或 pm)
PHP 自动版权年份 - date(“Y”)
© 2010-<?php echo date("Y")?>
获得时区 - date_default_timezone_set();
<?php
date_default_timezone_set("Asia/Shanghai");
echo "当前时间是 " . date("h:i:sa");
?>
PHP mktime() 创建日期
mktime() 函数返回日期的 Unix 时间戳。Unix 时间戳包含 Unix 纪元(1970 年 1 月 1 日 00:00:00 GMT)与指定时间之间的秒数。
mktime(hour,minute,second,month,day,year)
<?php
$d=mktime(9, 12, 31, 6, 10, 2015);
echo "创建日期是 " . date("Y-m-d h:i:sa", $d);
?>
PHP strtotime() 用字符串来创建日期
strtotime(time,now)
<?php
$d=strtotime("10:38pm April 15 2015");
echo "创建日期是 " . date("Y-m-d h:i:sa", $d);
?>
实例
<?php
$d=strtotime("tomorrow");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("next Saturday");
echo date("Y-m-d h:i:sa", $d) . "<br>";
$d=strtotime("+3 Months");
echo date("Y-m-d h:i:sa", $d) . "<br>";
?>
<?php
$startdate = strtotime("Saturday");
$enddate = strtotime("+6 weeks",$startdate);
while ($startdate < $enddate) {
echo date("M d", $startdate),"<br>";
$startdate = strtotime("+1 week", $startdate);
}
?>
<?php
$d1=strtotime("December 31");
$d2=ceil(($d1-time())/60/60/24);
echo "距离十二月三十一日还有:" . $d2 ." 天。";
?>
include 文件
- require 会生成致命错误(E_COMPILE_ERROR)并停止脚本
- include 只生成警告(E_WARNING),并且脚本会继续
<html>
<body>
<h1>欢迎访问我们的首页!</h1>
<p>一段文本。</p>
<p>一段文本。</p>
<?php include 'footer.php';?>
</body>
</html>
readfile() 函数
读取此文件并写到输出流
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
fgets() - 读取首行文件
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
End-Of-File - feof() - PHP 检查
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// 输出单行直到 end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>
文件上传
<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>
Cookies
setcookie() 函数用于设置 cookie。
**注释:**setcookie() 函数必须位于 标签之前。
setcookie(name, value, expire, path, domain);
<?php
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
<body>
</body>
</html>
session
存储 Session 变量
<?php
session_start();
// store session data
$_SESSION['views']=1;
?>
<html>
<body>
<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>
</body>
</html>
PHP 防止 E-mail 注入
假如用户在表单中的输入框内加入这些文本,会出现什么情况呢?
someone@example.com%0ACc:person2@example.com
%0ABcc:person3@example.com,person3@example.com,
anotherperson4@example.com,person5@example.com
%0ABTo:person6@example.com
与往常一样,mail() 函数把上面的文本放入邮件头部,那么现在头部有了额外的 Cc:, Bcc: 以及 To: 字段。当用户点击提交按钮时,这封 e-mail 会被发送到上面所有的地址!
<html>
<body>
<?php
function spamcheck($field)
{
//filter_var() sanitizes the e-mail
//address using FILTER_SANITIZE_EMAIL
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
//filter_var() validates the e-mail
//address using FILTER_VALIDATE_EMAIL
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['email']))
{//if "email" is filled out, proceed
//check if the email address is invalid
$mailcheck = spamcheck($_REQUEST['email']);
if ($mailcheck==FALSE)
{
echo "Invalid input";
}
else
{//send email
$email = $_REQUEST['email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
mail("someone@example.com", "Subject: $subject",
$message, "From: $email" );
echo "Thank you for using our mail form";
}
}
else
{//if "email" is not filled out, display the form
echo "<form method='post' action='mailform.php'>
Email: <input name='email' type='text' /><br />
Subject: <input name='subject' type='text' /><br />
Message:<br />
<textarea name='message' rows='15' cols='40'>
</textarea><br />
<input type='submit' />
</form>";
}
?>
</body>
</html>
- FILTER_SANITIZE_EMAIL 从字符串中删除电子邮件的非法字符
- FILTER_VALIDATE_EMAIL 验证电子邮件地址
错误提示
<?php
//error handler function
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br />";
echo "Webmaster has been notified";
error_log("Error: [$errno] $errstr",1,
"someone@example.com","From: webmaster@example.com");
}
//set error handler
set_error_handler("customError",E_USER_WARNING);
//trigger error
$test=2;
if ($test>1)
{
trigger_error("Value must be 1 or below",E_USER_WARNING);