PHP

PHP 是一门开源、免费、专为 Web 开发而生的服务器端脚本语言,1995 年诞生,全称是 Hypertext Preprocessor(超文本预处理器),核心优势是简单易学、部署便捷、与网页高度融合。

它的核心优势在于**可以直接嵌入 HTML 中运行、无需复杂编译**,配合 MySQL 等数据库即可快速搭建动态网站与接口,是全球最流行的后端开发语言之一。

传统后端开发往往需要复杂的编译与部署流程,而 PHP 以“嵌入 HTML、即写即跑”的轻量方式,大幅降低了 Web 后端入门与快速建站的门槛。
PHP 8 学习笔记

1. 概述

PHP 是一门开源、免费、专为 Web 开发而生的服务器端脚本语言,1995 年诞生,全称是 Hypertext Preprocessor(超文本预处理器)。它的核心优势在于可以直接嵌入 HTML 中运行、无需复杂编译,配合 MySQL 等数据库即可快速搭建动态网站与接口,是全球最流行的后端开发语言之一。本文从环境搭建与语法基础讲起,依次讲解表单传值、数据库操作、会话技术、文件编程与 GD 图像处理等内容。

2. 安装配置

搭建 PHP 运行环境通常需要 PHP 解释器、数据库、Web 服务器与建站程序四件套,下面给出常用组合与关键配置。

组件 说明 下载 / 地址
PHP 服务器端脚本语言,需配置 php.ini PHP: Downloads
MySQL 关系型数据库,常与 PHP 搭配 https://www.mysql.com/cn/
Nginx Web 服务器,反向代理转发 PHP 请求 —
WordPress 基于 PHP 的建站程序(示例项目) https://cn.wordpress.org/latest-zh_CN.zip
**php.ini 配置**:将 `php.ini-development` 备份并改名为 `php.ini` 后进行如下配置。

php.ini 关键配置:

data.timezone=Asia/Shanghai

extension_dir="D:\php8\ext"
cgi.fix_pathinfo=1
extension=mysqli
extension=pdo_mysql

extension=curl

启动 PHP 内置 CGI 进程(监听本地 9000 端口):

php-cgi -b 127.0.0.1:9000 -c D:\php8\php.ini(php.ini的路径)

Nginx 中配置 PHP 反向代理(以 WordPress 目录为例):

location / {
    root   D:\wordpress;
    index  index.html index.htm index.php;
}

