Search code examples
phpheaderdocuments

Using PHP variables in document header


I am trying to get php variables inserted into the code below. When the document download pop up shows up it shows $filename instead of the actual file name. How can i achieve this?

code:

<?php
header('Content-disposition: attachment; filename=$filename');
header('Content-type: $type');
readfile('$filename');
?>

Solution

  • You're using single quotes. Variables inside string literals using single quotes are not evaluated. Use concatenation or double quotes instead.

    <?php
    header("Content-disposition: attachment; filename=$filename"); // double quotes
    header('Content-type: ' . $type); // concatenation
    readfile($filename); // no quotes needed
    ?>
    

    See the PHP manual page for the String type.