首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 動態生成桌面快捷方式 (.url) 實現:HTTP 響應頭控制下載

     編輯:PHP 相關知識

原理

利用 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 會自動關聯顯示
MIMEapplication/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;

替代方案對比

總結

PHP 生成 .url 快捷方式是輕量級「添加到桌面」方案的經典實現,適合內部系統、推廣頁面快速分發。注意文件名編碼、目標 URL 驗證、HTTPS 環境下的混合內容策略。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方案優點缺點
.url 文件下載無需客戶端腳本,純 HTTP,兼容所有瀏覽器需用戶手動保存、雙擊
JavaScript 拖拽生成體驗更好,可直接拖到桌面需前端支持,移動端不適用
PWA 安裝提示現代標準,類原生體驗需 HTTPS、Service Worker、Manifest