php 语法

PHP语言简介:

CLI:(Command-Line Interface)与Linux Shell语言类似,作为后台可执行脚本的解决方案,用于后台脚本编程。

mod_php或fastCGI:用于网络应用编程,开发网站或者互联网应用,被称为网络(Web)脚本模式,LAMP:Linux Apache MySQL PHP/Perl/Python


规范:

PHP代码部分需要用<?php ...?>括号框起来,类似于ASP或者JSP,实际开发中可以把“?>”去掉。


注释:

单行:“//”或者“#”,多行:“/* ... */”


变量:

所有变量以”$“符号开始,变量命名与C++和java相同,PHP是弱类型语言不需要声明变量类型


常量:

使用define函数定义,类似于C和C++语言,变量名一般使用全大写字母


函数:

比如:”function hello(){ ... }“

<html>
<body>

<?php
function add($x,$y)
  {
  $total = $x + $y;
  return $total;
  }

echo "1 + 16 = " . add(1,16);
?>

</body>
</html>


类定义:

和Java基本类似,比如”public class User{ ... }“


包含文件:

require和clude方法包含,避免重复包含使用require_once和include_once方法

"menu.php":

echo '<a href="/default.php">Home</a>
<a href="/tutorials.php">Tutorials</a>
<a href="/references.php">References</a>
<a href="/examples.php">Examples</a>
<a href="/about.php">About Us</a>
<a href="/contact.php">Contact Us</a>';
<html>
<body>

<div class="leftmenu">
<?php include 'menu.php'; ?>
</div>

<h1>Welcome to my home page.</h1>
<p>Some text.</p>

</body>
</html>


命名空间:

比如:"namespace Core/Lib1"


预定义变量:

PHP提供大量预定义变量(预定义数组变量),用于存储来自服务器,运行环境和输入数据等动态信息,不同于其他语言对应的使用类包或者方法来获取的方式(如JAVA使用request.getParameter()方法,PHP会直接把所有的GET参数全部放到预定变量$_GET中)。

变量名环境作用
$GLOBALS引用全局作用域中可用的全部变量
$_SERVERWEB服务器和执行环境信息
$_GETWEBHTTP GET变量
$_POSTWEBHTTP POST变量
$_FILESWEBHTTP文件上传变量
$_COOKIEWEBHTTP Cookie
$_SESSIONWEBSession变量
$_REQUESTWEBHTTP Request 变量(包含了 $_GET, $_POST 以及 $_COOKIE 的内容。)
$_ENV系统环境变量
$http_reponse_headerWEBHTTP响应头
$argcCLI传递给脚本的参数数目
$argvCLI传递给脚本的参数数组


非 类型:PHP中null,false,0,空字符串,空数组之间可以画等号,也可以用===区别判断区别。

数值作用
null当变量未被赋值,则为null
0整型数值
false布尔类型
空字符串字符串' '和” “
空数组空数组Array()


魔术变量:(主要方便开发者调试PHP代码,魔术变量前后都有两个下划线)

__LINE__:返回文件中的当前行号

__FILE__:返回当前文件的完整路径和文件名

__DIR__:返回当前文件所在的目录

__FUNCTION__:返回当前函数的名称

__CLASS__:返回当前类的名称

__METHOD__:返回当前类的方法名

__NAMESPACE__:返回当前命名空间名

魔术方法:(主要解决PHP面向对象思想所遇到到的一些特殊情况,使用两个下划线开头)

__construct():通用的类构造函数

__destruct():通用的类析构造函数

__get(string $name):当试图读取一个并不存在的类属性时被调用

__set(string $name,mixed $value):给未定义的类变量赋值时被调用

__call(string $name,array $arguments):当调用一个不可访问类方法(如未定义或不可见)时,__call()被调用

__callStatic(string $name,array $arguments):当调用一个不可访问的静态方法时,__callStatic()方法会被调用

__toString():当打印一个类对象时被调用,这个方法类似与Java的toString 方法

__clone():当类对象被克隆时被调用

__sleep():持久话一个类对象时,如果__sleep()存在则先被调用,然后才执行序列化操作。这个功能可以用于清理对象,比如你有一些很大的对象,比如你有一些很大的对象

不需要持久化。

