Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable PHP download-header file name?

What's the proper syntax for this?

header('Content-Disposition: attachment; filename="{$_SESSION['name']} . '.txt');

This file works, though only properly when "view source" (HTML not formatted but contains correct line breaks).

<?php
header("Content-type: text/html");
session_start();
    if(file_exists("chat") && filesize("chat") > 0){
        $handle = fopen("chat", "r");
        $contents = fread($handle, filesize("chat"));
        fclose($handle);
        ob_start();
$download = strip_tags($contents, '<br>');
$processed = preg_replace('#<br\s*/?>#i', "\n", $download);
echo $processed;
$var = ob_get_clean();
echo $var;
    }
?>

The $_SESSION['name'] variable is something like guest_158512 and if you view the source of the page I'm trying to save, it has all the line breaks. How do I save the current page as guest_158512.txt with the proper syntax?

like image 872
ionFish Avatar asked Feb 12 '12 06:02

ionFish


3 Answers

Your problem here is that you've tried to use single quotes. Single quotes do not interpolate variables in PHP.

You have also failed to properly terminate the string, probably due to putting more single quotes inside it. Try:

header('Content-Disposition: attachment; filename="'.$_SESSION['name'].'.txt"');

Kolink also points out that you should use Content-Type: text/plain to serve plain-text non-HTML files.

like image 57
Borealid Avatar answered Sep 19 '22 00:09

Borealid


header("Content-Disposition: attachment; filename=\"".$_SESSION['name'].".txt\"");
header("Content-Type: text/plain");

For future reference, using a proper code editor such as Notepad++ would show you that your quotes are badly mismatched.

like image 41
Niet the Dark Absol Avatar answered Sep 19 '22 00:09

Niet the Dark Absol


You're close. With single quotes, you may do the following:

header('Content-Disposition: attachment; filename="' . $_SESSION['name'] . '.txt"');
like image 20
Josh Avatar answered Sep 18 '22 00:09

Josh