短網址服務需根據長網址生成網頁縮略圖(快照)。PhantomJS 渲染耗時不可預估(秒級),不可阻塞用戶請求。採用 「立即返回短網址 → 前端輪詢 → 後台異步生成」 架構。
$url = 'https://target-site.com/page';
$thumb = 'snapshots/' . md5($url) . '.png';
$phantomjs = '/usr/local/bin/phantomjs';
$script = '/var/www/scripts/snap.js'; // phantomjs 腳本
// 關鍵:& 符號讓進程在後台運行,popen/pclose 不等待結束
$cmd = "$phantomjs $script " . escapeshellarg($url) . " " . escapeshellarg($thumb) . " > /dev/null 2>&1 &";
try {
// popen 以 "r" 模式打開管道,立即 pclose 釋放父進程
@pclose(popen($cmd, 'r'));
} catch (Throwable $e) {
error_log("啟動快照進程失敗: " . $e->getMessage());
}
// 立即返回短網址給前端
echo json_encode(['short_url' => 'https://short.ly/abc123', 'thumb' => $thumb]);
escapeshellarg():防止命令注入,務必對用戶輸入轉義。> /dev/null 2>&1 &:重定向輸出到空設備,& 讓 Shell 放入後台作業控制。pclose(popen(...)):popen 啟動進程並返回管道,pclose 立即關閉管道,**不等待子進程結束**;子進程被 init (PID 1) 收養,成為孤兒進程繼續運行。popen('start /b ' . $cmd, 'r') 或 COM/WScript.Shell 異步啟動。// snap.js
var system = require('system');
var page = require('webpage').create();
var url = system.args[1];
var output = system.args[2];
page.viewportSize = { width: 1280, height: 800 };
page.clipRect = { top: 0, left: 0, width: 1280, height: 800 };
page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
page.open(url, function(status) {
if (status !== 'success') {
console.log('FAIL: ' + status);
phantom.exit(1);
}
// 等待動態內容渲染(可根據項目調整)
window.setTimeout(function() {
page.render(output);
console.log('OK: ' + output);
phantom.exit(0);
}, 2000);
});
// 生成請求後立即開始輪詢
let pollTimer = setInterval(() => {
$.ajax({
url: '?m=shorturl&c=index&a=check_snap',
data: { thumb: '= $thumb ?>' }, // 傳入快照文件名
dataType: 'json',
success: function(res) {
if (res.ready) {
clearInterval(pollTimer);
$('#thumb-img').attr('src', res.thumb_url + '?v=' + Date.now()).show();
}
},
error: () => { /* 靜默重試 */ }
});
}, 2000); // 每 2 秒輪詢一次
// 後台檢查接口 check_snap
if (file_exists($thumbPath) && filesize($thumbPath) > 100) {
echo json_encode(['ready' => true, 'thumb_url' => $thumbUrl]);
} else {
echo json_encode(['ready' => false]);
}
popen,支援重試、優先級、監控。chrome-headless-shell 或 Playwright,渲染更準確、支援現代 Web 標準。「異步生成 + 前端輪詢」是處理耗時任務的經典模式。核心在於後台進程完全脫離 HTTP 請求生命週期,前端通過輕量級輪詢或長連接感知完成狀態。隨著技術棧演進,建議逐步遷移至現代 Headless 瀏覽器 + 消息隊列架構。