Search code examples
phphttp-headersfilenames

What is the correct syntax for defining filename with variables?


Regarding downloading files and defining the headers, I am having trouble assigning a dynamic filename to my files. When using the code below :

header("Content-Disposition: attachment; filename=test.csv");

A test.csv file is generated for download. However if I use this:

header('Content-Disposition: attachment; filename=' . $filename . '.csv');

It generates a .php file instead. Using this method also doesn't pass the Content-Disposition or filename to the header.

Full code:

session_start();
    $file =$_SESSION['csvf'];
    $filename = $file."_".date("Y-m-d_H-i",time());
    header ( "Content-type: text/csv" );
    header("Content-Disposition: attachment; filename=test.csv");
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    print($file);
    exit ();

What is the correct syntax?

EDIT

Working Code after suggestions

session_start ();
$file = $_SESSION ['csvf'];
$filename =date ( "Y-m-d_H-i", time () );
header ( "Content-type: text/csv" );
header ( "Content-Disposition: attachment; filename=".$filename );
header ( 'Expires: 0' );
header ( 'Cache-Control: must-revalidate' );
header ( 'Pragma: public' );
header ( 'Content-Length: ' . filesize ( $file ) );
print ($file) ;
exit ();

Solution

  • I don't see the path to example.csv specified on your code, you need to give the full path to $file, i.e.:

    $mySession = $_SESSION['csvf'];
    //since $_SESSION['csvf'] contains the actual data you cannot use it for filename
    $filename = date("Y-m-d_H-i",time()).".csv"; 
    //write $mySession contents to file. Make sure this folder is writable
    file_put_contents("/home/site/csvfolder/$filename", $mySession); 
    $file = "/home/site/csvfolder/$filename";
    
    if (file_exists($file)) {
        header('Content-Description: File Transfer');
        header('Content-type: text/csv');
        header('Content-Disposition: attachment; filename='.$filename);
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        readfile($file);
        exit;
    }