收集整理 19 個高頻實用 PHP 代碼片段,涵蓋 WHOIS 查詢、簡訊發送、記憶體監控、原始碼顯示、Data URI、IP 定位、語言偵測、HTTPS 判斷、CSV 生成、距離計算、cURL 封裝、輸入清理、密碼強度、SEO 友善網址、加密雜湊、Twitter API 整合等場景,可直接複製套用或作為擴充套件基礎。
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;
}
require 'TextMagicAPI.php';
$router = new TextMagicAPI(['username' => 'user', 'password' => 'pass']);
$result = $router->send('Hello!', ['886912345678'], true);
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";
$lines = file('https://www.example.com');
foreach ($lines as $num => $line) {
echo "Line #$num: " . htmlspecialchars($line) . "\n";
}
function data_uri($file, $mime) {
$contents = file_get_contents($file);
$base64 = base64_encode($contents);
return "data:$mime;base64,$base64";
}
// 用法:
// CSS: background: url(= data_uri('bg.jpg', 'image/jpeg') ?>);
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';
}
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']);
$isHttps = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
|| ($_SERVER['SERVER_PORT'] == 443);
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);
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
];
}
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;
}
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;
}
同上第 6 片段,使用 ip-api.com 免費 API,支援 HTTPS、JSON 格式、無需 API Key (每分鐘 45 次限制)。
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')); // ~低
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"
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()
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 Slug | cocur/slugify (支援多語言、可擴展規則) |
Twitter API v2 + abraham/twitteroauth,需開發者帳號審核 |
這 19 個片段覆蓋了 Web 開發高頻需求的 80%。實務上建議封裝為 Composer 套件或服務類,統一錯誤處理、日誌、快取、測試,而非直接複製貼上。持續關注生態系統演進,適時替換為更優雅、更安全的現代庫。