现在很多便宜的虚拟主机还停留在 PHP 5.4,而很多教程和开源程序都要求 PHP 7+。其实不用慌,几个常用函数自己兼容一下就能跑。
**1. password_hash / password_verify**
PHP 5.5 才引入这两个函数,5.4 没有。其实用 crypt 函数就能实现:
```php
function password_hash($password, $algo = null, $options = array()) {
$salt = substr(str_replace('+', '.', base64_encode(md5(uniqid('', true), true))), 0, 22);
return crypt($password, '$2y$10$' . $salt);
}
function password_verify($password, $hash) {
return crypt($password, $hash) === $hash;
}
```
这样存出来的 hash 和 PHP 原生的是兼容的,以后升级版本也不用改数据。
**2. ?? 运算符**
PHP 7 才有的 null 合并运算符,5.4 不支持。
之前写 `$name = $_GET['name'] ?? '匿名';`
5.4 要写成 `$name = isset($_GET['name']) ? $_GET['name'] : '匿名';`
**3. 数组简写**
`[]` 这种短数组语法 PHP 5.4 开始支持了,这个没问题。但是 `list()` 解构赋值那些新写法不行。
**4. 注意事项**
- 不要用 `define()` 定义数组常量(PHP 7+ 才支持)
- 不要用标量类型声明返回值类型
- 不要用 `finally` 关键字
- 错误处理最好关掉 display_errors,不然报错信息露出来不安全
总结:老 PHP 版本虽然不方便,但只要避开新语法,常用功能都能实现。
**1. password_hash / password_verify**
PHP 5.5 才引入这两个函数,5.4 没有。其实用 crypt 函数就能实现:
```php
function password_hash($password, $algo = null, $options = array()) {
$salt = substr(str_replace('+', '.', base64_encode(md5(uniqid('', true), true))), 0, 22);
return crypt($password, '$2y$10$' . $salt);
}
function password_verify($password, $hash) {
return crypt($password, $hash) === $hash;
}
```
这样存出来的 hash 和 PHP 原生的是兼容的,以后升级版本也不用改数据。
**2. ?? 运算符**
PHP 7 才有的 null 合并运算符,5.4 不支持。
之前写 `$name = $_GET['name'] ?? '匿名';`
5.4 要写成 `$name = isset($_GET['name']) ? $_GET['name'] : '匿名';`
**3. 数组简写**
`[]` 这种短数组语法 PHP 5.4 开始支持了,这个没问题。但是 `list()` 解构赋值那些新写法不行。
**4. 注意事项**
- 不要用 `define()` 定义数组常量(PHP 7+ 才支持)
- 不要用标量类型声明返回值类型
- 不要用 `finally` 关键字
- 错误处理最好关掉 display_errors,不然报错信息露出来不安全
总结:老 PHP 版本虽然不方便,但只要避开新语法,常用功能都能实现。
广告
成都招摇科技
| 专业网站建设服务,从域名到上线一站式搞定,咨询微信:-62040
评论
还没有评论,来抢沙发。
登录后可以发表评论。去登录 · 免费注册