__wakeup():与__sleep()相反,在反持久化对象时,如果存在__wakeup()方法,则使用该方法预先准备对象数据。__wakeup()可用在类似于重新建立数据库连接等初始化操

作中。

__isset():当对未定义的类变量调用isset()或empty()时,__isset()会被调用

__unset():unset()一个对象的属性时被调用。如unset($class->name)

__invoke():当尝试以调用函数的方式调用一个对象时,__invoke()方法会被自动调用。

__autoload():区别于以上所有方法,并非是一个类方法,而是一个全局方法。在实例化一个对象时,如果对应的类不存在,则该方法被调用,可用于类的自动加载。

注意:所有的魔术方法都需要给予public属性。


数组:

有三种数组类型:

数值数组(创建方式以及使用)

$names = array("Peter","Quagmire","Joe");
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
<?php

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
?>

关联数组(创建方式以及使用)

$ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";
<?php

$ages['Peter'] = "32";
$ages['Quagmire'] = "30";
$ages['Joe'] = "34";

echo "Peter is " . $ages['Peter'] . " years old.";
?>

多维数组

$families = array
(
  "Griffin"=>array
  (
  "Peter",
  "Lois",
  "Megan"
  ),
  "Quagmire"=>array
  (
  "Glenn"
  ),
  "Brown"=>array
  (
  "Cleveland",
  "Loretta",
  "Junior"
  )
);
echo "Is " . $families['Griffin'][2] . 
" a part of the Griffin family?"; 

循环 while do..while for foreach 语句:

foreach 语句用于循环遍历数组。

每进行一次循环,当前数组元素的值就会被赋值给 value 变量(数组指针会逐一地移动) - 以此类推。

<html>
<body>

<?php
$arr=array("one", "two", "three");

foreach ($arr as $value)
{
  echo "Value: " . $value . "<br />";
}
?>

</body>
</html>

PHP 日期:

Date() 函数:date(format,timestamp)可把时间戳格式化为可读性更好的日期和时间。

<?php
echo date("Y/m/d");
echo "<br />";
echo date("Y.m.d");
echo "<br />";
echo date("Y-m-d");
?>
mktime() 函数可为指定的日期返回 Unix 时间戳。
<?php
$tomorrow = mktime(0,0,0,date("m"),date("d")+1,date("Y"));
echo "明天是 ".date("Y/m/d", $tomorrow);
?>

PHP 文件:

检测 End-of-file

if (feof($file)) echo "End of file";

逐行读取文件

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
  {
  echo fgets($file). "<br />";
  }
fclose($file);
?>

逐字符读取文件

<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file)) 
  { 
  echo fgetc($file); 
  }
fclose($file);
?>


PHP 文件上传 :
<?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";
  }
?>

PHP Cookies:

cookie 常用于识别用户。cookie 是服务器留在用户计算机中的小文件。每当相同的计算机通过浏览器请求页面时,它同时会发送 cookie。通过 PHP,您能够创建并取回 cookie 的值。

<?php 
setcookie("user", "Alex Porter", time()+3600);
?>

<html>
<body>

</body>
</html>
注释:setcookie() 函数必须位于 <html> 标签之前。

取回 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);
?>
不支持 cookie:

一种方式是从表单传递数据(POST)


PHP Sessions:

PHP session 变量用于存储有关用户会话的信息,或更改用户会话的设置。Session 变量保存的信息是单一用户的,并且可供应用程序中的所有页面使用。

当您运行一个应用程序时,您会打开它,做些更改,然后关闭它。这很像一次会话。计算机清楚你是谁。它知道你何时启动应用程序,并在何时终止。但是在因特网上,存在一个问题:服务器不知道你是谁以及你做什么,这是由于 HTTP 地址不能维持状态。
通过在服务器上存储用户信息以便随后使用,PHP session 解决了这个问题(比如用户名称、购买商品等)。不过,会话信息是临时的,在用户离开网站后将被删除。如果您需要永久储存信息,可以把数据存储在数据库中。
Session 的工作机制是:为每个访问者创建一个唯一的 id (UID),并基于这个 UID 来存储变量。UID 存储在 cookie 中,亦或通过 URL 进行传导。

开始 PHP Session

存储 Session 变量

<?php
session_start();
// store session data
$_SESSION['views']=1;
?>

<html>
<body>

<?php
//retrieve session data
echo "Pageviews=". $_SESSION['views'];
?>

