.url 檔案實為 INI 格式文字檔,瀏覽器識別 Content-Type: application/octet-stream 並觸發下載,雙擊即可在預設瀏覽器開啟指定網址。
<?php
$url = 'https://www.example.com';
$title = '範例連結';
$icon = 'https://www.example.com/favicon.ico';
$content = "[InternetShortcut]\r\n";
$content .= "URL=$url\r\n";
$content .= "IconFile=$icon\r\n";
$content .= "IconIndex=1\r\n";
$content .= "IDList=\r\n";
$content .= "[{000214A0-0000-0000-C000-000000000046}]\r\n";
$content .= "Prop3=19,2\r\n";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($title) . '.url"');
header('Content-Length: ' . strlen($content));
echo $content;
使用 rawurlencode() 編碼檔名,支援中文;瀏覽器會自動解碼儲存。
function downloadUrlShortcut($url, $title, $icon = '') {
$lines = [
'[InternetShortcut]',
'URL=' . $url,
'IconFile=' . $icon,
'IconIndex=1',
'IDList=',
'[{000214A0-0000-0000-C000-000000000046}]',
'Prop3=19,2',
];
$content = implode("\r\n", $lines) . "\r\n";
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($title) . '.url"');
header('Content-Length: ' . strlen($content));
echo $content;
exit;
}
// 使用
downloadUrlShortcut(
'https://github.com',
'GitHub 首頁',
'https://github.githubassets.com/favicon.ico'
);
幾行程式碼即可實現「點擊下載 → 雙擊開啟網頁」的體驗,適合行銷活動、桌面捷徑分發、離線收藏等場景。