Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中使用用户输入的变量设置文件名_Php_File_Set - Fatal编程技术网

在PHP中使用用户输入的变量设置文件名

在PHP中使用用户输入的变量设置文件名,php,file,set,Php,File,Set,我只是想知道如何在PHP中使用变量名来设置文件名?当我运行以下代码时: <?php if ($_POST) { $filename = $_POST['firstName']; header("Content-Type: application/txt"); header('Content-Disposition: attachment; filename="$filename.txt"'); echo "Welcome, ";

我只是想知道如何在PHP中使用变量名来设置文件名?当我运行以下代码时:

<?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 } ?>
将“”替换为“”,以便变量替换有效

header("Content-Disposition: attachment; filename=\"$filename.txt\"");
或者如果你想使用“


只有双引号允许插入变量:

$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*

有关更多信息,请参见。这是因为您正在对字符串使用单引号,而单引号中的字符串无法被解析。请参见

要解决此问题,您可以执行以下操作:


名字:
姓氏:
使用以下方法:

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

标题('Content-Disposition:attachment;filename=“.”.$filename..txt“);您可以在PHP手册中阅读,文件名是变量名,而不是内容。第6行:
filename=“.$filename.”.txt
正是我想要的,非常感谢,也感谢所有的答案!我还没有得到足够的支持率来投票,但肯定会很快投票!
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 } ?>
header('Content-Disposition: attachment; filename="'.$filename.'.txt"');