skip to Main Content

I have a simple PHP file download script,

<?php

$file = sprintf("/home/data/files/%d", intval($_GET['id']));
if (! file_exists($file))
{
    die("no such file");
}

if (str_ends_with($_GET['name'], ".pdf"))
{
    header("Content-Type: application/pdf");
}
else
{
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename="" . $_GET['name'] . """);
}

header("Content-Length: " . filesize($file));
readfile($file);

It works fine, but in the browser the title isn’t changed

enter image description here

I’m not sure if there’s a way to change the "files.php" title in browser. Does anyone know?

2

Answers


  1. Chosen as BEST ANSWER

    MárcioRossato was right, the tab title is determined by filename. The solution is quite simple, use a rewrite rule to make RESTful pattern work.

        location /files/ {
            rewrite /files/(.*)/(.*) /files.php?id=$1&name=$2 last;
        }
    

    Therefore I can use /files/ID/Desired Name of PDF file.pdf to access the file while make the title correct.


  2. Try this:

    header("Content-Disposition: attachment; filename="" . $_GET['name'] . ""; filename*=UTF-8''" . rawurlencode ($_GET['name']) );
    

    Not all browsers will understand filename*=UTF-8'' (but you need it in Chrome), so you need to insert also filename for cross-browser compatibility. This way, the browser tab should show the desired filename.

    Reference: https://www.rfc-editor.org/rfc/rfc6266 (and examples https://www.rfc-editor.org/rfc/rfc6266#section-5)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search