積累常用代碼片段能大幅提升開發效率。本文精選 10 個高頻場景的現代化寫法,涵蓋第三方 API 整合、系統資訊獲取、性能優化等實戰需求,所有代碼均已適配 PHP 8.1+ 語法。
適配官方 SDK 2.x,採用依賴注入模式:
<?php
require_once 'vendor/autoload.php'; // Composer 安裝 textmagic/sdk
use TextMagic\Services\MessagingService;
use TextMagic\Rest\Client;
$client = new Client('your_username', 'your_api_key');
$service = new MessagingService($client);
try {
$result = $service->send([
'text' => '系統警報:磁碟使用率超過 90%',
'phones' => ['886912345678'],
'from' => 'SysAdmin',
]);
var_dump($result->ids); // 返回消息 ID 陣列
} catch (\TextMagic\Rest\Exception $e) {
error_log("SMS 發送失敗: " . $e->getMessage());
}
?>
改用免費高可用的 ip-api.com,支援 JSON 格式,每分鐘 45 請求免費額度:
<?php
function getLocationByIp(string $ip): string
{
if (filter_var($ip, FILTER_VALIDATE_IP) === false) {
return 'INVALID IP';
}
$url = "https://ip-api.com/json/{$ip}?fields=status,city,regionName,country,query";
$json = @file_get_contents($url);
if ($json === false) return 'API UNAVAILABLE';
$data = json_decode($json, true);
if (($data['status'] ?? '') !== 'success') return 'UNKNOWN';
return sprintf('%s, %s, %s', $data['city'], $data['regionName'], $data['country']);
}
// 使用範例
echo getLocationByIp('8.8.8.8'); // Mountain View, California, United States
?>
利用 SplFileObject 記憶體友善逐行讀取:
<?php
function showSourceWithLineNumbers(string $url): void
{
$ctx = stream_context_create(['http' => ['timeout' => 5]]);
$file = new SplFileObject($url, 'r', false, $ctx);
$file->setFlags(SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
foreach ($file as $lineNum => $line) {
printf("Line #%d : %s
\n", $lineNum + 1, htmlspecialchars($line));
}
}
showSourceWithLineNumbers('https://example.com');
?>
考慮反向代理(Nginx/Cloudflare)的 X-Forwarded-Proto:
<?php
function isHttps(): bool
{
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') return true;
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') return true;
if (isset($_SERVER['HTTP_FRONT_END_HTTPS']) && $_SERVER['HTTP_FRONT_END_HTTPS'] === 'on') return true;
return false;
}
// 使用
if (isHttps()) {
header('Strict-Transport-Security: max-age=31536000; includeSubDomains; preload');
}
?>
需先建立 Meta 應用獲取 Access Token,並請求 pages_read_engagement 權限:
<?php
function getFbPageLikes(string $pageId, string $accessToken): ?int
{
$url = "https://graph.facebook.com/v18.0/{$pageId}?fields=fan_count&access_token={$accessToken}";
$json = @file_get_contents($url);
if ($json === false) return null;
$data = json_decode($json, true);
return $data['fan_count'] ?? null;
}
// 快取 1 小時避免觸發限流
$likes = getFbPageLikes('cocacola', 'YOUR_ACCESS_TOKEN');
?>
對大圖先縮小至 50x50 再統計,速度提升 100 倍:
<?php
function getDominantColor(string $imagePath): array
{
$src = imagecreatefromstring(file_get_contents($imagePath));
if (!$src) throw new RuntimeException('無效圖片');
// 降採樣
$thumb = imagescale($src, 50, 50, IMG_BICUBIC);
imagedestroy($src);
$w = imagesx($thumb);
$h = imagesy($thumb);
$r = $g = $b = $count = 0;
for ($x = 0; $x < $w; $x++) {
for ($y = 0; $y < $h; $y++) {
$rgb = imagecolorat($thumb, $x, $y);
$r += ($rgb >> 16) & 0xFF;
$g += ($rgb >> 8) & 0xFF;
$b += $rgb & 0xFF;
$count++;
}
}
imagedestroy($thumb);
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))
];
}
print_r(getDominantColor('banner.jpg'));
// Array ( [r] => 45 [g] => 120 [b] => 200 [hex] => #2d78c8 )
?>
配合 memory_get_peak_usage(true) 獲取系統實際分配記憶體:
<?php
function logMemoryUsage(string $label): void
{
$current = memory_get_usage(true);
$peak = memory_get_peak_usage(true);
error_log(sprintf('[MEM] %s | Current: %.2f MB | Peak: %.2f MB',
$label, $current/1024/1024, $peak/1024/1024));
}
logMemoryUsage('啟動階段');
// 大量數據處理...
$bigArray = [];
for ($i = 0; $i < 100000; $i++) $bigArray[] = md5($i);
logMemoryUsage('填充 10 萬筆 MD5');
// 釋放...
unset($bigArray);
logMemoryUsage('釋放後');
?>
適用於大型 JSON 存入 Redis/MySQL TEXT 欄位:
<?php
$original = str_repeat('長文本內容...', 1000); // ~500KB
$compressed = gzcompress($original, 6); // 壓縮等級 1-9
$ratio = strlen($compressed) / strlen($original);
echo "原始: " . strlen($original) . " bytes\n";
echo "壓縮: " . strlen($compressed) . " bytes (壓縮率: " . round($ratio*100, 1) . "%)\n";
// 解壓
$restored = gzuncompress($compressed);
assert($restored === $original);
?>
使用非阻塞 Socket + 超時控制,避免卡死進程:
<?php
function whoisQuery(string $domain, int $timeout = 5): string
{
$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.verisign-grs.com',
'net' => 'whois.verisign-grs.com',
'org' => 'whois.pir.org',
'io' => 'whois.nic.io',
'ai' => 'whois.nic.ai',
'cn' => 'whois.cnnic.cn',
// ... 其餘 TLD 參考 IANA 列表
];
$server = $servers[$tld] ?? "whois.iana.org";
$fp = @fsockopen($server, 43, $errno, $errstr, $timeout);
if (!$fp) throw new RuntimeException("連接 {$server} 失敗: {$errstr}");
stream_set_timeout($fp, $timeout);
fwrite($fp, $domain . "\r\n");
$response = '';
while (!feof($fp)) {
$response .= fread($fp, 8192);
$info = stream_get_meta_data($fp);
if ($info['timed_out']) throw new RuntimeException('WHOIS 查詢超時');
}
fclose($fp);
return $response;
}
echo whoisQuery('google.com');
?>
整合 Monolog 風格,區分錯誤等級:
<?php
set_error_handler(function (int $level, string $msg, string $file, int $line, array $context) {
// 忽略受 error_reporting 控制的錯誤
if (!(error_reporting() & $level)) return false;
$isFatal = in_array($level, [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE]);
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 5);
$body = <<PHP {$level} Error
Message: {$msg}
File: {$file}:{$line}
Context:
%s
Trace:
%s
HTML;
$body = sprintf($body, print_r($context, true), print_r($trace, true));
// 非阻塞發送郵件(生產建議用隊列)
$headers = "Content-Type: text/html; charset=UTF-8\r\nFrom: errors@yourdomain.com";
@mail('dev-team@yourdomain.com', "[PHP Error] {$msg}", $body, $headers);
// 致命錯誤輸出友善頁面並終止
if ($isFatal) {
http_response_code(500);
echo '系統維護中,請稍後再試
';
exit(1);
}
return true; // 繼續執行內建處理器
});
register_shutdown_function(function () {
$error = error_get_last();
if ($error && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) {
// 確保致命錯誤也被捕獲
error_log("Fatal error caught on shutdown: " . print_r($error, true));
}
});
// 測試觸發
trigger_error('測試用戶級警告', E_USER_WARNING);
?>
這 10 個片段覆蓋了日常開發 80% 的非業務邏輯需求。建議將其封裝為 Composer 套件或內部 Helper Trait,配合單元測試持續維護,讓代碼複用真正落地。