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

又十個超實用 PHP 代碼片段:簡訊發送、IP 定位、原始碼顯示、HTTPS 判斷、Facebook 粉絲數、圖片主色調、記憶體監控、資料壓縮、WHOIS 查詢、錯誤郵件通知

     編輯:PHP 綜合知識

片段 1:發送簡訊 (TextMagic API 範例)

 'your_username',
    'password' => 'your_password',
]);

try {
    $result = $router->send('系統通知:您的驗證碼 123456', ['+886912345678']);
    // $result['messages'] 含訊息 ID 對應電話
} catch (\Exception $e) {
    error_log('SMS 發送失敗: ' . $e->getMessage());
}
?>

現代替代:Twilio、Vonage (Nexmo)、Plivo、國內簡訊商 (每間 API 不同),建議封裝介面支援多商切換。

片段 2:IP 定位城市/國家 (ip-api.com 免費額度較大)

 true,
        CURLOPT_TIMEOUT => 3,
        CURLOPT_USERAGENT => 'PHP-IP-Detector/1.0',
    ]);
    $json = curl_exec($ch);
    curl_close($ch);

    $data = json_decode($json, true);
    return ($data['status'] ?? '') === 'success' ? $data : null;
}

// 使用
$loc = detectLocationByIp();
if ($loc) {
    echo "{$loc['city']}, {$loc['regionName']}, {$loc['country']} ({$loc['isp']})";
}
?>

片段 3:顯示網頁原始碼 (含行號、HTML 跳脫)

';
    foreach ($lines as $i => $line) {
        $num = str_pad($i + 1, strlen(count($lines)), '0', STR_PAD_LEFT);
        echo "{$num} " . htmlspecialchars($line) . "\n";
    }
    echo '
'; } // 直接瀏覽此檔案加 ?source=1 顯示自身原始碼 if (isset($_GET['source'])) { showSourceWithLines(__FILE__); exit; } ?>

片段 4:判斷是否 HTTPS

片段 5:取得 Facebook 粉絲專頁讚數 (Graph API)

片段 6:計算圖片平均主色調 (RGB)

> 16) & 0xFF;
            $g += ($rgb >> 8) & 0xFF;
            $b += $rgb & 0xFF;
        }
    }
    $count = (int)(($w / $step) * ($h / $step));
    imagedestroy($img);

    return [
        'r' => (int)round($r / $count),
        'g' => (int)round($g / $count),
        'b' => (int)round($b / $count),
        'hex' => sprintf('#%02x%02x%02x', (int)round($r/$count), (int)round($g/$count), (int)round($b/$count)),
    ];
}
?>

片段 7:記憶體使用監控

片段 8:資料壓縮/解壓 (gzcompress / gzuncompress)

片段 9:WHOIS 域名查詢 (支援常見 TLD)

 'whois.verisign-grs.com',
        'net' => 'whois.verisign-grs.com',
        'org' => 'whois.pir.org',
        'io'  => 'whois.nic.io',
        'ai'  => 'whois.nic.ai',
        'tw'  => 'whois.twnic.net.tw',
        'cn'  => 'whois.cnnic.cn',
        // ... 依需求擴充
    ];
    $server = $servers[$tld] ?? 'whois.iana.org'; // 根伺服器會轉介

    $fp = @fsockopen($server, 43, $errno, $errstr, 5);
    if (!$fp) return "連線失敗: $errstr";

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

echo whoisQuery('google.com');
?>

片段 10:錯誤郵件通知 (自訂錯誤處理器)

PHP 錯誤通知
        

類型: $severity

訊息: $message

檔案: $file (第 $line 行)

時間: " . date('Y-m-d H:i:s') . "

呼叫堆疊

" . print_r($trace, true) . "

上下文變數

" . print_r($context, true) . "
"; $headers = "MIME-Version: 1.0\r\nContent-type: text/html; charset=utf-8\r\nFrom: error@yourdomain.com"; @mail('dev@yourdomain.com', '[PHP Error] ' . $message, $body, $headers); // 正式環境不顯示錯誤細節 if (ini_get('display_errors')) { echo "

系統維護中,請稍後再試

"; } return true; // 已處理 } set_error_handler('errorHandler'); // 致命錯誤需額外註冊 register_shutdown_function(function() { $error = error_get_last(); if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) { errorHandler($error['type'], $error['message'], $error['file'], $error['line']); } }); // 測試 // echo $undefinedVar; // 觸發 Notice (不會寄信) // require 'not_exist.php'; // 觸發 Fatal Error (會寄信) ?>

結語

這十個片段涵蓋**外部服務整合、基礎設施查詢、除錯輔助、資料處理、監控告警**五大類。實際專案請:

  • 將片段**封裝為可測試的類/服務** (如 SmsService, IpLocator, ErrorNotifier)
  • **設定檔管理密鑰/端點**,勿硬編碼
  • **加入重試、熔斷、快取** (如 IP 定位結果快取 24h)
  • **單元測試覆蓋** 關鍵邏輯
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved