精選 10 個高頻使用的 PHP 實用片段,涵蓋字串處理、網路操作、圖片處理、快取、安全性等常見需求。每段代碼即拿即用,附參數說明與使用範例,建議收藏備查。
function is_spam($text, $file, $split = ':', $regex = false) {
$handle = fopen($file, 'rb');
$contents = fread($handle, filesize($file));
fclose($handle);
$lines = explode("\n", $contents);
$arr = [];
foreach ($lines as $line) {
list($word, $count) = explode($split, $line);
$arr[$regex ? $word : preg_quote($word)] = $count;
}
preg_match_all("~" . implode('|', array_keys($arr)) . "~", $text, $matches);
$temp = [];
foreach ($matches[0] as $match) {
if (!isset($temp[$match])) $temp[$match] = 0;
$temp[$match]++;
if ($temp[$match] >= $arr[$match]) return true;
}
return false;
}
// 使用:spam.txt 格式 "關鍵字:閾值"
$file = 'spam.txt';
$str = 'This string has cat, dog word';
echo is_spam($str, $file) ? 'spam' : 'clean';
function randomColor() {
$str = '#';
for ($i = 0; $i < 6; $i++) {
$randNum = rand(0, 15);
$str .= dechex($randNum); // 0-9, a-f
}
return $str;
}
echo randomColor(); // 例:#a3f21e
set_time_limit(0);
$url = 'https://example.com/large_file.zip';
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_AUTOREFERER => true,
CURLOPT_BINARYTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_TIMEOUT => 300,
]);
$content = curl_exec($ch);
curl_close($ch);
$pathinfo = pathinfo($url);
$filename = basename($pathinfo['basename']);
if (preg_match('/[^0-9a-z._-]/i', $filename)) $filename = md5(microtime(true)) . '.' . $pathinfo['extension'];
file_put_contents($filename, $content);
function page_rank($page, $type = 'alexa') {
$urls = [
'alexa' => "https://alexa.com/siteinfo/{$page}",
'google' => "https://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:https://{$page}"
];
$handle = @fopen($urls[$type], 'r');
if (!$handle) return false;
$content = stream_get_contents($handle);
fclose($handle);
$content = preg_replace('~\s+~', '', $content);
if ($type === 'alexa') {
if (preg_match('~<div class="data (down|up)"><img.+?>(.+?) </div>~im', $content, $m)) return $m[2];
} else {
$rank = explode(':', $content);
return $rank[2] ?? false;
}
return false;
}
echo 'Alexa: ' . page_rank('example.com');
echo 'Google: ' . page_rank('example.com', 'google');
$filename = $_GET['file'];
// 假設從資料庫查詢檔案資訊
// $row = $db->query("SELECT * FROM files WHERE id = ?", [$filename])->fetch();
$row = ['FileName' => 'report.pdf', 'FilePath' => '/var/www/files/report.pdf']; // 模擬
if ($row) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"" . basename($row['FileName']) . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($row['FilePath']));
readfile($row['FilePath']);
exit;
}
header("Location: /");
$email = 'user@example.com';
$gravatar = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s=80&d=mp';
echo "<img src='{$gravatar}' alt='Avatar' />";
$ch = curl_init('https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=YOUR_FEED_ID');
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => 1, CURLOPT_CONNECTTIMEOUT => 2]);
$content = curl_exec($ch);
curl_close($ch);
if (preg_match('/circulation="(\d+)"/i', $content, $m)) echo "訂閱數: {$m[1]}";
function ago($time) {
$periods = ['second', 'minute', 'hour', 'day', 'week', 'month', 'year', 'decade'];
$lengths = [60, 60, 24, 7, 4.35, 12, 10];
$now = time();
$diff = $now - $time;
$tense = 'ago';
for ($j = 0; $diff >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$diff /= $lengths[$j];
}
$diff = round($diff);
return $diff . ' ' . $periods[$j] . ($diff != 1 ? 's' : '') . ' ' . $tense;
}
echo ago(strtotime('-2 hours')); // 2 hours ago
$src = imagecreatefromjpeg('test.jpg');
list($w, $h) = getimagesize('test.jpg');
$dst = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($dst, 255, 255, 255);
imagefill($dst, 0, 0, $white);
imagecopy($dst, $src, 0, 0, 0, 0, 100, 100);
header('Content-Type: image/png');
imagepng($dst);
imagedestroy($src);
imagedestroy($dst);
function visit($url) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_USERAGENT => 'Mozilla/5.0',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_TIMEOUT => 5,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false,
]);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $code >= 200 && $code < 300;
}
echo visit('https://google.com') ? 'OK' : 'DOWN';
將常用片段整理為個人/團隊程式碼庫,能大幅提升開發效率與代碼品質一致性。