后端

PHP

技巧、工具函数、校验与文件操作常用片段。 — 共 19 条

共 19 条代码片段

A. 技巧类

空合并运算符

$name = $_GET['name'] ?? 'guest';
$config = $options['timeout'] ?? $defaults['timeout'] ?? 30;

三元运算符简写

$status = $active ?: 'inactive';
// 等价于 $active ? $active : 'inactive'

数组去重

$list = array_values(array_unique($arr));

过滤空值

$list = array_values(array_filter($arr));

JSON 编解码

$json = json_encode($data, JSON_UNESCAPED_UNICODE);
$data = json_decode($json, true);

判断字符串包含

// PHP 8+
str_contains($haystack, $needle);

// 兼容写法
strpos($haystack, $needle) !== false;

调试输出

echo '<pre>';
print_r($data);
echo '</pre>';
exit;

// 或
var_dump($data);
exit;

B. 常用函数

获取客户端 IP

function getClientIp(): string
{
    $keys = [
        'HTTP_X_FORWARDED_FOR',
        'HTTP_CLIENT_IP',
        'REMOTE_ADDR',
    ];
    foreach ($keys as $key) {
        if (!empty($_SERVER[$key])) {
            $ip = explode(',', $_SERVER[$key])[0];
            return trim($ip);
        }
    }
    return '0.0.0.0';
}

生成随机字符串

function randomString(int $length = 16): string
{
    return substr(bin2hex(random_bytes($length)), 0, $length);
}

格式化文件大小

function formatBytes(int $bytes, int $precision = 2): string
{
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = $bytes > 0 ? floor(log($bytes, 1024)) : 0;
    $pow = min($pow, count($units) - 1);
    $bytes /= (1024 ** $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}

分页计算

$page = max(1, (int) ($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;
$totalPages = (int) ceil($total / $limit);

安全跳转

header('Location: ' . $url);
exit;

C. 验证类

手机号验证

function checkMobile(string $val): bool
{
    return (bool) preg_match('/^1[3-9]\d{9}$/', $val);
}

邮箱验证

function checkEmail(string $val): bool
{
    return (bool) filter_var($val, FILTER_VALIDATE_EMAIL);
}

URL 验证

function checkUrl(string $val): bool
{
    return (bool) filter_var($val, FILTER_VALIDATE_URL);
}

身份证号验证

function checkIdCard(string $val): bool
{
    return (bool) preg_match('/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/', $val);
}

D. 文件类

读取 JSON 文件

$data = json_decode(file_get_contents($path), true);
if (json_last_error() !== JSON_ERROR_NONE) {
    throw new RuntimeException(json_last_error_msg());
}

写入文件

file_put_contents($path, $content, LOCK_EX);

// 追加
file_put_contents($path, $content, FILE_APPEND | LOCK_EX);

确保目录存在

if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
}