PHP高级语法总结

高级教程

1. 二维数组

function demo() {
      $cars = array(
        array("aaa",1, 11),
        array("bbb",2, 22),
        array("ccc",3, 33),
        array("ddd",4, 44),
      );

      print_r($cars);
      echo $cars[0][1];

      for ($row = 0; $row < count($cars); $row++) {
        echo "<p><b>Row number $row</b></p>";
        echo "<ul>";
        for ($col = 0; $col < count($cars[$row]); $col++) {
          echo "<li>{$cars[$row][$col]}.</li>";
        };
        echo "</ul>";
      }
    }
    // demo();

2. 日期

2.1 date(format, timestamp): 函数把时间戳格式化为更易读的日期和时间,返回服务器的当前日期/时间,当设置时区,则返回时区的日期时间
参数format:
* d - 表示月里的某一天
* m - 表示月(01-12)
* Y - 表示年(四位数)
* l - 表示周里的某天
* h - 带有首位零的12小时格式
* i - 带有首位零的分钟
* s - 带有首位零的秒(00-59)
* a - 小写的午前和午后(am或pm)
2.2 mktime(hour, minute, second, month, day, year): 创建日期
2.3 strtotime(time, now): 把人类可读的字符串转换为Unix时间,time参数非常灵活

function demo2() {
      echo "今天是".date("Y/m/d-l")."<br>";
      echo "现在的时间是".date("h:i:s-a")."<br>";
      echo "<hr>";
      
      $d = mktime(9, 12, 31, 6, 10, 2015);
      echo "创建的日期是".date("Y-m-d h:i:s-a", $d)."<br>";
      echo "<hr>";

      $f = strtotime("10:38pm April 15 2015");
      echo "创建的日期是".date("Y-m-d h:i:s-a", $f)."<br>";
      echo "<hr>";

      $f2 = strtotime();
    }
    // demo2();

3. 包含资源

3.1 include和require: 可以将 PHP 文件的内容插入另一个 PHP 文件(在服务器执行它之前)
3.2 区别:require 会生成致命错误(E_COMPILE_ERROR)并停止脚本;include 只生成警告(E_WARNING),并且脚本会继续
3.3 注释:请在此时使用 require:当文件被应用程序请求时;请在此时使用 include:当文件不是必需的,且应用程序在文件未找到时应该继续运行时

function demo3() {
      echo "开始引入资源<br>";
      require './common/footer.php';   // 若发生错误,终止脚本
      // include './common/footer.php';   // 若发生错误,不终止脚本,继续执行
      echo "<br>引入资源成功-".$test;
    }
    // demo3();

4. 文件操作

/**
     * 文件操作
     * 1. readfile(path): 读取文件,并把它写入输出缓冲,返回读取字节数
     * 2. fopen(path, mode): 打开文件,返回文件资源句柄; path为资源路径,mode为打开文件的模式; 
     * 3. 参数mode:
     *  r - 打开文件为只读。文件指针在文件的开头开始
     *  w - 打开文件为只写。删除文件的内容或创建一个新的文件,如果它不存在。文件指针在文件的开头开始
     *  a - 打开文件为只写。文件中的现有数据会被保留。文件指针在文件结尾开始。创建新的文件,如果文件不存在
     *  x - 创建新文件为只写。返回 FALSE 和错误,如果文件已存在
     *  r+ - 打开文件为读/写、文件指针在文件开头开始
     *  w+ - 打开文件为读/写。删除文件内容或创建新文件,如果它不存在。文件指针在文件开头开始
     *  a+ - 打开文件为读/写。文件中已有的数据会被保留。文件指针在文件结尾开始。创建新文件,如果它不存在
     *  x+ - 创建新文件为读/写。返回 FALSE 和错误,如果文件已存在
     * 4. fread(文件资源句柄, maxsize): 读取文件
     * 5. fclose(文件资源句柄): 关闭打开的文件
     * 6. fgets(文件资源句柄): 从文件读取单行
     * 7. fgetc(文件资源句柄): 逐个字符读取
     * 8. fseek(文件资源句柄, index): 设置文件指针到指定位置
     * 9. feof(): 检查是否已到达"end-of-file"
     * 11. file_exists(path): 检查文件或目录是否存在
     * 12. fwrite(文件资源句柄, write_str): 用于写入文件;参数write_str用于写入的字符串
     */
    function demo4() {
      // 读取文件
      $path = "./common/webdictinary.txt";
      $txt = readfile($path);
      echo "<br>";
      echo "common/webdictinary.txt读取字节数{$txt}";
      echo "<br><hr>";
      
      // 读取文件
      $myfile = fopen($path, "r") or die("Unable to open file!");
      echo fread($myfile, filesize($path));
      fseek($myfile,0);
      echo "<br><hr>";
      echo fgets($myfile);
      echo "<br><hr>";
      fseek($myfile, 0);
      while(!feof($myfile)) {
        echo fgets($myfile);
      }
      echo "<br><hr>";
      fseek($myfile, 0);
      while(!feof($myfile)) {
        echo fgetc($myfile);
      }
      fclose($myfile);
      echo "<br><hr>";

      // 创建/写入文件
      $new_path = "./common/new.txt";
      if(file_exists($new_path)) {
        $new_file = fopen($new_path, 'a+');
      } else {
        $new_file = fopen($new_path, 'w+');
      }
      $write_str = "这是一个写入字符串\n";
      fwrite($new_file, $write_str);

      $write_str = "这是一个新写入字符串\n";
      fwrite($new_file, $write_str);
      
      readfile($new_path);
      fclose($new_file);
    }
    // demo4();

