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

PHP 產生 .url 網址捷徑檔供下載

     編輯:PHP 相關知識

透過 PHP 動態產生 .url 檔案,讓使用者下載後雙擊即可開啟指定網址,適用於「加入我的最愛」、「桌面捷徑」等行銷場景。

實作程式碼

<?php
function downloadUrlShortcut(string $url, string $filename = 'website.url'): void
{
    // 驗證 URL 格式
    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        http_response_code(400);
        exit('無效網址');
    }

    // .url 內容格式(Windows 標準)
    $content = "[InternetShortcut]\r\n";
    $content .= "URL={$url}\r\n";
    $content .= "IDList=[{000214A0-0000-0000-C000-000000000046}]\r\n";
    $content .= "Prop3=19,2\r\n";

    // 可選:自訂圖示
    // $content .= "IconFile=https://example.com/favicon.ico\r\n";
    // $content .= "IconIndex=0\r\n";

    // 發送下載標頭
    if (ob_get_level()) ob_end_clean();

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . rawurlencode($filename) . '"');
    header('Content-Length: ' . strlen($content));
    header('Cache-Control: private, must-revalidate');
    header('Pragma: public');

    echo $content;
    exit;
}

// 使用範例
$targetUrl = 'https://blog.example.com/';
$fileName = '我的部落格.url'; // 中文檔名需 rawurlencode
downloadUrlShortcut($targetUrl, $fileName);

.url 檔案格式說明

欄位說明必要
[InternetShortcut]區段標識是
URL目標網址是
IDListShell 物件識別碼(固定值)否
IconFile自訂圖示路徑(.ico、.exe、.dll)否
IconIndex圖示索引否
HotKey熱鍵否

進階:動態產生含圖示的捷徑

跨平台替代方案

  • macOS:產生 .webloc (XML 格式) 或 .url 亦可被 Safari 支援
  • Linux:.desktop 檔案([Desktop Entry] Type=Link URL=...)
  • 通用:提供 QR Code、複製連結按鈕、PWA 安裝提示

安全提醒

  • 驗證 $url 為白名單域名,防止釣魚連結
  • 檔名過濾危險字元,避免路徑遍歷
  • HTTPS 站點建議強制 HTTPS 連結
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved