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

PHP 開發必備:23 個實用代碼片段精選(簡訊、郵件、防注入、圖片處理等)

     編輯:PHP 相關知識

前言

整理 23 個高頻使用的 PHP 代碼片段,涵蓋通訊、安全、檔案、圖片、資料格式等面向,適合快速複製調整投入專案。

片段列表

1. 發送簡訊(透過 MSG91 API)

function sendSms($mobile, $message) {
    $authKey = 'YOUR_AUTH_KEY';
    $senderId = 'YOUR_SENDER_ID'; // 6 字元
    $postData = [
        'authkey' => $authKey,
        'mobiles' => $mobile,
        'message' => urlencode($message),
        'sender' => $senderId,
        '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,
    ]);
    return curl_exec($ch);
}

2. 發送郵件(Mandrill API)

function sendEmail($to, $subject, $html) {
    require 'Mandrill.php';
    $mandrill = new Mandrill('YOUR_API_KEY');
    $message = [
        'html' => $html,
        'subject' => $subject,
        'from_email' => 'noreply@example.com',
        'from_name' => '系統通知',
        'to' => [['email' => $to]],
        'track_opens' => true,
    ];
    return $mandrill->messages->send($message);
}

3. SQL 注入防護:輸入清理

function cleanInput($input) {
    if (is_array($input)) {
        return array_map(__FUNCTION__, $input);
    }
    $input = trim($input);
    if (get_magic_quotes_gpc()) $input = stripslashes($input);
    return htmlentities($input, ENT_QUOTES, 'UTF-8');
}

4. 依 IP 偵測城市(ipinfodb)

function detectCity($ip) {
    $url = "https://ipinfodb.com/ip_locator.php?ip=" . urlencode($ip);
    $html = file_get_contents($url);
    if (preg_match('{<li>City : ([^<]*)</li>}i', $html, $m)) $city = $m[1];
    if (preg_match('{<li>State/Province : ([^<]*)</li>}i', $html, $m)) $state = $m[1];
    return isset($city, $state) ? "$city, $state" : 'UNKNOWN';
}

5. 取得網頁原始碼

function fetchSource($url) {
    $lines = file($url);
    $out = '';
    foreach ($lines as $i => $line) {
        $out .= "Line #<b>$i</b> : " . htmlspecialchars($line) . "<br>";
    }
    return $out;
}

6. 取得 FB 粉絲頁讚數

function getFbLikes($pageName) {
    $data = json_decode(file_get_contents("https://graph.facebook.com/$pageName"));
    return $data->likes ?? 0;
}

7. 計算圖片主色調

function dominantColor($imagePath) {
    $im = imagecreatefromjpeg($imagePath);
    $r = $g = $b = $total = 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('rgb(%d,%d,%d)', round($r/$total), round($g/$total), round($b/$total));
}

8. Whois 域名查詢

function whois($domain) {
    $domain = strtolower(trim($domain));
    $domain = preg_replace('/^https?:\/\//', '', $domain);
    $domain = preg_replace('/^www\./', '', $domain);
    $domain = explode('/', $domain)[0];
    $tld = array_pop(explode('.', $domain));
    $servers = ['com'=>'whois.internic.net','net'=>'whois.internic.net','org'=>'whois.pir.org','tw'=>'whois.twnic.net'];
    if (!isset($servers[$tld])) return "Unsupported TLD: $tld";
    $fp = fsockopen($servers[$tld], 43);
    fputs($fp, "$domain\r\n");
    $out = '';
    while (!feof($fp)) $out .= fgets($fp, 128);
    fclose($fp);
    return $out;
}

9. Email 格式驗證

function isValidEmail($email) {
    return (bool)filter_var($email, FILTER_VALIDATE_EMAIL);
}

10. 取得真實 Client IP

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

11. 文字中的 URL 自動轉連結