5. Cookies

/**
     * Cookies
     * 1. 概述:常用于识别用户。cookie是服务器留在用户计算机中的小文件。每当相同的计算机通过浏览器请求页面时,它同时会发送cookie
     * 2. setcookie(name, value, expire, path, domain): 设置cookie;setrawcookie()防止cookie值自动url编码
     * 3. 删除cookie只需要设置过期时间为过去的时间点就可以了
     * 4. session_destroy(): 清除所有session; 也可以使用unset()清除某一个
     */
    function demo5() {
      setcookie("user", "Alex Porter", time() + 3600*1000);

      if(isset($_COOKIE["user"])) {
        print_r($_COOKIE["user"]);
      } else {
        print_r($_COOKIE);
      }
      
    }
    // demo5();

6. Session

/**
     * Session
     * 1. 工作机制: 为每个访问者创建一个唯一的 id (UID),并基于这个 UID 来存储变量。UID 存储在 cookie 中,亦或通过 URL 进行传导
     * 2. 结束生命周期: 会话信息是临时的,在用户离开网站后将被删除
     */
    function demo6() {
      session_start();
      
      if(isset($_SESSION['views'])) {
        $_SESSION['views'] += 1;
      } else {
        $_SESSION['views']=1;
      }

      print_r($_SESSION['views']);

      if($_SESSION['views'] > 7) {
        session_destroy();
      }
    }
    // demo6();

6. 定义错误处理程序

/**
     * 定义错误处理程序
     * 1. 定义错误处理程序error_function(error_level,error_message,error_file,error_line,error_context)
     * 2. 参数error_level错误报告级别数值:
     *  2 - E_WARNING(非致命的 run-time 错误。不暂停脚本执行)
     *  8 - E_NOTICE(Run-time 通知,脚本发现可能有错误发生,但也可能在脚本正常运行时发生)
     *  256 - E_USER_ERROR(致命的用户生成的错误。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_ERROR)
     *  512 - E_USER_WARNING(非致命的用户生成的警告。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_WARNING)
     *  1024 - E_USER_NOTICE(用户生成的通知。这类似于程序员使用 PHP 函数 trigger_error() 设置的 E_NOTICE)
     *  4096 - E_RECOVERABLE_ERROR(可捕获的致命错误。类似 E_ERROR,但可被用户定义的处理程序捕获(参见 set_error_handler())
     *  8191 - E_ALL(所有错误和警告,除级别 E_STRICT 以外)
     */
    function customError($errno, $errstr, $errfile, $errline, $errcontext) {
      // echo "<b>Error:</b> [$errno] $errstr <br>";
      // echo "[$errfile] $errline  <br>";
      print_r($errcontext);
      echo "<br>Ending Scriptsss";
      error_log("Error: [$errno] $errstr");
      die();
    }
    
    /**
     * Error
     * 1. die(): 和exit()相同,die多用于错误信息输出,exit多用于提前程序执行结束
     * 2. set_error_handler(): 设置错误发生时的回调
     * 3. trigger_error(): 主动触发错误
     * 4. error_log(error,type,destination,headers): 记录错误信息到php.ini中的error_log配置文件下
     */
    function demo8() {
      $path = "welcome.txt";
      set_error_handler("customError");
      /*
      if(!file_exists($path)) {
        die("File not found");
      } else {
        $file = fopen($path, "r");
      }
      */

      /*
      $path23 = "welcssssomes.txt";
      fopen($path23, "r");
      */

      echo "<br><hr>";
      $test=2;
      if ($test>1) {
        trigger_error("Value must be 1 or below");
      }
    }
    // demo8();

