PHP 8.6 升级检查:那些不报错、但行为已经变了的项
发布说明:
PHP 8.6 里有相当一部分改动不会让代码立刻报错,只在 E_DEPRECATED 日志里留一行,或者干脆静默改了默认行为。下面按「上线前必须先查」的顺序整理。
1. Session 默认值更严
三个 ini 默认值变了:
session.use_strict_mode默认开启:客户端自带一个未初始化的 session id 不再被接受,PHP 会重新生成 idsession.cookie_httponly默认开启session.cookie_samesite默认Lax
Lax 会影响跨站 POST 之后跳转回来的请求带不带 session cookie,典型场景是第三方支付回调、跨域表单提交。strict_mode 会影响所有依赖客户端固定 PHPSESSID 的老逻辑(比如自己拼 URL 传 session id、或者多机共享 session 但没做 id 校验)。
查当前生效值:
php -i | grep -E '^session\.(use_strict_mode|cookie_httponly|cookie_samesite)'
需要保持旧行为时,在 php.ini 或 pool 配置里显式覆盖:
session.use_strict_mode = 0
session.cookie_httponly = 0
session.cookie_samesite =
2. 自定义 session handler 缺 create_sid() / validateId()
只实现 SessionHandlerInterface 的 handler 现在被弃用,需要同时提供:
SessionIdInterface::create_sid()SessionUpdateTimestampHandlerInterface::validateId()
final class RedisSessionHandler implements
SessionHandlerInterface,
SessionIdInterface,
SessionUpdateTimestampHandlerInterface
{
public function create_sid(): string
{
return bin2hex(random_bytes(16));
}
public function validateId(string $id): bool
{
return (bool) $this->redis->exists($this->prefix . $id);
}
// open/close/read/write/destroy/gc/updateTimestamp ...
}
先找出所有自建 handler:
grep -rn "SessionHandlerInterface\|SessionUpdateTimestampHandlerInterface" --include=*.php .
3. trim() / ltrim() / rtrim() 默认也去 \f
默认字符列表新增了换页符 \f。解析定宽报文、CSV、打印流输出时,字段尾部可能被多切掉一个字符。
trim("abc\f"); // 8.6 起返回 "abc"
trim($v, " \t\n\r\0\x0B"); // 显式给字符列表,行为不变
只传一个参数的 trim() 调用都要过一遍,尤其是处理二进制或定长文本的地方。
4. fclose() / file_put_contents() / copy() 失败返回 false
以前 flush 或 close 失败会被静默忽略,现在返回 false。写日志、写缓存的地方如果从不检查返回值,磁盘满、NFS 卡死、只读挂载都会变成「以为写成功了」。
if (file_put_contents($path, $data) === false) {
throw new RuntimeException("write failed: {$path}");
}
$fh = fopen($path, 'w');
fwrite($fh, $data);
if (!fclose($fh)) {
// 之前的 fwrite 不一定已经落盘
throw new RuntimeException("close failed: {$path}");
}
5. finally 里的 return 被弃用
finally 中 return 会吞掉 try/catch 抛出的异常,或者覆盖已有返回值,两种都是排查起来很痛的 bug。
function f(): int
{
try {
throw new RuntimeException('boom');
} finally {
return 1; // 异常被丢弃
}
}
自查(ripgrep 的 -U 允许多行匹配):
rg -U 'finally\s*\{[^}]*\breturn\b' -g '*.php' .
没有 rg 时用 grep 的 -Pzo:
grep -rnPzo 'finally\s*\{[^}]*\breturn\b' --include=*.php .
6. mbstring 正则函数弃用
mb_ereg()、mb_split() 等底层依赖 Oniguruma,该库已不再维护,整组函数弃用。改用带 u 修饰符的 PCRE:
// 旧
mb_ereg('^\d+$', $s);
// 新
preg_match('/^\d+$/u', $s);
注意 u 修饰符要求输入是合法 UTF-8,否则 preg_* 直接返回 false;mb_ereg 对非法字节序列的容忍度更高,输入源不可控时要在调用前做一次校验。
grep -rnE '\bmb_(ereg|eregi|ereg_replace|eregi_replace|split|regex_set_options|regex_get_options)\s*\(' --include=*.php .
7. 类型判断别名弃用
is_double() / is_long() / is_integer() / doubleval() 弃用,对应 is_float() / is_int() / floatval()。同批还有 spl_object_hash() → spl_object_id()、spl_classes() → ReflectionExtension::getClassNames()。
grep -rnE '\b(is_double|is_long|is_integer|doubleval|spl_object_hash|spl_classes)\s*\(' --include=*.php .
spl_object_hash() 换成 spl_object_id() 不是纯改名:返回值从 32 位十六进制字符串变成整数,而且对象被回收后 id 可能复用。把 hash 当持久键存过的地方要一并检查。
8. strcoll() 与 SORT_LOCALE_STRING 弃用
改用 intl 扩展的 Collator:
$collator = new Collator('zh_CN');
usort($rows, fn(array $a, array $b) => $collator->compare($a['name'], $b['name']));
9. 越界值、非法 flag、含 NUL 的字符串改抛 ValueError
一批函数不再静默截断或忽略,而是抛 ValueError。原来靠「返回 false 或宽松处理」的分支要改成前置校验或 try/catch。
if (str_contains($path, "\0")) {
throw new InvalidArgumentException('NUL byte in path');
}
含 NUL 的字符串在文件路径、header、URL 拼接里最常见。上线前对进入这些函数的输入做一次集中过滤,比逐个调用点包 try 更省事。
10. 向数组参数传对象被弃用
array_walk()、array_walk_recursive()、http_build_query()、mb_convert_variables(),以及压缩函数和过滤器,传对象时不再隐式转成属性数组。
// 旧:依赖对象隐式转数组
http_build_query($dto);
// 新:显式转换
http_build_query(get_object_vars($dto));
这类调用 grep 命中率有限,用 PHPStan 扫一遍比正则可靠:
vendor/bin/phpstan analyse src --level=5
11. php://filter 超过 16 个 filter
未设置 filter.max_filter_count context 选项、链上 filter 又超过 16 个时弃用。先把所有用法列出来数一数:
grep -rn "php://filter" --include=*.php .
确实需要长链的,在 stream context 的 filter 选项里显式设置 max_filter_count。
12. 其余弃用项
这些不影响运行时行为,但会进 deprecation 日志:
__construct()/__destruct()返回值、把它们声明成 generator;__debugInfo()声明可空返回类型let/is作为类名、函数名、常量名;_作为常量名;namespace作为类常量名;readonly作为函数名define()传第三个参数$allow_string为false时,is_a()/is_subclass_of()仍传字符串类名metaphone()、mysqli_get_charset()、mysqli_stmt_init()SplFileObject的 CSV 方法,ArrayIterator的排序、flag 和序列化方法
落地顺序
php -l 只查语法,查不出弃用。要在 CI 里把 E_ALL 打开跑到零 deprecation:
php -d error_reporting=-1 -d display_errors=1 vendor/bin/phpunit
需要让 deprecation 直接判定失败时:
php -d error_reporting=-1 -d display_errors=stderr script.php 2>&1 \
| grep -q 'Deprecated:' && exit 1
顺序上,先在 CI 里跑到零 deprecation 再上线;第 1 节那三个 session 默认值不要和代码改动放进同一批发布,单独在灰度环境验证登录态和跨站跳转,确认 Lax 和 strict_mode 不会把存量用户踢下线,再全量。