function autoLink($text) {
    $text = preg_replace('@(https?://[-\w.]+[^[:space:]]*)@', '<a href="$1" target="_blank">$1</a>', $text);
    $text = preg_replace('/(?

12. IP 黑名單封鎖

$deny = ['192.168.1.100', '10.0.0.5'];
if (in_array(getRealIp(), $deny)) {
    exit('Your IP is blocked.');
}

13. 強制檔案下載

function forceDownload($filePath, $fileName = null) {
    if (!file_exists($filePath)) return false;
    $fileName = $fileName ?? basename($filePath);
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . $fileName . '"');
    header('Content-Length: ' . filesize($filePath));
    readfile($filePath);
    exit;
}

14. 產生 JSON 回應

header('Content-Type: application/json');
echo json_encode(['id' => 1, 'name' => 'John', 'tags' => ['php', 'api']], JSON_UNESCAPED_UNICODE);

15. 建立 ZIP 壓縮檔

function createZip(array $files, $zipPath, $overwrite = false) {
    if (file_exists($zipPath) && !$overwrite) return false;
    $zip = new ZipArchive();
    if ($zip->open($zipPath, $overwrite ? ZipArchive::OVERWRITE : ZipArchive::CREATE) !== true) return false;
    foreach ($files as $file) if (file_exists($file)) $zip->addFile($file, basename($file));
    $zip->close();
    return file_exists($zipPath);
}

16. 解壓縮 ZIP

function unzip($zipPath, $destDir) {
    $zip = new ZipArchive();
    if ($zip->open($zipPath) !== true) return false;
    $zip->extractTo($destDir);
    $zip->close();
    return true;
}

17. 圖片等比縮放

function resizeImage($srcPath, $maxW, $maxH, $destPath) {
    list($w, $h, $type) = getimagesize($srcPath);
    if ($w <= $maxW && $h <= $maxH) return copy($srcPath, $destPath);
    $ratio = min($maxW/$w, $maxH/$h);
    $newW = (int)($w * $ratio);
    $newH = (int)($h * $ratio);
    $src = match($type) {
        IMAGETYPE_JPEG => imagecreatefromjpeg($srcPath),
        IMAGETYPE_PNG => imagecreatefrompng($srcPath),
        IMAGETYPE_GIF => imagecreatefromgif($srcPath),
        default => return false,
    };
    $dst = imagecreatetruecolor($newW, $newH);
    imagecopyresampled($dst, $src, 0, 0, 0, 0, $newW, $newH, $w, $h);
    switch ($type) {
        case IMAGETYPE_JPEG: imagejpeg($dst, $destPath, 90); break;
        case IMAGETYPE_PNG: imagepng($dst, $destPath); break;
        case IMAGETYPE_GIF: imagegif($dst, $destPath); break;
    }
    imagedestroy($src); imagedestroy($dst);
    return true;
}

18. 使用 mail() 發送 HTML 郵件

function mailHtml($to, $subject, $html) {
    $headers = "From: System <noreply@example.com>\r\n";
    $headers .= "Reply-To: noreply@example.com\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    return mail($to, $subject, $html, $headers);
}

19. 秒數轉人類可讀時間

function secondsToHuman($secs) {
    $units = [['year', 31536000], ['month', 2592000], ['week', 604800], ['day', 86400], ['hour', 3600], ['minute', 60], ['second', 1]];
    $parts = [];
    foreach ($units as [$name, $val]) {
        if ($secs >= $val) {
            $count = (int)($secs / $val);
            $parts[] = "$count $name" . ($count > 1 ? 's' : '');
            $secs %= $val;
        }
    }
    return implode(', ', $parts) ?: '0 seconds';
}

20. MySQL 連線(PDO 版)

$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', 'user', 'pass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

21. 列出目錄檔案

function listFiles($dir) {
    if (!is_dir($dir)) return [];
    return array_diff(scandir($dir), ['.', '..']);
}

22. 偵測瀏覽器語言

function detectLanguage(array $supported = ['en','zh-TW','ja'], $default = 'en') {
    if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return $default;
    foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
        $code = strtolower(substr($lang, 0, 2));
        if (in_array($code, $supported)) return $code;
    }
    return $default;
}

23. 讀取 CSV 檔案

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

使用建議

  • 將常用函式集中放入 helpers.php 並用 Composer files 自動載入。
  • 涉及外部 API(簡訊、郵件、IP 查詢)請務必加入錯誤處理、重試與日誌。
  • 資料庫操作一律使用 Prepared Statements,切勿拼接 SQL 字串。

這 23 個片段覆蓋了 PHP 專案 80% 的常見需求,建議收藏並依專案慣用風格微調。

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