$PHP_THREE

不言
Release: 2023-03-23 09:40:02
Original
1644 people have browsed it

This article introduces $PHP_THREE. The content is quite good. Friends in need can refer to it. Let’s take a look together


PHP_THREE

Usage of PhpStorm

Settings of PhpStorm


1. Set the default encoding character set

Path: Settings- >Editor->File Encodings

2. Display line number

Path: Editor->General->Appearance

3.Copyright information

/**
 * COPYRIGHT (C) ${YEAR} BY ${user} SOFTWARE. ALL RIGHTS RESERVED.
 *
 * @author:${user}
 * @date:${YEAR}/${MONTH}/${DAY}
 * @since:1.0
 * @description:
 */
Copy after login

4.Add PHP interpreter

Try to run the current PHP file. If the php interpreter is not added, it will prompt "interpreter is not specified or invalid" ", at this point, click Fix to add the php interpreter (php.exe).

Commonly used shortcut keys for PhpStorm

  • Ctrl j: Automatic code completion

  • Ctrl d: Copy the current Line

  • Shift 2: Quickly locate errors

  • Alt 1: Pop up file list

  • Ctrl g: Jump to the specified line

  • F4: Find the source of the variable

  • Ctrl y: Delete the current line

PhpStorm debugging use

  • step into [F7]: single-step execution, enter when encountering a sub-function and continue single-step execution (in short, enter the sub-function );

  • step over [F8]: During single-step execution, when a sub-function is encountered within a function, it will not enter the sub-function for single-step execution. Instead, the entire sub-function will be executed. Stop after execution, that is, treat the entire sub-function as one step. One thing, after our simple debugging, the effect is the same as step into when there is no sub-function (in short, the sub-function is skipped, but the sub-function will be executed).

  • step out: When single-stepping into a sub-function, use step out to execute the remaining part of the sub-function and return to the previous function.
    run to cursor Jump to the cursor position


Cookie

The cookie information will be saved in the form of a string

Session

The user opens a browser, clicks on multiple hyperlinks, accesses multiple web resources on the server, and then closes the browser. The entire process is called a session.

Problems to be solved

  • During a session, users will generate some data, such as shopping carts. When each user views the shopping cart, he will see that he has selected products, how is this achieved?

  • Why can some video websites save the record of the last time you watched?

  • How to save users How to save the last browsed information for a certain period of time without having to log in repeatedly?

Create cookie

<?php
    //演示如何创建cookie信息
    //把用户名和密码保存到客户端的cookie
    //1:key;2:value;3:interval(秒)

    setcookie("name", "hoki", time() + 10);//当前时间+10秒
    echo "保存成功";?>
Copy after login
  1. If you don’t add the third parameters, the cookie will not be saved to the client. When the browser session ends, our cookie will be invalid

  2. Cookie can only save strings

