日常開發中,我們經常需要處理一些通用任務:域名查詢、短信發送、記憶體監控、IP 定位、瀏覽器語言檢測等。與其重複造輪子,不如收藏這 19 個經過實戰驗證的 PHP 代碼片段,開箱即用,大幅提升開發效率。
通過連接對應後綴的 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;
}
付費服務,適合驗證碼、通知類簡訊發送。需先安裝官方 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']);
排查記憶體洩漏、優化大數據處理腳本的利器。
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";
$lines = file('https://www.example.com');
foreach ($lines as $num => $line) {
echo "Line #{$num}: " . htmlspecialchars($line) . "
\n";
}
減少 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') . '">';
需申請免費 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']}" : '未知';
}
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;
}
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| ($_SERVER['SERVER_PORT'] === 443);
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]]);
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;
}
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;
}
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;
}
略,建議使用成熟的 GeoIP2 資料庫(MaxMind)離線查詢,效能更高。
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')); // 低
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;
}
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;
}
現代做法請參考 Twitter API v2 文檔,使用 OAuth 2.0 Bearer Token 認證。
這 19 個片段覆蓋了網絡請求、字符串處理、安全、編碼、地理定位等高頻場景。實際項目中建議:
guzzlehttp/guzzle、geoip2/geoip2、ramsey/uuid)password_hash() / password_verify()