收集整理 20 個高頻實用 PHP 代碼片段,涵蓋字串生成、郵件處理、目錄操作、數據驗證等常見場景。拿來即用,提升開發效率。
function readable_random_string(int $length = 6): string {
if ($length % 2 !== 0) $length++; // 必須為偶數
$conso = ['b','c','d','f','g','h','j','k','l','m','n','p','r','s','t','v','w','x','y','z'];
$vocal = ['a','e','i','o','u'];
$password = '';
for ($i = 0; $i < $length/2; $i++) {
$password .= $conso[array_rand($conso)] . $vocal[array_rand($vocal)];
}
return $password;
}
echo readable_random_string(8); // 如: "bavetozi"
function generate_random_string(int $length = 12): string {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+[]{}|;:,.<>?';
$bytes = random_bytes($length);
$result = '';
for ($i = 0; $i < $length; $i++) {
$result .= $chars[$bytes[$i] % strlen($chars)];
}
return $result;
}
echo generate_random_string(16); // 高強度隨機密碼
安全提示: 使用 random_bytes() (CSPRNG) 而非 rand()/mt_rand()。
function encode_email(string $email, string $linkText = 'Contact Us', string $attrs = 'class="email"') : string {
$email = str_replace(['@', '.'], ['@', '.'], $email);
$linkText = str_replace(['@', '.'], ['@', '.'], $linkText);
return '<a href="mailto:' . $email . '" ' . $attrs . '>' . $linkText . '</a>';
}
echo encode_email('admin@example.com', '聯繫我們');
現代瀏覽器可正常渲染點擊,爬蟲難以直接提取純文本郵箱。
function is_valid_email(string $email, bool $checkMx = false): bool {
// 格式驗證 (RFC 5322 簡化版)
if (!preg_match('/^[\w.+-]+@[\w-]+\.[\w.-]+$/', $email)) {
return false;
}
if ($checkMx) {
list(, $domain) = explode('@', $email);
return checkdnsrr($domain, 'MX'); // 檢查域名是否有郵件交換記錄
}
return true;
}
var_dump(is_valid_email('test@example.com', true));
function list_files_recursive(string $dir): array {
$result = [];
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
foreach ($iterator as $file) {
$result[] = [
'path' => $file->getPathname(),
'name' => $file->getFilename(),
'size' => $file->getSize(),
'mtime' => $file->getMTime(),
'is_dir' => $file->isDir(),
];
}
return $result;
}
print_r(list_files_recursive(__DIR__));
// 方法一:pathinfo (推薦,內建、可靠)
$ext = pathinfo($filename, PATHINFO_EXTENSION);
// 方法二:SplFileInfo (物件導向)
$ext = (new SplFileInfo($filename))->getExtension();
// 方法三:strrchr + substr (舊版兼容)
$ext = substr(strrchr($filename, '.'), 1);
function format_bytes(int $bytes, int $precision = 2): string {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
return round($bytes / (1024 ** $pow), $precision) . ' ' . $units[$pow];
}
echo format_bytes(123456789); // 117.74 MB
function generate_slug(string $text, string $divider = '-'): string {
// 轉小寫、移除非字母數字、替換空格、去重分隔符、去首尾分隔符
$slug = mb_strtolower($text, 'UTF-8');
$slug = preg_replace('/[^\p{L}\p{N}]+/u', $divider, $slug);
$slug = trim($slug, $divider);
return $slug;
}
echo generate_slug('你好,世界!PHP 教程'); // 你好-世界-php-教程
function safe_redirect(string $url, int $status = 302): void {
// 僅允許相對路徑或同域絕對路徑
$parsed = parse_url($url);
if (isset($parsed['host']) && $parsed['host'] !== $_SERVER['HTTP_HOST']) {
$url = '/'; // 非本域回首頁
}
header('Location: ' . $url, true, $status);
exit;
}
safe_redirect('/dashboard'); // 安全
function chunk_array_iter(array $array, int $chunkSize): Generator {
$chunk = [];
foreach ($array as $key => $value) {
$chunk[$key] = $value;
if (count($chunk) === $chunkSize) {
yield $chunk;
$chunk = [];
}
}
if ($chunk) yield $chunk;
}
// 用法:大數據導出、批次入庫
foreach (chunk_array_iter(range(1, 10000), 500) as $batch) {
// 處理 $batch (500 條)
}
fputcsv + php://output 串流輸出。strtr 替換佔位符 {var}。HTTP_X_FORWARDED_FOR, HTTP_CLIENT_IP。BaconQrCode 或 Endroid/QrCode。apcu/redis/文件快取。yield 實現無限序列。similar_text() 或 levenshtein()。$_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']。將常用片段封裝為 Helper 類或 trait,通過 Composer 自動加載,專案間復用。注意 PHP 版本要求 (建議 8.1+),善用類型聲明、嚴格模式。