收集 20 個高頻使用的 PHP 實用程式碼片段,涵蓋隨機字串生成、Email 處理、目錄操作等常見需求,適合快速參考與專案整合。
交替使用子音與母音,生成類似單字的字串:
<?php
function readable_random_string($length = 6) {
$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 = 1; $i <= $length / 2; $i++) {
$password .= $conso[array_rand($conso)];
$password .= $vocal[array_rand($vocal)];
}
return $password;
}
// 使用範例
echo readable_random_string(8); // 如 "bavetoku"
?>
<?php
function generate_rand($length) {
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$result = '';
$max = strlen($chars) - 1;
for ($i = 0; $i < $length; $i++) {
$result .= $chars[random_int(0, $max)];
}
return $result;
}
?>
現代化改進: 使用 random_int() 取代 rand(),提供加密級隨機性。
將 Email 轉為 HTML 實體並用 JavaScript 動態輸出:
<?php
function encode_email($email = 'info@domain.com', $linkText = 'Contact Us', $attrs = 'class="emailencoder"') {
// 編碼為 HTML 實體
$email = str_replace(['@', '.'], ['@', '.'], $email);
$linkText = str_replace(['@', '.'], ['@', '.'], $linkText);
$parts = [
'<a href="ma',
'ilto:',
'" ' . $attrs . ' >',
'</a>'
];
$encoded = '<script type="text/javascript">';
$encoded .= "document.write('{$parts[0]}');";
$encoded .= "document.write('{$parts[1]}');";
foreach (str_split($email, 5) as $chunk) {
$encoded .= "document.write('{$chunk}');";
}
$encoded .= "document.write('{$parts[2]}');";
foreach (str_split($linkText, 5) as $chunk) {
$encoded .= "document.write('{$chunk}');";
}
$encoded .= "document.write('{$parts[3]}');";
$encoded .= '</script>';
return $encoded;
}
?>
<?php
function is_valid_email($email, $checkMx = false) {
// 基本格式驗證
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
if ($checkMx) {
list($username, $domain) = explode('@', $email);
return checkdnsrr($domain, 'MX');
}
return true;
}
// 使用
var_dump(is_valid_email('test@example.com', true));
?>
現代化: 使用 filter_var() 取代已棄用的 eregi()。
<?php
function list_files($dir) {
if (!is_dir($dir)) return;
$files = new DirectoryIterator($dir);
foreach ($files as $file) {
if ($file->isDot() || $file->getFilename() === 'Thumbs.db') continue;
echo '<a target="_blank" href="' . $dir . $file->getFilename() . '">' . $file->getFilename() . '</a><br>';
}
}
?>
<?php
function destroyDir($dir, $virtual = false) {
$ds = DIRECTORY_SEPARATOR;
$dir = $virtual ? realpath($dir) : $dir;
$dir = rtrim($dir, $ds);
if (!is_dir($dir) || !$handle = opendir($dir)) return;
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$path = $dir . $ds . $file;
is_dir($path) ? destroyDir($path) : unlink($path);
}
closedir($handle);
rmdir($dir);
}
?>
| 編號 | 功能 | 關鍵函式/技術 |
|---|---|---|
| 7 | 取得檔案擴展名 | pathinfo() |
| 8 | 檔案大小人類可讀格式 | 遞迴除以 1024 |
| 9 | 建立多層目錄 | mkdir($path, 0755, true) |
| 10 | 安全檔案下載 | readfile() + Header 控制 |
| 11 | JSON 回應輸出 | json_encode() + 正確 Content-Type |
| 12 | CURL 發送 POST 請求 | curl_init(), CURLOPT_POSTFIELDS |
| 13 | 產生 CSV 匯出 | fputcsv() |
| 14 | 圖片縮圖生成 | GD imagecopyresampled() |
| 15 | Session 防固定攻擊 | session_regenerate_id(true) |
| 16 | 輸入資料清理 | htmlspecialchars(), filter_input() |
| 17 | 記憶體使用量監控 | memory_get_peak_usage() |
| 18 | 執行時間測量 | microtime(true) |
| 19 | 陣列分頁處理 | array_slice() |
| 20 | 多語言支援基礎 | 陣列或 gettext |
random_int() 或 random_bytes()