雖然現代瀏覽器已內置「添加到桌面/主屏幕」功能,但某些場景(如企業內部系統、特定推廣活動)仍需要由服務端主動生成 `.url` 快捷方式文件供用戶下載。本文介紹如何使用 PHP 動態生成符合 Windows 標準的 Internet Shortcut 文件。
Windows 的 `.url` 文件本質是 INI 格式的文本文件,核心結構如下:
[InternetShortcut]
URL=https://example.com/
IDList=[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,2
<?php
// 目標網址(可從參數獲取,注意防範注入)
$targetUrl = 'https://blog.example.com/';
// 構建 .url 文件內容
$shortcutContent = "[InternetShortcut]\r\n";
$shortcutContent .= "URL={$targetUrl}\r\n";
$shortcutContent .= "IDList=[{000214A0-0000-0000-C000-000000000046}]\r\n";
$shortcutContent .= "Prop3=19,2\r\n";
// 設置下載響應頭
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="網站快捷方式.url"');
header('Content-Length: ' . strlen($shortcutContent));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
// 輸出內容
echo $shortcutContent;
?>
<a href="generate_shortcut.php" class="btn btn-primary">
<i class="bi bi-download"></i> 下載桌面快捷方式
</a>
.url 文件本身不支持自定義圖標。若需自定義圖標,需生成 `.lnk` (Shell Link) 二進制文件,這在 PHP 中較為複雜,通常需調用 COM 組件(僅限 Windows 服務器)或使用第三方庫(如 `php-shell-link`)。對於大多數 Web 場景,`.url` 已足夠滿足需求。
PHP 生成 `.url` 快捷方式文件的核心在於:正確構建 INI 格式內容、設置恰當的 HTTP 響應頭、處理文件名編碼。這是一個輕量級、無依賴的功能,適合為用戶提供「一鍵訪問」的便捷入口。