Get cookie information

    echo "<pre class="brush:php;toolbar:false">";
    print_r($_COOKIE);    echo "<pre class="brush:php;toolbar:false">";    //获取指定的key对应的值
    if(!empty($_COOKIE[&#39;name&#39;])){        echo $_COOKIE[&#39;name&#39;];        return;
    }    echo "cookie失效了";?>
Copy after login
  1. If the cookie validity time expires, it cannot be taken out;

  2. The cookie is transmitted to the server through the http protocol;

  3. The client can save multiple key-value pairs;

  4. The cookie can also save Chinese, and the Chinese will be urlencoded by default;

  5. Cookies can specify different validity times for different key-value pairs

Updating cookie information

means resetting cookies. Just like creating a cookie

Delete cookie information

To delete a cookie, you need to ensure that its expiration date is in the past before triggering the browser's deletion mechanism

  • Delete a specified key-value pair

<?php
    //如果要删除某个键,只需要把time()-秒数即可
    setcookie("name","",time()-200);    echo "删除name键成功";?>
Copy after login
  • Delete all key-value pairs

<?php
    //遍历删除
    foreach($_COOKIE as $key=>$val){
            setcookie("$key","",time()-200);
    }    echo "删除所有的键值对成功";?>
Copy after login

Small details of cookies

  • If the cookie you want to delete has not been deleted, the cookie will still be retained on the client; if you delete all cookies on this website If all are deleted, the browser will delete the entire file.

  • Cookies can be md5 encrypted

    setcookie("name", md5("hoki"), time() + 10);
Copy after login

Session

How to implement after logging in to a website Can the user name be viewed on any web page?

graph LR浏览器-->|将数据保存到session文件中|session01.phpsession01.php-->|写入|session文件浏览器-->|取出该浏览器保存的session数据|session02.phpsession02.php-->|读取|session文件
Copy after login

Why choose session instead of database or cookie?

  1. The database is more complicated to implement

  2. Cookies need to transmit data over the network, which has problems with insecurity and excessive data volume

Save session data

Saved data format : name|s:8:”hoki”;
- name: key
- s: Data Type
- 8: Data Size(Byte)

<?php
    echo "<br>--演示如何保存session数据?--<br>";    //1. 初始化session
    session_start();//可通过手册获取(函数扩展->Session扩展->Session函数)
    //2. 保存数据
    $_SESSION[&#39;name&#39;]="hoki";    //3. session文件可以保存double,integer,bool,array,object等类型
    $_SESSION[&#39;age&#39;]=100;//integer
    $_SESSION[&#39;isBoy&#39;]=true;//bool

    //save array
    $arr=array("hoki","lin","handsome");    $_SESSION[&#39;arr&#39;]=$arr;    //save object
    class Cat{
        private $name;        private $age;        private $intro;        function __construct($name,$age,$intro){
            $this->name = $name;            $this->age = $age;            $this->intro = $intro;

        }        public function getName(){
            return $this->name;
        }        public function getAge(){
            return $this->age;
        }        public function getIntro(){
            return $this->intro;
        }
    }    $cat = new Cat("猫","2","well");    $_SESSION[&#39;cat&#39;] = $cat;    echo "保存成功";?>
Copy after login

Get session data

<?php
    echo "<br/>获取session数据<br/>";

    session_start();    //1. 获取所有session
    echo "<pre class="brush:php;toolbar:false">";
    print_r($_SESSION);    echo "
"; //2. 通过key来指定获取某个值 echo "名字是:".$_SESSION[name]; $arr = $_SESSION['arr']; echo "
数组的数据是:"; foreach($arr as $key=>$val){ echo "
$val"; } //3. 获取对象 //因为对象没有串行化,所以要把类的定义也搬过来 //当然,也可以把类的定义独立出来,要用到时require_once调用即可 class Cat{ private $name; private $age; private $intro; function __construct($name,$age,$intro){ $this->name = $name; $this->age = $age; $this->intro = $intro; } public function getName(){ return $this->name; } public function getAge(){ return $this->age; } public function getIntro(){ return $this->intro; } } $cat = $_SESSION['cat']; echo "
猫的名字是:".$cat->getName(); echo "
猫的年龄是:".$cat->getAge(); echo "
猫的介绍是:".$cat->getIntro();?>
Copy after login

Update session data

<?php
    session_start();    $_SESSION[&#39;name&#39;] = "小明";    echo "更新成功";?>
Copy after login

Delete session data

<?php
    session_start();    //1. 删除某一个键值对
    unset($_SESSION[&#39;name&#39;]);    //2. 删除所有键值对,相当于把当前这个浏览器对应的session文件删除
    session_destroy();    echo "删除session数据成功";?>
Copy after login

Features of session

  1. ##To use session, you need to initialize session_start();

  2. Multiple key-value pairs can be placed in the session file, but please note that the keys cannot be repeated, and the values ​​can be basic data types or arrays, objects

  3. If you want to obtain an object, you need to declare the definition of the class

  4. A session corresponds to a session file

  5. session.gc_maxlifetime = 1440 秒

  6. 在php.ini文件中搜索session.save_path,可以查看session文件的默认保存路径

Cookie与Session的区别

  • Cookie是把用户的数据写给用户的浏览器

  • Session是把用户的数据写到用于独有的$_SESSION中,存在服务器的某个路径的文件中

session的应用例子

F12查看效果更佳;记得清除浏览器缓存;

MyHall.php

<?php
    //购物界面
    echo "<h1>欢迎购买</h1>";    echo "<a href=&#39;ShopProcess.php?bookid=sn001&bookname=三国演义&#39;>三国演义</a><br/>";    echo "<a href=&#39;ShopProcess.php?bookid=sn002&bookname=红楼梦&#39;>红楼梦</a><br/>";    echo "<a href=&#39;ShopProcess.php?bookid=sn003&bookname=水浒传&#39;>水浒传</a><br/>";    echo "<a href=&#39;ShopProcess.php?bookid=sn004&bookname=西游记&#39;>西游记</a><br/>";    echo "<hr/>";    echo "<a href=&#39;ShowCart.php&#39;>查看已购商品列表</a>"?>
Copy after login

ShowProcess.php

<?php
    //接收用户购买请求并把书存到session中
    $bookid = $_GET[&#39;bookid&#39;];    $bookname = $_GET[&#39;bookname&#39;];    //保存到session中
    session_start();    $_SESSION[$bookid] = $bookname;    echo "<br/>购买商品成功";    echo "<br/><a href=&#39;MyHall.php&#39;>返回购物界面继续购买</a>";?>
Copy after login

ShowCart.php

<?php
    echo "<h1>购物车商品列表</h1><br/>";

    session_start();    foreach($_SESSION as $key=>$val){        echo "书号:".$key.";书名:".$val."<br/>";
    }    echo "<br/><a href=&#39;MyHall.php&#39;>返回购物界面继续购买</a>";?>
Copy after login

禁用cookie的处理

浏览器->工具->Internet选项->隐私->高级

如果用户禁用cookie后,服务器每次session_start();都会创建一个全新的session文件,后果就是无法让多个php页面共享同一份session文件。

有三种方式可以实现在客户端禁用cookie后共享session

  1. 在每个超链接上添加一个PHPSESSID=sessionId;同时在每个页面加入:

    if(isset($_GET[&#39;PHPSESSID&#39;])){
        session_id($_GET[&#39;PHPSESSID&#39;]);
    }

    session_start();
Copy after login
  1. 使用常量SID
    在超链接action ,header(“Location:xx”)可以直接拼接SID常量即可

echo "<a href=&#39;ShopProcess.php?bookid=sn004&bookname=西游记&".SID."&#39;>西游记</a><br/>";
Copy after login
  1. 启用session.use_trans_sid=1

如何防止用户非法登录

登录页面

session_start();$_SESSION[&#39;loginuser&#39;]=$name;
Copy after login

目标页面

session_start();if(empty($_SESSION[&#39;loginuser&#39;])){
    header("Location: login.php");
}
Copy after login

session垃圾回收机制

当某个用户操作session的时候,会使用到session_start(),该函数会调用gc,但是其概率是session.gc_probability/session.gc_pisor;如果网站的规模越大,应该把这个概率设置得越小。


PHP文件编程

获取文件的信息

  • [atime] => 1523005390 该文件上一次被访问的时间戳

  • [mtime] => 1523005397 该文件上一次内容被修改时间戳

  • [ctime] => 1523005390 该文件上一次文件所有者/文件所在组被修改的时间戳

<?php
    //第一种方式获取文件信息
    //打开文件
    $file_path = "test.txt";    //fopen函数返回一个指向文件的指针
    if ($fp = fopen($file_path,"r")){        //fstat函数返回文件指针的文件统计信息
        $file_Info = fstat($fp);        echo "<pre class="brush:php;toolbar:false">";
        print_r($file_Info);        echo "
"; //获取文件大小等 echo "
文件大小:".$file_Info['size']; //如果会出现警告,可能是没有在php.ini中设置时区 //修改date.timezone = UTC后重启即可 echo "
文件上次修改时间:".date("Y-m-d H:i:s",$file_Info['mtime']); echo "
文件上次访问时间:".date("Y-m-d H:i:s",$file_Info['atime']); echo "
文件上次change时间:".date("Y-m-d H:i:s",$file_Info['ctime']); }else{ echo "打开文件失败"; } //关闭文件指针 fclose($fp); //第二种方式获取文件信息 echo "
".filesize($file_path); echo "
".fileatime($file_path); echo "
".filectime($file_path); echo "
".filemtime($file_path);?>
Copy after login

读文件

<?php
    $file_path = "test.txt";    /**************第一种读取方式*******************/
    //判断文件是否存在/*  if(file_exists($file_path)){
        //打开文件
        $fp = fopen($file_path,"a+");
        //读内容,并输入
        $con = fread($fp,filesize($file_path));
        echo "文件的内容是:<br/>";
        //在默认情况下,得到内容输出到网页后,不会换行,因为网页不认为\r\n是换行符
        $con = str_replace("\r\n","<br/>",$con);
        echo $con;
    }else{
        echo "文件不存在";
    }

    //关闭文件
    fclose($fp);
*/
    /**************第二种读取方式*******************//*  $con = file_get_contents($file_path);//连关闭的动作都不用写
    //在默认情况下,得到内容输出到网页后,不会换行,因为网页不认为\r\n是换行符
    $con = str_replace("\r\n","<br/>",$con);
    echo $con;
*/
    /**************第三种读取方式*******************/
    $fp = fopen($file_path,"a+");    //设置一次读取1024个字节
    $buffer = 1024;    $str = "";    //一边读,一边判断是否到文件结束位置
    while(!feof($fp)){        //读内容
        $str.= fread($fp,$buffer);
    }    //在默认情况下,得到内容输出到网页后,不会换行,因为网页不认为\r\n是换行符
    $con = str_replace("\r\n","<br/>",$str);    echo $str;    //关闭文件
    fclose($fp);
Copy after login

文件读取的实际用法

连接数据库的时候,可以把用户名,密码等配置到一个外部文件

db.ini

host=127.0.0.1user=adminpassword=123456
Copy after login

readIni.php

<?php
    $arr = parse_ini_file("db.ini");
    print_r($arr);    echo "<br/>";    echo $arr[&#39;host&#39;];    echo "<br/>";    echo $arr[&#39;user&#39;];    echo "<br/>";   
    echo $arr[&#39;password&#39;];?>
Copy after login

写文件

<?php

    $file_path="C:/test.txt";//路径名的斜杆必须是/

    //传统方式写入/*  if(file_exists($file_path)){
        //如果是追加内容,则使用a+的方式打开
        $fp = fopen($file_path,"a+");
        $con = "\r\n这是追加的内容";
        for($i=0;$i<10;$i++){
            fwrite($fp,$con);
        }
    }else{
        echo "执行失败";
    }
    echo "添加成功";
    //关闭文件
    fclose($fp);
*/  
    //第二种方式写入
    $con = "\r\nhello";
    file_put_contents($file_path,$con,FILE_APPEND);//底层封装了fopen(),fwrite()和fclose()
    //如果用第二种方式来循环添加内容的话,效率就没有传统的方式写入高了
    //因为第二种方式总是需要走三步执行一次,如果一定要用第二种方式写入的话,
    //应该先把字符串拼接完再调用file_put_contents函数写入,效率才高
    echo "添加成功";?>
Copy after login

复制文件(image)

<?php
    //路径不要带中文,否则会提示失败信息
    $file_path = "E:\\phpAll\\Apache24\\htdocs\\file\\jay.jpg";    //路径名转码
    $file_target = iconv("utf-8","gb2312","d:\\周杰伦.jpg");    //copy(数据源,目标地址);
    if(!copy($file_path,$file_target)){        echo "error";        return;
    }    echo "success";?>
Copy after login

文件及文件夹的创建和删除

<?php
    $file_path = "d:/hoki_test/a/b";    //创建一个文件夹 /*  if(!is_dir($file_path) && mkdir($file_path)){
        echo "create success";
        return;
    }
    echo "create failed";
*/  

    //创建多个文件夹(递归创建) /*  if(!is_dir($file_path) && mkdir($file_path,0777,true)){
        //777:可读可写可执行;
        echo "create success";
        return;
    }
    echo "create failed";
*/  

    //删除一个文件夹(如果是多级的就删除最外面的那个)
    //如果文件夹下有文件,或者目录,均不能删除成功/*  if(is_dir($file_path) && rmdir($file_path)){
        echo "delete success";
        return;
    }
    echo "delete failed";
*/

    //在指定现有目录下创建一个文件并写入内容/*  $file_name = "/test.txt";
    $fp = fopen($file_path.$file_name,"w+");
    $content = "hello world";
    fwrite($fp,$content);
    fclose($fp);
    echo "create file success";
*/

    //删除文件
    $file_name = "/test.txt";    if (is_file($file_path.$file_name)){        if (unlink($file_path.$file_name)){            echo "delete file success";            return;
        }        echo "delete file failed";        return;
    }    echo "file none found";?>
Copy after login

php文件上传案例

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>文件上传案例</title>
    </head>
    <body>
        <h1>上传文件</h1>
        <form action="upload.php" method="post" enctype="multipart/form-data">
            请选择文件:
            <input type="file" name="file" />
            <input type="submit" value="上传" />
        </form>
    </body>
</html>
Copy after login
<?php
    //取文件信息
    $arr = $_FILES["file"];    //var_dump($arr);
    //加限制条件
    //1.文件类型
    //2.文件大小
    //3.保存的文件名不重复
    if(($arr["type"]=="image/jpeg" || $arr["type"]=="image/png" ) && $arr["size"]<10241000 )
    {        //临时文件的路径
        $arr["tmp_name"];        //上传的文件存放的位置
        //避免文件重复: 
        //1.加时间戳.time()加用户名.$uid或者加.date(&#39;YmdHis&#39;)
        //2.类似网盘,使用文件夹来防止重复
        $filename = "./images/".date(&#39;YmdHis&#39;).$arr["name"];        //保存之前判断该文件是否存在
        if(file_exists($filename))
        {            echo "该文件已存在";
        }        else
        {            //中文名的文件出现问题,所以需要转换编码格式
            $filename = iconv("UTF-8","gb2312",$filename);            //移动临时文件到上传的文件存放的位置(核心代码)
            //括号里:1.临时文件的路径, 2.存放的路径
            move_uploaded_file($arr["tmp_name"],$filename);
        }
    }else{        echo "上传的文件大小或类型不符";
    }?>
Copy after login

PHP绘图

像素是密度单位,不是长度单位

步骤

在php.ini中启动gd库(extension=php_gd2.dll)

  1. 创建画布

  2. 绘制需要的各种图形

  3. 输出图像到网页,也可另存

  4. 销毁图片(服务器端的),释放内存

图片格式的比较

  • GIF:压缩率高,但是只能显示256色,会造成颜色丢失,可以显示动画

  • JPG/JPEG:压缩率高(有损压缩),可以用较小的文件来显示,网页上用的比较多

  • png:该格式综合了GIF和JPG的优势,缺点是不能显示动画

基本步骤模板

<?php
    //1. 创建画布,默认背景是黑色的
    $im = imagecreatetruecolor(800,600);    //修改背景颜色
    $white = imagecolorallocate($im,255, 255, 255);
    imagefill($im,0,0,$white);    //2. 绘制需要的各种图形
    //创建三个颜色
    $red = imagecolorallocate($im,255, 29, 0);    $blue = imagecolorallocate($im,6, 81, 244);    $gary = imagecolorallocate($im,178, 174, 170);    //3. 输出图像到网页,也可另存
    header("content-type: image/png");
    imagepng($im);    //4. 销毁图片(服务器端的),释放内存
    imagedestroy($im);?>
Copy after login

例子

<?php//  1. 创建画布,默认背景是黑色的
    $im = imagecreatetruecolor(800,600);//  2. 绘制需要的各种图形
    //创建一个颜色
    $red = imagecolorallocate($im,255,0,0);    //ellipse:椭圆
    imageellipse($im,20,20,20,20,$red);    //直线
    imageline($im,0,0,400,300,$red);    //矩形
    imagerectangle($im,150,150,40,50,$red);    //填充矩形
    imagefilledrectangle($im,0,0,40,50,$red);//PHP设计者设计函数名时设计得不好
    //弧线(顺时针)
    imagearc($im,100,100,50,50,0,180,$red);    //扇形
    imagefilledarc($im,100,100,50,50,180,270,$red,IMG_ARC_PIE);
    imagefilledarc($im,100,100,50,50,270,360,$red,IMG_ARC_PIE);    //拷贝图像到画布
    //加载源图片/*  $srcImage = imagecreatefromjpeg("cat.jpg");
    //获取图片的宽和高存于数组中
    $srcImageInfo = getimagesize("cat.jpg");
    //拷贝源图片到目标画布
    imagecopy($im,$srcImage,0,10,200,0,$srcImageInfo[0],$srcImageInfo[1]);
*/  
    //字符串
    $str = "hello world,中文";//  imagestring($im,10,400,200,$str,$red);//中文显示乱码
    //在字体库C:\Windows\Fonts中找中文字体//  imagettftext($im,10,0,50,50,$red,"STFANGSO.TTF",$str);//  3. 输出图像到网页,也可另存
    header("content-type: image/png");
    imagepng($im);//  4. 销毁图片(服务器端的),释放内存
    imagedestroy($im);?>
Copy after login

饼状统计图的绘制

可封装为一个函数,方便使用

<?php
    //1. 创建画布,默认背景是黑色的
    $im = imagecreatetruecolor(800,600);    //修改背景颜色
    $white = imagecolorallocate($im,255, 255, 255);
    imagefill($im,0,0,$white);    //2. 画出扇形
    //创建三个颜色
    $red = imagecolorallocate($im,255, 29, 0);    $darkred = imagecolorallocate($im,144, 0, 0);    $blue = imagecolorallocate($im,6, 81, 244);    $darkblue = imagecolorallocate($im,0, 0, 80);    $gary = imagecolorallocate($im,178, 174, 170);    $darkgary = imagecolorallocate($im,144, 144, 144);    //立体扇形其实就是多个扇形的叠加
    for ($i=200;$i>=150;$i--){
        imagefilledarc($im,350,$i,200,150,0,35,$darkblue,IMG_ARC_PIE);
        imagefilledarc($im,350,$i,200,150,35,75,$darkgary,IMG_ARC_PIE);
        imagefilledarc($im,350,$i,200,150,75,360,$darkred,IMG_ARC_PIE);
    }    //在上面加个盖
    imagefilledarc($im,350,150,200,150,0,35,$blue,IMG_ARC_PIE);
    imagefilledarc($im,350,150,200,150,35,75,$gary,IMG_ARC_PIE);
    imagefilledarc($im,350,150,200,150,75,360,$red,IMG_ARC_PIE);    //3. 输出图像到网页,也可另存
    header("content-type: image/png");
    imagepng($im);    //4. 销毁图片(服务器端的),释放内存
    imagedestroy($im);?>
Copy after login

验证码

<?php
    echo "<img src=yanzhengma.php>";?>
Copy after login
<?php
    function random($len){
        $srcstr = "ABCDEFGHIJKLMNONPQRSTUVWXYZ0123456789";
        mt_rand();        $strs = "";        for($i=0;$i<$len;$i++){            $strs.=$srcstr[mt_rand(0,35)];
        }        return strtoupper($strs);
    }    $str = random(4);//随机生成的字符串
    $width = 50;    $height = 25;
    @header("Content-Type: image/png");    $im = imagecreate($width,$height);    $back = imagecolorallocate($im,0xFF,0xFF,0xFF);    //模糊点颜色
    $pix = imagecolorallocate($im,187,230,247);    //字体色
    $font = imagecolorallocate($im,41,163,238);    //绘制模糊作用的点
    mt_srand();    for($i=0;$i<1000;$i++){
        imagesetpixel($im,mt_rand(0,$width),mt_rand(0,$height),$pix);  
    }
    imagestring($im,5,7,5,$str,$font);
    imagerectangle($im,0,0,$width-1,$height-1,$font);
    imagepng($im);
    imagedestroy($im);?>
Copy after login

相关推荐:

PHPTree——php快速生成无限级分类_php技巧

php中tree类的使用方法

The above is the detailed content of $PHP_THREE. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template