location ~ \.php$ {
    root           D:\wordpress; //wordpress的目录
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  
    $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

WordPress 示例截图:

20250622223e6202506221542184066.png

3. PHP 入门

PHP 是一种运行在服务器端的脚本语言,可以嵌入 HTML 中。

2.1 嵌入 HTML 示例

<html>
<body>
    <b>
        <?php
            echo "hello"
        ?>
    </b>
</body>
</html>

2.2 注释

注释

//

/* */

2.3 PHP 代码标记

<?php ?>

2.4 PHP 语句分隔符

; 为一句的结束

<?php 后面可以不写 ?> ,这样说明后面的都为 PHP 代码

2.5 定义变量

$var1;

$var2 = 1;

unset($var2) ===> 删除变量

2.6 预定义变量

预定义变量 说明
$_GET 获取所有表单以 GET 方式提交的内容
$_POST POST 提交的数据
$_REQUEST GET 和 POST 的数据
$GLOBALS 全局数据
$_SERVER 服务器信息
$_SESSION session 会话数据
$_COOKIE cookie 会话信息
$_ENV 环境信息
$_FILES 用户上传的文件

2.7 可变变量

$a = "b";

$b = "bb";

$$a ==> "bb" 解析 $a 为 b 再解析 $b 为 bb

2.8 变量传值

$a = &$a 类似 C 的指针(引用传值)

2.9 常量

常量不需要加 $

常量通常使用大写字母,Define 和 const 有访问权限的区别

define('RI', 'hahah');

const TI = 3.14;
echo TI;

输出特殊字符常量:

define('-_-', '-_-');
echo constant('-_-');

2.10 系统常量

/* 版本    整形大小   最大整形   */
echo PHP_VERSION ,'<br/>', PHP_INT_SIZE ,'<br/>',PHP_INT_MAX;

2.11 魔术变量

魔术常量 说明
__DIR__ 当前被执行脚本在所在电脑的绝对路径
__FILE__ 当前被执行脚本在所在电脑的绝对路径(带上文件名)
__LINE__ 当前所属的行数
__DIR__ 当前所属类的

2.12 数据类型

整形 int / integer

浮点 float / double

字符串 string

布尔 bool / boolean 可以使用 var_dump() 查看

类型转换与判断:

类型转换 (float)1 (数据类型)值

类型判断 is_xxx(变量名)

var_dump(is_int(10));  //====>true

gettype(变量名) 获取类型,返回字符串

settype(变量名,类型) 设定数据类型,与强制类型转换不同

empty() 判断是否为空

isset() 判断变量本身是否存在

2.13 连接运算符

. : 连接两个字符串

.= : 将左边和右边的内容连接起来并赋值给左边

$a = "ha";
$b = "lo";
echo $a . $b; 
// ===>halo
$a = "ha";
$b = "lo";
$a .= $b;
echo $a;

2.14 错误抑制符

可能会出错但无法避免,并且不希望给用户报错

@ ==> 错误抑制符,常用于生成环境

2.15 流程控制替代语法

HTML 嵌套 PHP

<table border="1">
    <?php for ($i = 1;$i<10;$i++){?>
                <tr>
                    <?php for ($j = 1;$j<= $i;$j++){ ?>
                        <td>
                            <?php echo $i . "*" . $j . "=" .($i*$j);?>
                        </td>
                    <?php } ?>
                </tr>
            <?php }?>
</table>

此时可以使用 endfor 和 : 替代语法:

<table border="1">
    <?php for ($i = 1;$i<10;$i++):?>
        <tr>
            <?php for ($j = 1;$j<= $i;$j++): ?>
                <td>
                    <?php echo $i . "*" . $j . "=" .($i*$j);?>
                </td>
            <?php endfor;?>
        </tr>
    <?php endfor;?>
</table>

替代语法对应关系:

if ===> endif

while ===> endwhile

for ===> endfor

foreach ===> endforeach

switch ===> endswitch

4. PHP 基础

3.1 常用系统函数

3.1.1 打印相关函数

//打印相关函数
echo print("hahaah1<br/>");
print "hahaha2<br/>";

$a = 1234;
print_r($a);

3.1.2 时间相关函数

microtime

echo date("Y 年 m月 d日 H:i:s",12344555),'<br/>';  //格式化字符串
echo time() ,'<br/>';   //时间戳
echo microtime(); 

3.1.3 关于函数的函数

function_exists() 不去执行一个不存在的函数

func_get_arg() 自定义函数中获取指定数值对应的参数

func_get_args() 获取所有的参数 –> 数组

func_num_args() 获取参数的数量

function test($a,$b){
    var_dump(func_get_arg(0));
    var_dump(func_get_args());
    var_dump(func_num_args());
}

test(10,20);

3.2 文件包含

include 包含文件

include_once 只包含一次

require 与 include 相同

require_once 与 include_once 相同

include '文件名';
include("文件名")
**包含差异**:加载到哪,相当于文件嵌入哪里。`require` 要求较高,如果没有该文件就会**报错(警告),后面的代码不执行**;`include` 要求较低,如果没有包含到文件会警告,但后面的代码**继续执行**。嵌套包含容易出现相对路径错误的问题。

3.3 函数

3.3.1 函数的基本使用

function 函数名(){}

默认值

function test($a=0,$b=0){}

引用传递
function test($a,&$b){

}
test($a,$b);

static $count = 1 // 静态变量

3.3.2 可变函数

function display(){
    echo __FUNCTION__ ;
}

$fun = 'display';

$fun();

3.3.3 匿名函数

$a = function(){

};

变量保存的匿名函数本质上是一个 Closure

3.3.4 伪类型

Mixed,混合的,可以是多种 PHP 的数据类型

Number 数值类型,可以是任意数值类型

3.4 错误

3.4.1 错误代号

错误代号 说明
E_PARSE 编译错误,代码不会执行
E_ERROR fatal error,代码不会执行
E_WARNING warning,警告错误,不会影响代码执行
E_NOTICE 通知错误
E_ALL 所有错误
E_USER_* 用户错误(E_USER_ERROR / E_USER_WARNING / E_USER_NOTICE)

3.4.2 触发错误

trigger_error() // 默认 notice,代码会继续执行

trigger_error(msg, E_ERROR) // 报错,不会继续执行

3.4.3 错误显示设置(php.ini)

display_errors 是否显示错误

error_reporting 显示什么级别的错误

3.4.4 在 PHP 脚本中设置

error_reporting() 设置错误的显示级别

ini_set("配置文件的配置项","配置值")

php.ini

log_errors = on ====> 开启日志功能

error_log = "D/errors/log" ===> 配置日志记录文件

3.4.5 自定义错误

function my_repo($errorno,$errorstr,$errorfile,$errorline){
    if (!(error_reporting() & $errorno)){ //error_reporting没有参数表示获取当前错误处理对应的级别
        return false;
    }
    switch($errorno){
        case E_ERROR:
        case E_WARNING:
            echo "wrong" . "ONLINE:" . $errorline . "ONFILE:" . $errorfile . "<br/>";
            echo "msg:" . $errorstr;
            break;
        case E_PARSE:
        case E_NOTICE:
            echo "wraning" . "ONLINE:" . $errorline . "ONFILE:" . $errorfile . "<br/>";
            echo "msg:" . $errorstr;
    }
    return true;
}
set_error_handler("my_repo");
echo $a;

3.5 字符串

3.5.1 定义字符串

"hello" 'hello'

    $str1 = <<<EOD
    hello
EOD;
    $str2 = <<<'EOD'
    hello1
EOD;
    echo $str1 . "    " . $str2;

上边界符同行后面不能加内容

下边界符必须顶格写

    $str1 = <<<EOD
    <script>
        alert("test");
    </script>
EOD;
    echo $str1;

strlen() 字节长度

3.5.2 字符串函数

函数 说明
implode(连接方式,数组) 将数组按连接方式拼成字符串
explode(分割字符,字符串) 将字符串切分成数组
str_split(字符串,长度) 按指定长度拆分字符串得到数组
trim() / ltrim() / rtrim() 去除(左/右)空格
substr(字符串,起始位置,长度) 截取字符串
strstr(字符串,匹配字符) 匹配到字符后全部截取
strtolower() / strtoupper() / ucfirst() 全小写 / 全大写 / 首字母大写
strpos(字符串,'a') 查找首次出现的位置
strrpos(字符串,'a') 查找最后一次出现的位置
str_replace(目标字符,替换成的字符,字符串) 将目标字符串中部分字符串进行替换
printf() / sprintf() 格式化输出
str_repeat() 重复某个字符串 N 次
str_shuffle() 随机打乱字符串

3.6 数组

3.6.1 一维数组

**定义数组的三种方式**
//1.
$arr = array("1","2","3");
//2.
$arr1 = ["4","5","6"];

//3.给变量增加一个中括号
$变量[] = 值1;
$变量[下标] = 值;

字符串也可以作为下标

如果中间出现下标较大的,那么后面的自增元素从最大值 +1 开始

$arr = array("1","2","3");
echo $arr[2];

$arr1 = [10,20,30];
echo $arr1[2];
$arr2[1] = 20;
$arr2["key"] = "key";

特殊下标自行转换

true,false –> 1,0

NULL –> ""

下标没有类型限制

3.6.2 二维数组

$info = array(
    array(1,2,3),
    array(4,5,6),
    array(7,8,9),
);

for ($i = 0; $i < count($info); $i++) {
    for ($j = 0; $j < count($info[$i]); $j++) {
        echo $info[$i][$j];
    }
    echo "<br/>";
}

3.6.3 foreach

$info = array(
    array(1,2,3),
    array(4,5,6),
    array(7,8,9),
);

foreach ($info as $k) {
    foreach ($k as $m) {
        echo $m;
    }
    echo "<br/>";
}

获取下标

$k as $m=>$n $m 为下标 $n 为值

$info = array(
    array(1,2,3),
    array(4,5,6),
    array(7,8,9),
);

foreach ($info as $k) {
    foreach ($k as $m=>$n) {
        echo "key:" . $m . "," . "value:" . $n;
    }
    echo "<br/>";
}
$arr = array(
    0 => array("name"=>"Tom","age"=>"18"),
    1 => array("name"=>"jack","age"=>"19")   
);

3.6.4 each

each() 打印之后,指针往后偏移,移动到最后返回 false

$arr = array(1,"a"=>"b","c"=>"d",3);

while (list($key,$value) = each($arr)) {
    echo "". $key ."". $value ."";
}

3.6.5 数组指针函数

函数 说明
reset() 重置指针,将指针回到首位
end() 将指针指向最后一个位置
next() 指针下移,取得下一个元素的值
prev() 指针上移,取得上一个元素的值
current() 获取当前指针的元素
key() 获取当前指针对应的下标

3.6.6 其他函数

函数 说明
count() 统计数量
array_push() 加入一个元素,尾部
array_pop() 取出元素,尾部
array_shift() 取出一个元素,头部
array_unshift() 加入一个元素,头部
array_reverse() 反转数组
in_array() 判断是否在数组内存在
array_keys() 取出所有的下标
array_values() 取出所有的值

5. 表单传值

通过浏览器表单元素将输入的数据交给后台服务器。

4.1 PHP 接收表单数据

超全局预定义数组,表单元素的 name 属性的值作为下标,而 value 则为数组的元素值。

$_REQUEST 是 GET 和 POST 合并存储到同一个数组。

var_dump($_GET);
echo "<br/>";
var_dump($_POST);
echo "<br/>";
var_dump($_REQUEST);

4.2 PHP 处理复选框

选择多个可能会产生覆盖问题

PHP 会自动组合同名元素为数组

<input name=test[] type="checkbox"></input>

4.3 多选按钮

表单中 name 属性使用数组格式,名字 []

后台接收到数据之后,是一个数组

PHP 需要将数组转换成指定格式的字符串

implode("数组","分隔符")

explode("分隔符","字符串")

4.4 文件上传

表单制作

<form method="POST" enctype="multipart/form-data" action="">
    <input type="file" name="image"/>
    <input type="submit" name="btn" value="上传" />
</form>

4.4.1 $_FILES 变量详解

键名 说明
name 文件实际名称
tmp_name 上传之后的临时保存路径
type MIME(多功能互联网邮件扩展)类型,识别文件类型
error 文件上传的代号,告知应用软件文件接收过程出现了什么问题
size 文件大小(根据需求是否保留)
$file = $_FILES['image'];  //获取
if (is_uploaded_file($file)){  //is_uploaded_file($file)为判断文件是否通过HTTP上传
  if (move_uploaded_file($File["tmp_name"],'uploads/')){
    echo "保存成功";
  }else{
    echo "保存失败";
  }
}

4.4.2 多文件上传

同名:

<form method="POST" enctype="multipart/form-data" action="/richu/richu.php">
    <input type="file" name="image[]"/>
    <input type="file" name="image[]"/>
    <input type="file" name="image[]"/>
    <input type="submit" name="btn" value="批量上传" />
</form>

不同名:

<form method="POST" enctype="multipart/form-data" action="/richu/richu.php">
    <input type="file" name="head"/>
    <input type="file" name="body"/>
    <input type="file" name="foot"/>
    <input type="submit" name="btn" value="批量上传" />
</form>

4.4.3 文件上传函数封装

<?php
    /**
     * @param array $allow_type 允许上传的MIME类型
     * @param string $path
     * @param string $error
     * @param array $allow_format = array()
     * @param int $max_size = 200000
     */
    function uploadFile($allow_type,$path,$error,$allow_format= array(),$max_size=20000){

    }

6. 数据库操作

5.1 连接

$link = mysqli_connect("localhost:3306","root","password");
var_dump($link);
//设置字符集
mysql_query('set names utf8',$link);
var_dump($res); //===>true

5.2 选定要使用的数据库

$res = mysqli_query($link,'use mp');
var_dump($res);

5.3 关闭连接

mysqli_close($link);

5.4 增删改操作

增删查改在 mysqli_query($link,"") 中使用写 SQL 语句

$link = mysqli_connect("localhost:3306","root","password") or die("连接失败");

mysqli_query($link,"set names utf8");

mysqli_query($link,"use mp");

$res = mysqli_query($link,'insert into book(type,name,description) values("文学","背影","感动")');
var_dump($res);

mysqli_close($link);

5.4.1 获取结果

echo mysqli_num_rows($res);

//表的表单名为下标,元素为元素值
print_r(mysqli_fetch_assoc($res));

//列的索引作下标,元素为元素值
print_r(mysqli_fetch_row($res));

//同时获取
print_r(mysqli_fetch_array($res,MYSQL_BOTH));

5.4.2 其他函数

//字段数
echo mysqli_num_fields($res);

//取得上一次insert语句的id
mysqli_insert_id($link);

7. 新闻项目实战

6.1 插入功能的设置

header("Content-type:text/html;charset=utf-8");
$link = mysqli_connect("localhost:3306","root","password") or die("连接失败");

mysqli_query($link,"set names utf8");

//封装处理函数
function my_err($link,$sql){
    $res = mysqli_query($link,$sql);
    if (!$res) {
        echo ""."error".""."";
    }
    return $res;
}

mysqli_query($link,"use mp");

if (empty($title) || empty($Context)){
    header('Refresh:3;url=../test.html');
    echo "标题和内容不能为空";
}

$sql = "insert into news values(null,'{$title}',{$isTop},'{$Context}','{$author}')";

$id = my_err($link,$sql);

header("Refresh:3;url=../test.html");
echo "插入成功";

6.2 删除操作

function my_err($link,$sql){
    $res = mysqli_query($link,$sql);
    if (!$res) {
        echo ""."error".""."";
    }
    return $res;
}
header("Content-type:text/html;charset=utf-8");
$link = mysqli_connect("localhost:3306","root","password") or die("连接失败");
mysqli_query($link,"set names utf8");
mysqli_query($link,"use mp");

$id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;
if ($id == 0) {
    header("Refresh:3;url=news.php");
    echo "当前新闻页面不存在";
    exit();
}
$sql ='delete from news where id = '.$id;
my_err($link,$sql);

header("Refresh:3;url=news.php");
echo "当前新闻删除成功";

6.3 更新操作

(原文未展开。)

8. HTTP 协议

7.1 HTTP 响应

HTTP 响应常用设置

响应项 说明
Location 重定向,立即跳转
Refresh 重定向,定时跳转
Content-type 内容类型 / MIME 类型
Content-disposition 内容类型 / MIME 类型,激活浏览器文件下载对话框

7.2 PHP 模拟 HTTP 请求

curl 库

//创建
$ch = curl_init();
//设置请求项
curl_setopt($ch, CURLOPT_RETURNTRANSFER,TRUE);
curl_setopt($ch, CURLOPT_URL,"localhost/test/news.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
//执行请求
$res = curl_exec($ch);
echo $res;
//关闭连接
curl_close($ch);

9. 文件编程

8.1 文件基本操作

函数 说明
mkdir() 创建目录
rmdir() 删除目录
@mkdir 错误抑制符 @
函数 说明
opendir() 打开目录资源
readdir() 读取目录资源,读一个指针后移
. 第一个特殊文件,代表当前目录
.. 第二个特殊文件,代表上级目录
closedir() 关闭目录资源
函数 说明
dirname() 返回上一级目录路径
realpath() 返回文件真实地址
is_dir() 判断是否为目录
scandir() 封装版的 opendir() / readdir() / closedir()

8.2 文件目录递归遍历

$dir = "test";
function my_scanf($dir) : void {
    if(is_dir($dir)) {
        dir($dir);
    }

    $files = scandir($dir);
    foreach($files as $file) {
        echo $file .'<br>';
    }
}

my_scanf($dir);

递归搜索

$dir = "test";
function my_scanf($dir) : void {
    if(is_dir($dir)) {
        dir($dir);
    }

    $files = scandir($dir);
    foreach($files as $file) {

        if ($file == "."&& $file == "") continue;

        $nfile = $dir . '/' .  $file;
        echo $nfile . '<br>';
        if (is_dir($dir)) {
            my_scanf($nfile);
        }
    }
}
my_scanf($dir);

8.3 文件操作

//读取
$file = "test.txt";
$content = file_get_contents( $file );

var_dump( $content );

//写入
$content = "test test test";
file_put_contents( $file, $content );

8.4 其他文件函数

函数 说明
is_file() 判断文件是否正确(不识别路径)
filesize() 获取文件大小
file_exists() 判断文件是否存在
unlink() 取消文件名字与磁盘地址的连接
filemtime() 获取文件最后一次修改的时间
fseek() 设定 fopen 打开文件的指针位置
fgetc() 一次获取一个字符
fgets() 一次获取一个字符串
file() 读取整个文件(按行读取,返回一个数组)

8.5 PHP 实现文件下载

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

设定相应的响应头

$file = "test.html";
header("Content-type:text/html;charset=utf-8");

header("Content-type:application/octem-stream");  //以文件方式传递
header("Accept-ranges:bytes");//以字节方式计算
header("Content-disposition:attachment;filename=".$file); //指定文件下载名

echo file_get_contents($file);

10. 会话技术

设置 cookie

setcookie("","");

获取 cookie

$_COOKIE

设置 cookie 七天后过期

setcookie("a",1,time()+7*24*60*60);

0 生命周期(关闭会话过期)

setcookie("a",1,0);

删除 cookie

setcookie("a","")

setcookie("a","1",time())

普通 cookie,上层目录无法访问下层,下层可以访问上层

setcookie("global_key","key",0,'/');

setcookie(键,值,作用时间,作用范围,作用域名);

通过配置作用域名实现 cookie 跨子域

setcookie("a1['k1']","a");
$_COOKIE["a1"]["k1"];

9.6 Session

9.6.1 开启 Session

session_start();

var_dump($_SESSION);

9.6.2 设置 Session 信息

$_SESSION['name'] = "richu";

$_SESSION['list'] = array('1','2','3');

9.6.3 读取 Session 的值

$_SESSION['name'];

$_SESSION['list'];

9.6.4 删除一个 Session 的数据

unset($_SESSION['name']);

9.6.5 删除整个 Session 的数据

$_SESSION = array();

将 session 置为一个空数组

9.6.6 在脚本中配置 PHP 设置

@ini_set(设置,值);

9.6.7 销毁 Session

session_destroy()

自动提取 session_start() 获得的 sessionId 找到指定的 session 文件,并将其删除

9.7 垃圾回收参数设置

session.gc_maxlifetime = 1440 // session 最大生命周期为 1440 秒

session.gc_probability = 1 // 垃圾回收的概率因子

session.gc_divisor = 1000 // 垃圾回收的概率分母,触发概率为 1/1000

  1. 保存 sessionID 和名字

$id = session_id();

$name = session_name();

echo $name . ' = ' . $id;

// 设置内容

$_SESSION['name'] = 'mark';

  1. 利用 a 标签传递 sessionId
  2. 接收数据
  3. session_id($id)
  4. session_start() // 告诉 session_start() 已经有了 sessionId
  5. session_id($id)

11. GD

10.1 开启 GD

imagecreate(宽,高) 创建一个空画布

imagecreatetruecolor(宽,高) 创建一个真彩画布

imagecreatefromjpeg() 打开一个 jpeg 的图片

imagecreatefromgif() 打开一个 gif 的图片

imagecreatefrompng() 打开一个 png 的图片

10.2 操作画布资源

分配颜色:imagecolorallocate(画布资源,红色,绿色,蓝色) 返回一个颜色句柄

//创建一个画布资源
$img = imagecreatetruecolor(100,100); //黑色图片

$white = imagecolorallocate($img,100,100,255); //创建白色画布

填充区域

imagefill(画布资源,起始x坐标,起始y坐标,指定的颜色句柄) 指定位置开始填充

从指定位置开始,自动匹配相邻点,如果颜色一致,自动渲染,扩展到原图

imageline(图片资源,起始点x,起始点y,终点x,终点y,颜色句柄) 画直线

imagerectangle(图片资源,左上角x,左上角y,右下角x,右下角y,颜色句柄) 画矩形

imagearc(图像资源,轴点x,轴点y,宽度,高度,弧度的起点,弧度的终点) 画圆弧

imagestring(图片资源,文字大小,起始x,起始y,内容,颜色)

imagettftext(图片资源,文字大小,旋转角度,起始x,起始y,内容,颜色,字体,内容)

10.3 输出和销毁画布资源

输出为图片文件保存

imagejpeg() 保存为 jpeg

imagepng() 保存为 png

imagegif() 保存为 gif

不指定保存路径,默认输出到浏览器

销毁画布

imagedestroy($img)

10.4 获取图片信息

  1. 获取画布尺寸

imagesx()

imagesy()

  1. 获取图片尺寸

getimagesize()

10.5 验证码制作

//制作验证码图片
//创建图片资源
$img = imagecreatetruecolor(200 , 50);

//背景色
$bg_color = imagecolorallocate($img,220,220,220);
imagefill($img,0,0, $bg_color);

//写入内容
$font = "dashicons.TTF";
$str_color = imagecolorallocate($img,100,100,100);
imagettftext($img,30,-15,14060,40,$str_color,$font,'A');

//输出资源
header("Content-type:image/png");
imagepng($img);

//销毁资源
imagedestroy($img);

具体实现

//制作验证码图片

//创建图片资源
$img = imagecreatetruecolor(100 , 30);

//背景色
$bg_color = imagecolorallocate($img,220,220,220);
imagefill($img,0,0, $bg_color);

/*     //写入内容
    $str_color = imagecolorallocate($img,100,100,100);
    imagestring($img,6,-15,0,"4",$str_color); */

$captch_code = "";
for ($i=0; $i < 4; $i++) { 
    $fontsize=6;
    $fontcolor=imagecolorallocate($img,rand(0,120),rand(0,120),rand(0,120));

    //产生随机数字0-9
    $fontcontent = rand(0,9);
    //拼接字符串
    $captch_code.= $fontcontent;
    //数字的位置,0,0是左上角。不能重合显示不完全
    $x=($i*100/4)+rand(10,20);
    $y=rand(5,10);
    imagestring($img,$fontsize,$x,$y,$fontcontent,$fontcolor);
}

//为验证码增加干扰元素,控制好颜色,
//点   
for ($i=0; $i < 200; $i++) { 
    $pointcolor = imagecolorallocate($img,rand(50,200),rand(50,200),rand(50,200));
    imagesetpixel($img, rand(1,99), rand(1,29), $pointcolor);
}

//为验证码增加干扰元素
//线   
for ($i=0; $i < 3; $i++) { 
    $linecolor = imagecolorallocate($img,rand(80,220),rand(80,220),rand(80,220));
    imageline($img, rand(1,99), rand(1,29),rand(1,99), rand(1,29) ,$linecolor);
}

//输出资源
header("Content-type:image/png");
imagepng($img);

//销毁资源
imagedestroy($img);

10.6 缩略图制作

// 采样赋值

imagecopyresampled(缩略图资源,原图资源,缩略图开始x,缩略图开始y,原图采样起始x,原图采样起始y,存放宽,存放高,原图采样宽,原图采样高);

imagesx($img) ===> 原图采样宽

imagesy($img) ===> 原图采样高

$img_src= './relationship-with-mybatis.png';
$src= imagecreatefrompng($img_src);

//制作缩略图资源
$dst = imagecreatetruecolor(100,100);

//采样赋值
$res = imagecopyresampled($dst,$src,0,0,
                          0,0,100,100,imagesx($src),imagesy($src));

header("Content-type:image/png");
imagepng($dst);

10.7 等比缩放缩略图

//缩略图宽高
$thumb_x = 0;
$thumb_y = 0;
if ($thumb_b >= $thumb_img){
    //缩略图宽高比比原图大
    $thumb_y = 100;
    $thumb_x = floor($thumb_y * $thumb_b);
}else{
    //缩略图宽高比比原图小
    $thumb_x = 100;
    $thumb_y = floor($thumb_x / $thumb_b);
}

10.8 水印图的制作

$img_src = "./relationship-with-mybatis.png";
$watermark_src = "./icon.png";

$img = imagecreatefrompng($img_src);
$watermark = imagecreatefrompng($watermark_src);

//合并图片
$res = imagecopymerge($img,$watermark,0,0,0,0,imagesx($img),imagesy($img),50);
header("Content-type:image/png");
imagepng($img);

imagedestroy($img);
imagedestroy($watermark);

一句话总结:PHP 是一门可嵌入 HTML、即写即跑的服务器端脚本语言,从环境搭建、语法基础到表单、数据库、会话与 GD 图像处理,构成了一套完整的 Web 后端开发体系。