Set file name using user-entered variable in PHP

I'm just wondering how can I use a variable name 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 " $filename.txt ", but I would like it to be Adam.txt or Brian.txt etc. depending on user input.

+3
source share
5 answers

Replace '' with "" so the replacement variables work

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

or if you want to use ''

 header('Content-Disposition: attachment; filename="'.$filename.'.txt"'); 
+6
source

Only double quotes allow you to interpolate variables:

 $a = "some text" $b = "another part of $a" //works, results in *another part of some text* $b = 'another part of $a' //will not work, result *in another part of $a* 

See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details

0
source

This is because you use single quotes for your strings, and strings in single quotes are not processed - see the documentation .

To fix this, you can do this:

 header('Content-Disposition: attachment; filename="'.$filename.'.txt"'); 
0
source
  <?php if ($_POST) { $filename = isset($_POST['firstName'])? $_POST['firstName'] :'general'; 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 } ?> 
0
source

Use this:

 header('Content-Disposition: attachment; filename="'.$filename.'.txt"'); 
0
source

Source: https://habr.com/ru/post/1396344/


All Articles