精選 9 個高頻使用的 PHP 代碼片段,涵蓋數據 URI、文件合併、郵件追蹤、關鍵詞提取、鏈接掃描、URL 自動鏈接、圖片下載、語言檢測、Facebook 粉絲數獲取,可直接集成到項目中。
function dataUri($file, $mime) {
$base64 = base64_encode(file_get_contents($file));
return "data:$mime;base64,$base64";
}
// 使用: ?>)
減少 HTTP 請求,適合小圖標、背景圖嵌入 CSS/HTML。
function combineAssets($files, $destDir, $destName) {
$destPath = $destDir . $destName;
if (!file_exists($destPath)) {
$content = '';
foreach ($files as $file) $content .= file_get_contents($file);
// 可接入壓縮庫:$content = minify($content);
file_put_contents($destPath, $content);
}
return '';
}
header('Content-Type: image/jpeg');
$ip = $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
$log = date('Y-m-d H:i:s') . " $ip {$_SERVER['HTTP_USER_AGENT']}\n";
file_put_contents('email_open.log', $log, FILE_APPEND);
imagejpeg(imagecreate(1,1)); // 輸出 1px 透明圖片
嵌入郵件:<img src="track.php?uid=123" width="1" height="1">
$meta = get_meta_tags('https://example.com');
$keywords = array_filter(array_map('trim', explode(',', $meta['keywords'] ?? '')));
$dom = new DOMDocument();
@$dom->loadHTML(file_get_contents($url));
$xpath = new DOMXPath($dom);
foreach ($xpath->evaluate('//a') as $link) {
echo $link->getAttribute('href') . "\n";
}
function autoLink($text) {
return preg_replace_callback(
'#(^|[\s>])(\w+://[\w\x80-\xff#$%&~/.\-;:=,?@\[\]+]*)#i',
fn($m) => $m[1] . '' . $m[2] . '',
$text
);
}
file_put_contents('/local/path.jpg', file_get_contents('https://remote/image.jpg'));
function detectLanguage($available = ['en','zh','ja'], $default = 'en') {
if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) return $default;
foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) {
if (in_array($lang[0].$lang[1], $available)) return $lang[0].$lang[1];
}
return $default;
}
$pageId = 'your_page_id';
$json = file_get_contents("https://graph.facebook.com/$pageId?fields=fan_count");
echo json_decode($json)->fan_count ?? 0;
需申請 Access Token 並替換為 https://graph.facebook.com/$pageId?fields=fan_count&access_token=...
這些片段解決了開發中 80% 的常見場景,建議整理為個人代碼庫隨時調用。