首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

10 個超實用 PHP 程式碼片段:垃圾郵件過濾、隨機顏色、檔案下載、頁面排名等

     編輯:PHP 綜合知識

精選 10 個高頻使用的 PHP 實用片段,涵蓋字串處理、網路操作、圖片處理、快取、安全性等常見需求。每段代碼即拿即用,附參數說明與使用範例,建議收藏備查。

1. 黑名單關鍵字過濾

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';

2. 隨機十六進位顏色產生器

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

3. cURL 下載遠端檔案(支援大檔、斷點續傳基礎)

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);

4. Alexa / Google PageRank 查詢

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');

5. 強制下載檔案(含資料庫查詢、Header 完整設定)

$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: /");

6. 由 Email 顯示 Gravatar 大頭照

$email = 'user@example.com';
$gravatar = 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . '?s=80&d=mp';
echo "<img src='{$gravatar}' alt='Avatar' />";

7. cURL 取得 FeedBurner 訂閱數

$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]}";

8. 相對時間格式化(X 秒/分/小時/天前)

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

9. GD 裁剪圖片(固定尺寸、白底填充)

$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);

10. 網站存活監測(cURL 檢查 HTTP 狀態碼)

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';

使用建議

  • 片段 1、4、7 依賴外部服務,正式環境建議快取結果、設定超時。
  • 片段 3、5 處理檔案下載,注意記憶體限制,大檔案建議分塊寫入。
  • 片段 9 為同步裁剪,大量圖片建議使用 Imagine、Intervention Image 等庫或非同步佇列處理。
  • 所有片段請依專案命名規範封裝為函數/類別方法,避免全域汙染。

將常用片段整理為個人/團隊程式碼庫,能大幅提升開發效率與代碼品質一致性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved