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

PHP 實用代碼片段大全(基礎篇):23 個必收藏的開發技巧

     編輯:PHP 綜合知識

前言

本文收錄 23 個高頻 PHP 代碼片段,涵蓋短信/郵件發送、安全防護、用戶識別、文件處理、數據交換等核心場景。每個片段均附帶調用示例,適合快速複製應用於項目中。

1. 發送短信(基於 MSG91 API)

需替換 $authKey、$senderId 為自己的賬號信息,手機號需包含國家代碼(如中國 86)。

function send_sms($mobile, $msg) {
    $postData = [
        'authkey' => 'YOUR_AUTH_KEY',
        'mobiles' => $mobile,
        'message' => urlencode($msg),
        'sender'  => 'YOUR_SENDER_ID',
        'route'   => 'template',
    ];
    $ch = curl_init('https://control.msg91.com/sendhttp.php');
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
    ]);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

2. 使用 Mandrill 發送郵件

需 composer require mandrill/mandrill 並配置 API Key、發件域名 DNS(SPF/DKIM/DMARC)。

function send_email($to, $subject, $html) {
    $mandrill = new Mandrill('YOUR_API_KEY');
    $message = [
        'html' => $html,
        'text' => strip_tags($html),
        'subject' => $subject,
        'from_email' => 'noreply@yourdomain.com',
        'from_name' => 'Your App',
        'to' => [['email' => $to]],
        'track_opens' => true,
    ];
    return $mandrill->messages->send($message);
}

3. 防 SQL 注入清理函數

現代建議: 改用 PDO 預處理語句(prepare() + execute()),此函數僅作舊項目兼容參考。

function clean($input) {
    if (is_array($input)) return array_map('clean', $input);
    $output = (string)$input;
    if (get_magic_quotes_gpc()) $output = stripslashes($output);
    return htmlentities($output, ENT_QUOTES, 'UTF-8');
}

4. 根據 IP 檢測用戶城市(ipinfodb)

免費額度有限,生產環境建議使用 MaxMind GeoIP2 本地庫或付費 API。

function detect_city($ip) {
    $url = "https://api.ipinfodb.com/v3/ip-city/?key=YOUR_KEY&ip=$ip&format=json";
    $data = json_decode(file_get_contents($url), true);
    return ($data['cityName'] ?? '') . ', ' . ($data['regionName'] ?? '');
}

5. 獲取網頁源碼(帶行號)

