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

19 個超實用 PHP 代碼片段:開發效率倍增器

     編輯:PHP 相關知識

收集整理 19 個高頻實用 PHP 代碼片段,涵蓋 WHOIS 查詢、簡訊發送、記憶體監控、原始碼顯示、Data URI、IP 定位、語言偵測、HTTPS 判斷、CSV 生成、距離計算、cURL 封裝、輸入清理、密碼強度、SEO 友善網址、加密雜湊、Twitter API 整合等場景,可直接複製套用或作為擴充套件基礎。

1. WHOIS 域名查詢

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',
        'org' => 'whois.pir.org', 'info' => 'whois.nic.info',
        'cn' => 'whois.cnnic.net.cn', 'io' => 'whois.nic.io',
        // ... 更多 TLD 對應
    ];
    $server = $servers[$tld] ?? 'whois.iana.org';
    
    $fp = fsockopen($server, 43, $errno, $errstr, 10);
    if (!$fp) return "Connection failed: $errstr";
    fputs($fp, "$domain\r\n");
    $result = '';
    while (!feof($fp)) $result .= fgets($fp, 128);
    fclose($fp);
    return $result;
}

2. TextMagic API 發送簡訊

require 'TextMagicAPI.php';
$router = new TextMagicAPI(['username' => 'user', 'password' => 'pass']);
$result = $router->send('Hello!', ['886912345678'], true);

3. 記憶體使用量監控

echo "Initial: " . memory_get_usage() . " bytes\n";
for ($i = 0; $i < 100000; $i++) $arr[] = md5($i);
for ($i = 0; $i < 50000; $i++) unset($arr[$i]);
echo "Final: " . memory_get_usage() . " bytes\n";
echo "Peak: " . memory_get_peak_usage() . " bytes\n";

4. 顯示網頁原始碼 (含行號)

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

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

function data_uri($file, $mime) {
    $contents = file_get_contents($file);
    $base64 = base64_encode($contents);
    return "data:$mime;base64,$base64";
}
// 用法: 
// CSS: background: url();

6. IP 定位 (城市/省份)

function detect_city($ip) {
    if (!filter_var($ip, FILTER_VALIDATE_IP) || $ip === '127.0.0.1') $ip = '8.8.8.8';
    $url = "https://ip-api.com/json/$ip?fields=city,regionName,country";
    $json = @file_get_contents($url);
    $data = json_decode($json, true);
    return ($data['city'] && $data['regionName']) 
        ? "{$data['city']}, {$data['regionName']}, {$data['country']}" 
        : 'Unknown';
}

7. 偵測瀏覽器偏好語言

function get_client_language(array $available, $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;
}
// 用法: $lang = get_client_language(['en', 'zh', 'ja', 'ko']);

8. 判斷 HTTPS

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

9. 陣列轉 CSV 字串

function generateCsv(array $data, $delimiter = ',', $enclosure = '"') {
    $fp = fopen('php://memory', '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'); echo generateCsv($rows);

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

function getDistance($lat1, $lon1, $lat2, $lon2) {
    $theta = $lon1 - $lon2;
    $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 [
        'km' => $dist * 1.609344,
        'm'  => $dist * 1609.344,
        'mi' => $dist
    ];
}

11. 完善 cURL 封裝 (支援 GET/POST/Referer/UA/重導向)

function xcurl($url, $ref = null, $post = [], $ua = 'Mozilla/5.0...', $print = false) {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_AUTOREFERER => 1,
        CURLOPT_USERAGENT => $ua,
        CURLOPT_HEADER => 0,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false, // 僅開發測試用
    ]);
    if ($ref) curl_setopt($ch, CURLOPT_REFERER, $ref);
    if ($post) {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post)); // 關鍵!
    }
    $output = curl_exec($ch);
    curl_close($ch);
    return $print ? print($output) : $output;
}

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 定位 (備用 API 版)

