阿赛·游梦鱼·郭言赛·阿赛工作室
技术分类
推荐技术
近期热门技术

PHP学习第二课

  •  字体:
  • PHP 多维数组
    <?php
    header("Content-type:text/html;charset=UTF-8");

    $cars = array
       (
       array("Volvo",33,20),
       array("BMW",17,15),
       array("Saab",5,2),
       array("Land Rover",15,11)
       );
       
    echo $cars[0][0].": 库存:".$cars[0][1].", 已售:".$cars[0][2].".<br>";
    echo $cars[1][0].": 库存:".$cars[1][1].", 已售:".$cars[1][2].".<br>";
    echo $cars[2][0].": 库存:".$cars[2][1].", 已售:".$cars[2][2].".<br>";
    echo $cars[3][0].": 库存:".$cars[3][1].", 已售:".$cars[3][2].".<br>";
    ?>

    PHP 日期和时间
    <?php
    date_default_timezone_set("Asia/Shanghai");//规定显示的时区
    echo "标准时间显示 " . date("Y-m-d H-i-s") . "<br>";

    $d=mktime(9, 12, 31, 6, 10, 2015);//mktime(hour,minute,second,month,day,year)
    echo "创建日期是 " . date("Y-m-d h:i:sa", $d);

    $d=strtotime("10:38pm April 15 2015");//把人类可读的字符串转换为 Unix 时间。
    echo "创建日期是 " . date("Y-m-d h:i:sa", $d);
    $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>";

    $startdate = strtotime("Saturday");
    $enddate = strtotime("+6 weeks",$startdate);
    while ($startdate < $enddate) {
    echo date("M d", $startdate),"<br>";
    $startdate = strtotime("+1 week", $startdate);
      
    $d1=strtotime("December 31");
    $d2=ceil(($d1-time())/60/60/24);
    echo "距离十二月三十一日还有:" . $d2 ." 天。";
    }
    ?>
    PHP Include 文件
    <?php //include 'footer.php';//include 与 require 有一个巨大的差异:如果用 include 语句引用某个文件并且 PHP 无法找到它,脚本会继续执行:?>
    PHP 文件处理
    <?php
    echo file_get_contents("ceshi.txt");//注意读取文件的编码
    //echo readfile("ceshi.txt");

    $myfile = fopen("ceshi.txt", "r") or die("Unable to open file!");
    echo '<br>逐行读取:';
    while(!feof($myfile)) {
      echo fgets($myfile) . "<br>";
    }
    $myfile = fopen("ceshi.txt", "r") or die("Unable to open file!");
    echo '<br>逐个字符读取:';
    while(!feof($myfile)) {
      echo fgetc($myfile);
    }
    $myfile = fopen("ceshi.txt", "r") or die("Unable to open file!");
    echo '<br>首行:'.fgets($myfile);
    echo '<br>全部内容:'.fread($myfile,filesize("ceshi.txt"));
    fclose($myfile);

    $myfile = fopen("ceshi.txt", "w") or die("Unable to open file!");
    $txt = date("Y-m-d H-i-s")."\n";
    fwrite($myfile, $txt);
    $d=strtotime("tomorrow");
    $txt = date("Y-m-d H-i-s",$d)."\n";
    fwrite($myfile, $txt);
    fclose($myfile);

    echo file_put_contents("ceshi.txt",date("Y-m-d H-i-s",$d)."尾部添加内容\n");//注意读取文件的编码

    ?>
    PHP 文件上传
    <?php
    //echo $_FILES["file"]["size"];
    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/pjpeg"))
    && ($_FILES["file"]["size"] < 200000))
      {
      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";
      }
    ?>
    <form action="" 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>

    PHP Cookies
    <?php
    setcookie("user", "Guo Yansai", time()+3600);
    setcookie("home", "JiangSu", time()+3600);

    // Print a cookie
    if (isset($_COOKIE["user"])){echo $_COOKIE["user"];}

    // A way to view all cookies
    print_r($_COOKIE);
    // set the expiration date to one hour ago
    setcookie("user", "", time()-3600);//del cookie
    ?>

    PHP Sessions
    <?php
    session_start();//session_start() 函数必须位于 <html> 标签之前

    if(isset($_SESSION['views']))
      $_SESSION['views']=$_SESSION['views']+1;

    else
      $_SESSION['views']=1;

    echo "Views=". $_SESSION['views'];

    unset($_SESSION['views']);//unset() 函数用于释放指定的 session 变量
    session_destroy();//将重置 session,您将失去所有已存储的 session 数据。destroy
    ?>

    PHP 发送电子邮件
    <?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=''>
      Email: <input name='email' type='text' value='asai@eesai.com' /><br />
      Subject: <input name='subject' type='text'  value='test我的邮件'/><br />
      Message:<br />
      <textarea name='message' rows='15' cols='40'>是的
      </textarea><br />
      <input type='submit' />
      </form>";
      }
    ?>

    PHP 错误处理
    <?php
    if(!file_exists("welcome.txt"))
     {
     die("File not found");
     }
    else
     {
     $file=fopen("welcome.txt","r");
     }
    //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,
     "asai@eesai.com","From: asai@02590.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
    class customException extends Exception
     {
     public function errorMessage()
      {
      //error message
      $errorMsg = $this->getMessage().' is not a valid E-Mail address.';
      return $errorMsg;
      }
     }

    $email = "someone@example.com";

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

    catch (customException $e)
     {
     //display custom message
     echo $e->errorMessage();
     }
    ?>

    PHP 过滤器(Filter)
    <?php
    $filters = array
     (
     "name" => array
      (
      "filter"=>FILTER_SANITIZE_STRING
      ),
     "age" => array
      (
      "filter"=>FILTER_VALIDATE_INT,
      "options"=>array
       (
       "min_range"=>1,
       "max_range"=>120
       )
      ),
     "email"=> FILTER_VALIDATE_EMAIL,
     );

    $result = filter_input_array(INPUT_GET, $filters);

    if (!$result["age"])
     {
     echo("Age must be a number between 1 and 120.<br />");
     }
    elseif(!$result["email"])
     {
     echo("E-Mail is not valid.<br />");
     }
    else
     {
     echo("User input is valid");
     }
    ?>

    Powered by eesai.Com ©  2018  阿赛工作室 All Rights Reserved
    本网站由 阿赛工作室 提供源代码技术支持.  备案号:苏ICP备08114364号

    网站地图建议反馈MapRssXml回到顶部