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

19個高頻實用PHP代碼片段:從Whois查詢到郵件發送,開發必備收藏

     編輯:PHP 綜合知識

前言

日常開發中,我們經常需要處理一些通用任務:域名查詢、短信發送、記憶體監控、IP 定位、瀏覽器語言檢測等。與其重複造輪子,不如收藏這 19 個經過實戰驗證的 PHP 代碼片段,開箱即用,大幅提升開發效率。

1. Whois 域名信息查詢

通過連接對應後綴的 Whois 伺服器,獲取域名註冊信息。支援主流頂級域(.com/.net/.cn/.org 等)及多國國家域。

function whois_query($domain) {
    $domain = strtolower(trim($domain));
    $domain = preg_replace('/^https?:\/\//i', '', $domain);
    $domain = preg_replace('/^www\./i', '', $domain);
    $domain = explode('/', $domain)[0];

    $tld = array_pop(explode('.', $domain));

    $servers = [
        'com' => 'whois.internic.net', 'net' => 'whois.internic.net',
        'cn'  => 'whois.cnnic.net.cn', 'org' => 'whois.pir.org',
        'io'  => 'whois.nic.io',       'ai'  => 'whois.nic.ai',
        // 更多請參考 IANA 列表
    ];

    if (!isset($servers[$tld])) {
        throw new Exception("不支援的域名後綴: $tld");
    }

    $fp = fsockopen($servers[$tld], 43, $errno, $errstr, 10);
    if (!$fp) throw new Exception("無法連接 Whois 伺服器: $errstr");

    fputs($fp, $domain . "\r\n");
    $result = '';
    while (!feof($fp)) $result .= fgets($fp, 128);
    fclose($fp);
    return $result;
}

2. TextMagic API 發送簡訊

付費服務,適合驗證碼、通知類簡訊發送。需先安裝官方 SDK:composer require textmagic/sdk

use TextMagic\Services\Messages;

$client = new \TextMagic\Client('your_username', 'your_api_key');
$msg = new Messages($client);
$msg->send(['phones' => '85212345678', 'text' => '您的驗證碼:123456']);

3. 監控 PHP 記憶體使用情況

排查記憶體洩漏、優化大數據處理腳本的利器。

echo "初始: " . memory_get_usage() . " bytes\n";
// 模擬佔用記憶體
for ($i = 0; $i < 100000; $i++) $arr[] = md5($i);
echo "峰值: " . memory_get_peak_usage() . " bytes\n";
// 釋放一半
for ($i = 0; $i < 50000; $i++) unset($arr[$i]);
echo "釋放後: " . memory_get_usage() . " bytes\n";

4. 獲取任意網頁源碼(帶行號)

$lines = file('https://www.example.com');
foreach ($lines as $num => $line) {
    echo "Line #{$num}: " . htmlspecialchars($line) . "
\n"; }

5. 生成 Data URI(圖片內嵌 HTML/CSS)

減少 HTTP 請求,適合小圖標、背景圖。

function data_uri($file, $mime) {
    $content = file_get_contents($file);
    $base64  = base64_encode($content);
    return "data:$mime;base64,$base64";
}
// 用法
echo '<img src="' . data_uri('logo.png', 'image/png') . '">';

6. IP 歸屬地查詢(基於 ipinfodb)

需申請免費 API Key,此處示範基本邏輯。

function detect_city($ip) {
    if (!filter_var($ip, FILTER_VALIDATE_IP) || $ip === '127.0.0.1') $ip = '8.8.8.8';
    $url = "https://api.ipinfodb.com/v3/ip-city/?key=YOUR_KEY&ip=$ip&format=json";
    $json = @file_get_contents($url);
    $data = json_decode($json, true);
    return ($data['statusCode'] === 'OK') ? "{$data['cityName']}, {$data['regionName']}" : '未知';
}

7. 檢測瀏覽器偏好語言

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

8. 判斷是否 HTTPS 請求

$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') 
          || ($_SERVER['SERVER_PORT'] === 443);

9. 陣列導出 CSV

function generateCsv(array $data, $delimiter = ',', $enclosure = '"') {
    $fp = fopen('php://temp', 'r+');
    foreach ($data as $row) fputcsv($fp, $row, $delimiter, $enclosure);
    rewind($fp);
    $csv = stream_get_contents($fp);
    fclose($fp);
    return $csv;
}
// 直接下載
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="export.csv"');
echo generateCsv([['姓名','年齡'],['張三',25],['李四',30]]);

10. 經緯度距離計算(Haversine 公式)

function getDistance($lat1, $lng1, $lat2, $lng2, $unit = 'km') {
    $theta = $lng1 - $lng2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) 
          + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist) * 60 * 1.1515; // 英里
    return ($unit === 'km') ? $dist * 1.609344 : $dist;
}

