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

PHP 開發常用 10 大代碼範例:黑名單過濾、隨機色、檔案下載、PageRank、Gravatar、RSS 訂閱數、時間差、圖片裁切、網站存活檢測

     編輯:PHP 相關知識

10 個實戰常見功能的精簡實作

1. 黑名單關鍵字過濾

function isSpam($text, $dictFile) {
    $lines = file($dictFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $patterns = [];
    foreach ($lines as $line) {
        [$word, $limit] = explode(':', $line);
        $patterns[$word] = (int)$limit;
    }
    $regex = '~' . implode('|', array_map('preg_quote', array_keys($patterns))) . '~';
    preg_match_all($regex, $text, $matches);
    $counts = array_count_values($matches[0]);
    foreach ($counts as $word => $cnt) {
        if ($cnt >= ($patterns[$word] ?? PHP_INT_MAX)) return true;
    }
    return false;
}
// spam.txt 格式:badword:3

2. 隨機十六進位顏色

function randomHexColor() {
    return '#' . str_pad(dechex(mt_rand(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}

3. 遠端檔案下載儲存

function downloadFile($url) {
    $info = pathinfo($url);
    $fileName = ($info['filename'] ?? 'file') . '.' . ($info['extension'] ?? 'bin');
    $fileName = preg_replace('/[^a-z0-9._-]/i', '', $fileName) ?: md5(microtime(true)) . '.' . ($info['extension'] ?? 'bin');
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER=>1, CURLOPT_BINARYTRANSFER=>1, CURLOPT_FOLLOWLOCATION=>1, CURLOPT_AUTOREFERER=>1]);
    $data = curl_exec($ch);
    curl_close($ch);
    file_put_contents($fileName, $data);
    return $fileName;
}

4. Alexa / Google PageRank 查詢

function getPageRank($domain, $type = 'alexa') {
    $urls = [
        'alexa' => "https://alexa.com/siteinfo/$domain",
        'google' => "https://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:https://$domain",
    ];
    $html = file_get_contents($urls[$type]);
    if ($type === 'alexa') {
        if (preg_match('~<div class="data (down|up)"><img.+?>(.+?)</div>~is', $html, $m)) return $m[2];
    } else {
        $parts = explode(':', $html);
        return $parts[2] ?? false;
    }
    return false;
}

5. 資料庫檔案強制下載

// 從 DB 取得檔案路徑後
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($filePath));
header("Content-Length: " . filesize($filePath));
readfile($filePath);
exit;

6. 依 Email 顯示 Gravatar

function gravatarUrl($email, $size = 80) {
    return 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($email))) . "?s=$size&d=mp";
}
// 使用
echo '<img src="' . gravatarUrl($user->email) . '" />';

7. cURL 取得 FeedBurner 訂閱數

function getFeedburnerCount($feedId) {
    $url = "https://feedburner.google.com/api/awareness/1.0/GetFeedData?id=$feedId";
    $xml = simplexml_load_string(curlExec($url));
    return (string)($xml->feed->entry->circulation ?? 0);
}

8. 相對時間格式化

function timeAgo($timestamp) {
    $diff = time() - $timestamp;
    $units = [31536000=>'年',2592000=>'月',604800=>'週',86400=>'天',3600=>'小時',60=>'分鐘',1=>'秒'];
    foreach ($units as $sec => $unit) {
        if ($diff >= $sec) return floor($diff/$sec) . $unit . '前';
    }
    return '剛剛';
}

9. 圖片裁切(正方形縮圖)

function cropThumbnail($srcPath, $size, $destPath) {
    $src = imagecreatefromjpeg($srcPath);
    $w = imagesx($src); $h = imagesy($src);
    $side = min($w, $h);
    $x = ($w - $side) / 2;
    $y = ($h - $side) / 2;
    $dst = imagecreatetruecolor($size, $size);
    imagecopyresampled($dst, $src, 0, 0, $x, $y, $size, $size, $side, $side);
    imagejpeg($dst, $destPath, 90);
    imagedestroy($src); imagedestroy($dst);
}

10. 網站存活檢測

function isSiteUp($url, $timeout = 5) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_TIMEOUT => $timeout,
        CURLOPT_USERAGENT => 'Mozilla/5.0 (HealthCheck)',
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    return $code >= 200 && $code < 300;
}

整理重點

  • 所有外部請求(cURL、file_get_contents)必須設定 timeout,避免阻塞。
  • 資料庫操作請改用 PDO + Prepared Statements,範例為示意簡化。
  • 檔案下載、圖片處理需注意 memory_limit 與 max_execution_time。
  • PageRank、FeedBurner 等外部 API 可能已停用或需金鑰,請以當前可用服務為準。

這 10 個範例涵蓋內容安全、視覺呈現、外部整合、檔案處理、監控檢測等核心場景,可直接納入專案工具庫。

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