萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 生成桌面捷徑 (.url) 讓用戶一鍵收藏網站

原理

輸出 Content-Type: application/octet-stream 並設定 Content-Disposition: attachment,瀏覽器會下載一個 .url 檔案(Windows 網際網路捷徑),雙擊即可用預設瀏覽器開啟指定網址。

實作步驟

  1. 準備 favicon.ico 放置網站根目錄,捷徑圖示才會顯示。
  2. 建立 shorturl.php:
<?php
$shortcut = "[InternetShortcut]\n"
          . "URL=https://www.example.com/\n"
          . "IDList=\n"
          . "[{000214A0-0000-0000-C000-000000000046}]\n"
          . "Prop3=19,2\n";

header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="MySite.url"');
echo $shortcut;
?>
  1. 頁面放置連結:
<a href="/shorturl.php">📌 發送到桌面</a>

進階:動態生成當前頁面捷徑

<?php
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST'];
$uri    = $_SERVER['REQUEST_URI'];
$url    = "$scheme://$host$uri";

$shortcut = "[InternetShortcut]\n"
          . "URL=$url\n"
          . "IconFile=$scheme://$host/favicon.ico\n"
          . "IDList=\n"
          . "[{000214A0-0000-0000-C000-000000000046}]\n"
          . "Prop3=19,2\n";

header("Content-Type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . rawurlencode($host) . '.url"');
echo $shortcut;
?>

注意事項

  • 僅 Windows 原生支援 .url;macOS/Linux 需額外工具或改用 .webloc/.desktop 格式。
  • 若網站有 HTTPS,圖示檔案亦需 HTTPS,否則瀏覽器可能拒絕載入圖示。
  • 現代替代方案:PWA (Progressive Web App) + manifest.json + Service Worker,支援「加入主畫面」且跨平台。
copyright © 萬盛學電腦網 all rights reserved