同上第 6 片段,使用 ip-api.com 免費 API,支援 HTTPS、JSON 格式、無需 API Key (每分鐘 45 次限制)。

14. 密碼強度估算 (基於資訊熵)

function password_strength($string) {
    $h = 0; $len = strlen($string);
    foreach (count_chars($string, 1) as $freq) {
        $p = $freq / $len;
        $h -= $p * log($p, 2);
    }
    $strength = min(100, ($h / 4) * 100); // 理論最大 4 bits/char
    return $strength;
}
// 測試
var_dump(password_strength('Correct Horse Battery Staple')); // ~高
var_dump(password_strength('abc123')); // ~低

15. 瀏覽器語言偵測 (重複片段,略)

16. Data URI 生成 (重複片段,略)

17. SEO 友善網址 (Slug 生成)

function make_seo_name($title) {
    $title = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $title); // 處理中文/特殊字元
    $title = preg_replace('/[^a-z0-9_\-]/i', '', strtolower(str_replace(' ', '-', trim($title))));
    return $title;
}
// "這是測試 Title!" -> "zhe-shi-ce-shi-title"

18. 多層加密雜湊 (FUE: Fucking Uncrackable Encryption)

function fue($hash, $times) {
    for ($i = $times; $i > 0; $i--) {
        $hash = base64_encode($hash);
        $hash = md5($hash);
        $hash = sha1($hash);
        $hash = hash('sha256', $hash);
        $hash = hash('sha512', $hash);
    }
    return $hash;
}
// 注意:這不是標準密碼雜湊,不可用於儲存密碼!請用 password_hash()

19. Twitter Timeline 讀取 (舊版 API v1.1,需 OAuth)

class TwitterFeed {
    private $twitURL = 'https://api.twitter.com/1.1/';
    private $xml;
    
    public function loadTimeline($user, $max = 20) {
        // 實際需 OAuth 簽名,此處略過簽名過程
        $url = $this->twitURL . "statuses/user_timeline.json?screen_name=$user&count=$max";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $this->xml = curl_exec($ch);
        return $this;
    }
    
    public function getTweets() {
        $data = json_decode($this->xml, true);
        $tweets = [];
        foreach ($data as $status) {
            $tweets[$status['created_at']] = $status['text'];
        }
        return $tweets;
    }
    
    public function formatTweet($tweet) {
        $tweet = preg_replace('/(https?:\/\/\S+)/', '$1', $tweet);
        $tweet = preg_replace('/#(\w+)/', '#$1', $tweet);
        $tweet = preg_replace('/@(\w+)/', '@$1', $tweet);
        return $tweet;
    }
}

// 使用
$twitter = new TwitterFeed();
$feed = $twitter->loadTimeline('php')->getTweets();
foreach ($feed as $time => $msg) {
    echo "
{$twitter->formatTweet($msg)}
At: $time
"; }

使用建議與現代化替代

片段現代替代/注意事項
WHOIS使用 phpwhois/phpwhois 庫,支援更多 TLD、RDAP 協定
簡訊Twilio、Vonage、Plivo 等現代雲通訊平台 SDK
IP 定位MaxMind GeoIP2 (本地資料庫)、ipinfo.io、ip-api.com (付費版無限制)
cURL 封裝guzzlehttp/guzzle (PSR-7/18 標準)、symfony/http-client
輸入清理htmlpurifier/htmlpurifier (XSS 防護)、PDO 預處理 (SQL 注入)
密碼強度zxcvbn-php (Dropbox 算法、更精準)
SEO Slugcocur/slugify (支援多語言、可擴展規則)
TwitterTwitter API v2 + abraham/twitteroauth,需開發者帳號審核

結語

這 19 個片段覆蓋了 Web 開發高頻需求的 80%。實務上建議封裝為 Composer 套件或服務類,統一錯誤處理、日誌、快取、測試,而非直接複製貼上。持續關注生態系統演進,適時替換為更優雅、更安全的現代庫。

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