dongyuan8312 2013-06-22 23:49
浏览 199
已采纳

根据页面标题自动重命名下载的文件?

Basically, I want to have a link to download a .zip file at the bottom of each page. Inside that .zip file I will have a PDF file.

Any time that the .zip file is downloaded, I want its title to be the same as the page's title - plus, I want the PDF to be the same.

For example, if they downloaded from a page with the title "This Is My Page" then the .zip file should be "This Is My Page.zip" and the PDF inside should be "This Is My Page.pdf". The PDF will have the exact same content regardless of which page it's downloaded from.

I'm open to any solutions whether it be PHP, Javascript, HTML, etc.

  • 写回答

2条回答 默认 最新

  • dounao1875 2013-06-22 23:53
    关注

    When you force a download with PHP, you can use filename= in the Content-Disposition header to dynamically set the download's filename.

    download_zip.php

    $actual_file_name = '/var/yourserver/file.zip';
    $download_file_name = substr(str_replace(array('\\/|>< ?%\"*'), '_', $_GET['title'] . '.zip'), 0, 255);
    $mime = 'application/zip';
    
    header('Pragma: public');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Cache-Control: private', false);
    header('Content-Type: ' . $mime);
    header('Content-Disposition: attachment; filename="'. $download_file_name .'"'); // Set it here!
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . filesize($actual_file_name));
    header('Connection: close');
    readfile($actual_file_name);
    exit();
    

    To get the page title of the last page, the easiest method would likely be passing the title as a $_GET variable in the download link. From the page with the download link:

    <a href="http://yoursite.com/download_zip.php?title=The+Page+You+Were+Just+On">Download Zip File With This Page's Title</a>
    

    This will require that you include your page title in the link, so to keep from updating the page title in two places, try using a $page_title variable. In the page with the download link:

    <?php
    $page_title = 'Page Title';
    ?>
    <html>
    <head>
        <title><?= $page_title ?></title>
    </head>
    <body>
        <a href="http://yoursite.com/download_zip.php?title=<?= urlencode($page_title) ?>">Download Zip File With This Page's Title</a>
    </body>
    </html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?