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开发者_如何学JAVA" /><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.
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"');
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 more info
This is because you're using single quotes for your strings and strings in single quotes doesn't get parsed - see the documentation.
To fix this you can do this:
header('Content-Disposition: attachment; filename="'.$filename.'.txt"');
Use this:
header('Content-Disposition: attachment; filename="'.$filename.'.txt"');
<?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 } ?>
精彩评论