7. Exception

/**
     * Exception
     * 1. set_exception_handler(函数): 设置顶层异常处理器
     */
    function demo9() {

      class customException extends Exception {
        public function errorMessage() {
          $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
          .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
          return $errorMsg;
        }
      }
      
      function checkNum($number) {
        if($number > 1) {
          // throw new Exception("Value must be 1 or below");
          throw new customException("Value must be 11111 or below");
        } else {
          return true;
        }
      }
      try{
        checkNum(2);
      }catch(Exception $e) {
        // echo 'Message: ' .$e->getMessage();
        echo 'Message: ' .$e->errorMessage();   //自定义异常处理方法
      }

    }
    // demo9();

8. Filter过滤器

/**
     * Filter
     * 1. 外部数据: 来自表单的输入数据、Cookies、服务器变量、数据库查询结果等等
     * 2. filter_var() - 通过一个指定的过滤器来过滤单一的变量
     * 3. filter_var_array() - 通过相同的或不同的过滤器来过滤多个变量
     * 4. filter_input - 获取一个输入变量,并对它进行过滤
     * 5. filter_input_array - 获取多个输入变量,并通过相同的或不同的过滤器对它们进行过滤
     */
    function demo10() {
      $int = "s23";

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

      $var=300;

      $int_options = array(
      "options"=>array
      (
      "min_range"=>0,
      "max_range"=>256
      )
      );

      if(!filter_var($var, FILTER_VALIDATE_INT, $int_options))
      {
      echo("Integer is not valid");
      }
      else
      {
      echo("Integer is valid");
      }

      echo "<br>";

      // 使用自定义过滤器
      function convertSpace($string) {
        return str_replace("_", " ", $string);
      }

      $string = "v_o_Li";
      // options为过滤规则,必须为一个数组
      echo filter_var($string, FILTER_CALLBACK, array("options"=> "convertSpace"));
    }
    demo10();

11. $_FILES: 获取所有二进制数据流

#前端代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>文件/多文件上传</title>
</head>
<body>
  <form action="/demo/advanced/upload/upload.php" method="post" enctype="multipart/form-data">
    <label for="file">Filename:</label>
    <input type="file" name="img_file[]" id="file" multiple>
    <label for="file">name:</label>
    <input type="text" name="name" id="name">
    <br>
    <input type="submit" value="提交">
  </form>
</body>
</html>
#后端代码
<?php

  /**
   * $_FILES: 获取所有二进制数据流
   * move_uploaded_file(source_file, dest_file): 移动资源到目标资源地址 
   */

  header("Content-Type: text/html;charset=utf-8");

  echo "<pre>";

  print_r($_FILES);
  print_r($_POST);

  $img_type = $_FILES["img_file"]["type"][0];
  $img_size = $_FILES["img_file"]["size"][0];
  $img_error = $_FILES["img_file"]["error"][0];
  $img_name = $_FILES["img_file"]["name"][0];
  $img_tmp_name = $_FILES["img_file"]["tmp_name"][0];
  $limit_img_type = array("image/gif", "image/jpeg", "image/png");
  if (in_array($img_type, $limit_img_type) && $img_size < 200000) {
    if ($img_error > 0) {
      echo "Error: ".$img_error;
    } else {
      echo "name: ".$img_name."<br>";
      echo "type: ".$img_type."<br>";
      echo "tmp_name: ".$img_tmp_name."<br>";
      echo "error: ".$img_error."<br>";
      echo "size: ".($img_size/1024)."<br>";

      // 需要迭代判断路径中的文件或文件夹是否存在
      $upload_path = "upload_direcotry/".$img_name;
      if(file_exists($upload_path)) {
        echo $img_name."已存在";
      } else {
        move_uploaded_file($img_tmp_name, $upload_path);
        echo "Stored in: ".$upload_path;
      }
    }
  } else {
    echo "Invalid file";
  }

?>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值