空合并运算符
$name = $_GET['name'] ?? 'guest';
$config = $options['timeout'] ?? $defaults['timeout'] ?? 30;后端
技巧、工具函数、校验与文件操作常用片段。 — 共 19 条
共 19 条代码片段
$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_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;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;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);
}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);
}$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);
}