function display_sourcecode($url) {
    $lines = file($url);
    foreach ($lines as $num => $line) {
        echo "Line #$num : " . htmlspecialchars($line) . "
"; } }

6. 獲取 Facebook 頁面讚數(Graph API)

需 Access Token,v12+ 版本字段為 fan_count。

function fb_fan_count($page) {
    $json = file_get_contents("https://graph.facebook.com/$page?fields=fan_count&access_token=YOUR_TOKEN");
    return json_decode($json, true)['fan_count'] ?? 0;
}

7. 計算圖片主導顏色

遍歷像素取平均,大圖建議先縮略或使用 K-means 聚類。

function dominant_color($image) {
    $im = imagecreatefromjpeg($image);
    $total = $r = $g = $b = 0;
    for ($x = 0; $x < imagesx($im); $x++) {
        for ($y = 0; $y < imagesy($im); $y++) {
            $rgb = imagecolorat($im, $x, $y);
            $r += ($rgb >> 16) & 0xFF;
            $g += ($rgb >> 8) & 0xFF;
            $b += $rgb & 0xFF;
            $total++;
        }
    }
    return sprintf('#%02x%02x%02x', round($r/$total), round($g/$total), round($b/$total));
}

8. Whois 域名信息查詢

內置主流後綴對應的 WHOIS 服務器,通過 TCP 43 端口查詢。

9. 郵箱格式驗證

function is_validemail($email) {
    return (int)filter_var($email, FILTER_VALIDATE_EMAIL);
}

10. 獲取用戶真實 IP(穿透代理)

function getRealIpAddr() {
    foreach (['HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR'] as $key) {
        if (!empty($_SERVER[$key])) {
            $ips = explode(',', $_SERVER[$key]);
            return trim($ips[0]);
        }
    }
    return 'unknown';
}

11. URL 自動轉超鏈接

使用 preg_replace 替換 eregi_replace(已棄用)。

function makeClickableLinks($text) {
    $text = preg_replace('@(https?://\S+)@i', '$1', $text);
    $text = preg_replace('@(?$1', $text);
    $text = preg_replace('@([\w.-]+@[\w.-]+\.\w+)@', '$1', $text);
    return $text;
}

12. IP 黑名單封禁

支援從文件加載,建議改用 Redis/資料庫存儲以提升性能。

13. 強制文件下載

function force_download($file, $dir = '../log/exports/') {
    $path = $dir . $file;
    if (!file_exists($path)) return false;
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Content-Length: ' . filesize($path));
    readfile($path);
    exit;
}

14. 生成 JSON 數據

echo json_encode(['id' => 1, 'name' => 'Mohit'], JSON_UNESCAPED_UNICODE);

15. 壓縮 ZIP 文件

使用 ZipArchive 類,支援大文件分卷(需擴展)。

16. 解壓 ZIP 文件

調用系統 unzip 命令,Windows 環境建議改用 ZipArchive::extractTo()。

17. 圖片縮放(保持比例)

function resize_image($src, $max_w, $max_h) {
    list($w, $h, $type) = getimagesize($src);
    $ratio = min($max_w/$w, $max_h/$h);
    $new_w = (int)($w * $ratio);
    $new_h = (int)($h * $ratio);
    $dst = imagecreatetruecolor($new_w, $new_h);
    $src_im = match($type) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($src),
        IMAGETYPE_PNG  => imagecreatefrompng($src),
        IMAGETYPE_GIF  => imagecreatefromgif($src),
    };
    imagecopyresampled($dst, $src_im, 0, 0, 0, 0, $new_w, $new_h, $w, $h);
    return $dst;
}

18. 原生 mail() 發送 HTML 郵件

需服務器配置 Postfix/Sendmail,大量發送建議用 SMTP 库(PHPMailer/Symfony Mailer)。

19. 秒數轉人類可讀時間

function secsToStr($secs) {
    $units = ['年'=>31536000, '月'=>2592000, '天'=>86400, '小時'=>3600, '分鐘'=>60, '秒'=>1];
    $str = '';
    foreach ($units as $name => $val) {
        if ($secs >= $val) {
            $num = floor($secs/$val);
            $str .= "$num$name";
            $secs %= $val;
        }
    }
    return $str ?: '0秒';
}

20. MySQL 連接(mysqli 風格)

棄用提示: mysql_* 函數已移除,請使用 mysqli 或 PDO。

$mysqli = new mysqli('localhost', 'root', 'password', 'dbname');
if ($mysqli->connect_errno) die('Connect Error: ' . $mysqli->connect_error);

21. 目錄列表掃描

function list_files($dir) {
    $files = array_diff(scandir($dir), ['.', '..', 'Thumbs.db']);
    foreach ($files as $f) echo "$f
"; }

22. 檢測瀏覽器語言

function get_client_language($available = ['en','zh','ja'], $default = 'en') {
    if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return $default;
    foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
        $code = substr($lang, 0, 2);
        if (in_array($code, $available)) return $code;
    }
    return $default;
}

23. 讀取 CSV 文件

function readCSV($file) {
    $data = [];
    if (($h = fopen($file, 'r')) !== false) {
        while (($row = fgetcsv($h, 1024)) !== false) $data[] = $row;
        fclose($h);
    }
    return $data;
}

總結與避坑指南

  • 第三方 API: 短信、郵件、地理位置、社交數據等片段強依賴第三方服務,請評估 SLA、費率限制、備選方案。
  • 安全函數: SQL 清理、郵箱驗證、IP 獲取等涉及安全邊界,生產環境務必配合 WAF、參數化查詢、輸入白名單等多層防護。
  • 性能優化: 文件讀寫、圖片處理、壓縮解壓等 I/O 密集操作,大文件場景請使用流式處理、異步隊列、CDN 卸載。
  • 現代化替代: 建議將常用片段封裝為 Composer 包,依賴 league/csv、phpmailer/phpmailer、spatie/geocoder 等成熟庫,減少自造輪子。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved