原理
利用 HTTP 響應頭 Content-Disposition: attachment 觸發瀏覽器下載,內容為 Windows .url 文件格式(本質是 INI 文件),用戶保存後雙擊即可打開對應網址。
核心代碼
<?php
// shortcut.php
$url = 'https://www.example.com'; // 目標網址
$filename = '我的網站.url'; // 下載文件名
$content = "[InternetShortcut]\r\n" .
"URL=$url\r\n" .
"IDList=\r\n" .
"[{000214A0-0000-0000-C000-000000000046}]\r\n" .
"Prop3=19,2\r\n";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
header('Content-Length: ' . strlen($content));
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
echo $content;
關鍵點詳解
| 項目 | 說明 |
| 文件格式 | .url 為文本 INI 格式,核心鍵 URL 指定目標地址 |
| 編碼 | 文件內容建議 UTF-8 無 BOM;文件名用 rawurlencode() 防中文亂碼 |
| 圖標 | 需網站根目錄有 favicon.ico,Windows 會自動關聯顯示 |
| MIME | application/octet-stream 通用二進制流,強制下載 |
| 安全 | 僅生成指向自有域名的快捷方式,防止釣魚利用 |
進階:動態參數化版本
<?php
// gen_shortcut.php?url=https://example.com/page&title=我的頁面
$url = filter_input(INPUT_GET, 'url', FILTER_VALIDATE_URL);
$title = filter_input(INPUT_GET, 'title', FILTER_SANITIZE_SPECIAL_CHARS) ?? '網站快捷方式';
if (!$url) {
http_response_code(400);
exit('無效的 URL 參數');
}
$filename = $title . '.url';
$content = "[InternetShortcut]\r\nURL=$url\r\n";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
echo $content;
替代方案對比