</body>
</html>

终结 Session

unset() 函数用于释放指定的 session 变量:

<?php
unset($_SESSION['views']);
?>
您也可以通过 session_destroy() 函数彻底终结 session:(您将失去所有已存储的 session 数据。)

<?php
session_destroy();
?>


PHP 发送电子邮件:

<html>
<body>

<?php
if (isset($_REQUEST['email']))
//if "email" is filled out, send email
  {
  //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>

PHP 防止 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>

PHP 错误处理:

简单的 "die()" 语句:

<?php
if(!file_exists("welcome.txt"))
 {
 die("File not found");
 }
else
 {
 $file=fopen("welcome.txt","r");
 }
?>
自定义错误和错误触发器:
function customError($errno, $errstr)
 { 
 echo "<b>Error:</b> [$errno] $errstr<br />";
 echo "Ending Script";
 die();
 }
<?php
//error handler function
function customError($errno, $errstr)
 { 
 echo "<b>Error:</b> [$errno] $errstr";
 }

//set error handler
set_error_handler("customError");

//trigger error
echo($test);
?>
<?php
//error handler function
function customError($errno, $errstr)
 { 
 echo "<b>Error:</b> [$errno] $errstr<br />";
 echo "Ending Script";
 die();
 }

//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);
 }
?>

错误报告

<?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);
 }
?>


PHP 异常处理:

什么是异常?
PHP 5 提供了一种新的面向对象的错误处理方法。
异常处理用于在指定的错误(异常)情况发生时改变脚本的正常流程。这种情况称为异常。

当异常被触发时,通常会发生:
当前代码状态被保存
代码执行被切换到预定义的异常处理器函数
根据情况,处理器也许会从保存的代码状态重新开始执行代码,终止脚本执行,或从代码中另外的位置继续执行脚本

异常的基本使用:

创建自定义的异常处理器:

<?php
//创建可抛出一个异常的函数
function checkNum($number)
 {
 if($number>1)
  {
  throw new Exception("Value must be 1 or below");
  }
 return true;
 }

//在 "try" 代码块中触发异常
try
 {
 checkNum(2);
 //If the exception is thrown, this text will not be shown
 echo 'If you see this, the number is 1 or below';
 }

//捕获异常
catch(Exception $e)
 {
 echo 'Message: ' .$e->getMessage();
 }
?>

多个异常:

<?php
class customException extends Exception
{
public function errorMessage()
{
//error message
$errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
.': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
return $errorMsg;
}
}

$email = "someone@example.com";

try
 {
 //check if 
 if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
  {
  //throw exception if email is not valid
  throw new customException($email);
  }
 //check for "example" in mail address
 if(strpos($email, "example") !== FALSE)
  {
  throw new Exception("$email is an example e-mail");
  }
 }

catch (customException $e)
 {
 echo $e->errorMessage();
 }

catch(Exception $e)
 {
 echo $e->getMessage();
 }
?>

重新抛出异常:

如果在其目前的 "try" 代码块中异常没有被捕获,则它将在更高层级上查找 catch 代码块。


设置顶层异常处理器:

set_exception_handler() 函数可设置处理所有未捕获异常的用户定义函数。

<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}

set_exception_handler('myException');

throw new Exception('Uncaught Exception occurred');
?>

异常的规则

  • 需要进行异常处理的代码应该放入 try 代码块内,以便捕获潜在的异常。
  • 每个 try 或 throw 代码块必须至少拥有一个对应的 catch 代码块。
  • 使用多个 catch 代码块可以捕获不同种类的异常。
  • 可以在 try 代码块内的 catch 代码块中再次抛出(re-thrown)异常。

简而言之:如果抛出了异常,就必须捕获它。



PHP 过滤器(Filter):

如需过滤变量,请使用下面的过滤器函数之一:

filter_var() - 通过一个指定的过滤器来过滤单一的变量

filter_var_array() - 通过相同的或不同的过滤器来过滤多个变量

filter_input - 获取一个输入变量,并对它进行过滤

filter_input_array - 获取多个输入变量,并通过相同的或不同的过滤器对它们进行过滤

<?php
$int = 123;

if(!filter_var($int, FILTER_VALIDATE_INT))
 {
 echo("Integer is not valid");
 }
else
 {
 echo("Integer is valid");
 }
?>




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值