萬盛學電腦網

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

PHP 動態生成 .url 桌面捷徑:一鍵新增網站圖標

原理

.url 檔案實為 INI 格式文字檔,包含 [InternetShortcut] 區段與 URL= 鍵值。瀏覽器/檔案總管識別後顯示為捷徑圖示,雙擊啟動預設瀏覽器開啟目標網址。

最小實作

<?php
// shortcut.php
$targetUrl = 'https://www.example.com/';
$filename = '我的網站.url'; // 下載檔名

$content = "[InternetShortcut]\nURL={$targetUrl}\nIDList=\n[{000214A0-0000-0000-C000-000000000046}]\nProp3=19,2\n";

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

進階:動態參數、圖示、熱鍵

<?php
function generateUrlShortcut(
    string $url,
    string $filename = 'Shortcut.url',
    ?string $iconUrl = null,
    ?string $hotkey = null
): void {
    $lines = [
        '[InternetShortcut]',
        'URL=' . $url,
        'IDList=',
        '[{000214A0-0000-0000-C000-000000000046}]',
        'Prop3=19,2', // 標準屬性
    ];

    if ($iconUrl) {
        $lines[] = 'IconFile=' . $iconUrl;
        $lines[] = 'IconIndex=0';
    }
    if ($hotkey) {
        // 熱鍵格式:十六進位虛擬鍵碼 + 修飾鍵 (Ctrl=2, Alt=4, Shift=1)
        // 範例:Ctrl+Alt+S = 0x4312 (需查表)
        $lines[] = 'HotKey=' . $hotkey;
    }

    $content = implode("\n", $lines) . "\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('Pragma: no-cache');
    echo $content;
}

// 使用
$url = 'https://example.com/dashboard?user=' . urlencode($_GET['user'] ?? '');
generateUrlShortcut($url, '我的儀表板.url', 'https://example.com/favicon.ico');
?>

前端整合:按鈕一鍵下載

<button onclick="downloadShortcut()">新增到桌面</button>
<script>
function downloadShortcut() {
    const url = window.location.origin + '/shortcut.php?user=' + encodeURIComponent(currentUser);
    const a = document.createElement('a');
    a.href = url;
    a.download = '我的網站.url'; // 建議檔名
    document.body.appendChild(a);
    a.click();
    a.remove();
}
</script>

圖示顯示條件

  • 目標網站根目錄需有 favicon.ico,或在 .url 中指定 IconFile 指向 .ico 檔案。
  • Windows 會快取圖示,更新圖示需變更 .url 檔名或清除圖示快取 (ie4uinit.exe -ClearIconCache)。

安全與相容性

項目說明
檔案副檔名必須為 .url,Windows 才識別為網路捷徑
編碼檔案內容建議 UTF-8 (含 BOM) 或 ANSI,中文檔名用 rawurlencode
跨平台.url 僅 Windows 原生支援;Mac/Linux 需手動建立 .desktop 或 .webloc
安全風險惡意 .url 可指向釣魚網站,企業環境可透過群組原則限制
copyright © 萬盛學電腦網 all rights reserved