11. 通用 cURL 封裝(支援 GET/POST/代理/UA)

function xcurl($url, $ref = null, array $post = [], $ua = 'Mozilla/5.0') {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_AUTOREFERER   => true,
        CURLOPT_REFERER       => $ref,
        CURLOPT_HEADER        => false,
        CURLOPT_FOLLOWLOCATION=> true,
        CURLOPT_RETURNTRANSFER=> true,
        CURLOPT_USERAGENT     => $ua,
        CURLOPT_TIMEOUT       => 30,
        CURLOPT_SSL_VERIFYPEER=> false, // 僅測試環境
    ]);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

12. 用戶輸入清理(防 XSS)

function cleanInput($input) {
    $search = [
        '@]*?>.*?@si',
        '@<[\/\!]*?[^<>]*?>@si',
        '@]*?>.*?@siU',
        '@@'
    ];
    return preg_replace($search, '', $input);
}

function sanitize($input) {
    if (is_array($input)) return array_map('sanitize', $input);
    if (get_magic_quotes_gpc()) $input = stripslashes($input);
    $input = cleanInput($input);
    // 建議改用 PDO 預處理,而非 mysql_real_escape_string
    return $input;
}

13. IP 歸屬地查詢(備用版,同 6)

略,建議使用成熟的 GeoIP2 資料庫(MaxMind)離線查詢,效能更高。

14. 密碼強度評估(基於熵值)

function password_strength($str) {
    $len = strlen($str);
    $freq = count_chars($str, 1);
    $entropy = 0;
    foreach ($freq as $c) {
        $p = $c / $len;
        $entropy -= $p * log($p, 2);
    }
    $score = min(100, ($entropy / 4) * 100);
    return round($score, 1);
}
// 測試
var_dump(password_strength('Correct Horse Battery Staple')); // 高
var_dump(password_strength('abc123'));                       // 低

15. 瀏覽器語言檢測(同 7,去重)

16. Data URI 生成(同 5,去重)

17. 生成 SEO 友好 URL Slug

function make_seo_name($title) {
    $title = iconv('UTF-8', 'ASCII//TRANSLIT', $title); // 處理中文需配合拼音庫
    $title = preg_replace('/[^a-z0-9\s-]/i', '', $title);
    $title = strtolower(trim($title, '-'));
    $title = preg_replace('/[\s-]+/', '-', $title);
    return $title;
}

18. 多重哈希加密(教學用,生產請用 bcrypt/argon2)

function fue($hash, $times) {
    for ($i = 0; $i < $times; $i++) {
        $hash = base64_encode($hash);
        $hash = md5($hash);
        $hash = sha1($hash);
        $hash = hash('sha256', $hash);
        $hash = hash('sha512', $hash);
    }
    return $hash;
}

19. Twitter 時間線獲取(API v1.1 已棄用,現需用 v2 + Bearer Token)

現代做法請參考 Twitter API v2 文檔,使用 OAuth 2.0 Bearer Token 認證。

總結

這 19 個片段覆蓋了網絡請求、字符串處理、安全、編碼、地理定位等高頻場景。實際項目中建議:

  • 優先使用成熟 Composer 包(如 guzzlehttp/guzzle、geoip2/geoip2、ramsey/uuid)
  • 密碼存儲務必用 password_hash() / password_verify()
  • 所有外部請求加上超時與異常處理
  • 定期審查並更新第三方依賴
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved