ionFish
ionFish

Reputation: 1024

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?

Upvotes: 8

Views: 23913

Answers (3)

Borealid
Borealid

Reputation: 98489

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.

Upvotes: 13

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

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.

Upvotes: 2

Josh
Josh

Reputation: 8191

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

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

Upvotes: 1

Related Questions