Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set file name using user inputted variable in PHP

Tags:

file

php

set

I'm just wondering how I can use the name of a variable to set a file name in PHP? When I run the following code:

<?php
if ($_POST) {
    $filename = $_POST['firstName'];

    header("Content-Type: application/txt");        
    header('Content-Disposition: attachment; filename="$filename.txt"');

    echo "Welcome, ";
    echo $_POST['firstName']. " " . $_POST['lastName'];

    exit;
} else {

?>

<form action="" method="post">
    First Name: <input type="text" name="firstName" /><br />
    Last Name: <input type="text" name="lastName" /><br />
    <input type="submit" name="submit" value="Submit me!" />
</form>

<?php } ?>

The file name is always set to "$filename.txt", but I'd like it to be Adam.txt, or Brian.txt etc depending on the user input.

like image 914
Lars Avatar asked Nov 06 '25 00:11

Lars


1 Answers

Replace the '' with "" so variable substitution works

header("Content-Disposition: attachment; filename=\"$filename.txt\"");

or if you want to use ''

header('Content-Disposition: attachment; filename="'.$filename.'.txt"');
like image 142
Bluewind Avatar answered Nov 08 '25 16:11

Bluewind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!