本文介绍了在PHP中使用用户输入变量设置文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是想知道如何使用变量的名称在PHP中设置文件名?当我运行下面的代码时:$ $ p $ $ code $<?php
if($ _POST){
$ filename = $ _POST ['firstName'];
header(Content-Type:application / txt);
header('Content-Disposition:attachment; filename =$ filename.txt');
echoWelcome,;
echo $ _POST ['firstName']。 。 $ _POST [的lastName];
exit;
} else {
?>
< form action =method =post>
名字:< input type =textname =firstName/>< br />
姓氏:< input type =textname =lastName/>< br />
< input type =submitname =submitvalue =Submit me! />
< / form>
<?php}?>
文件名始终设置为 $ filename.txt
,但我希望它是 Adam.txt
或 Brian.txt
等等在用户输入上。
解决方案
用替换,所以变量替换工作
header(Content-Disposition:attachment; filename = \$ filename.txt \);
或者如果您想使用''
header('Content-Disposition:attachment; filename =''。$ filename。'。txt');
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.
解决方案
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"');
这篇关于在PHP中使用用户输入变量设置文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!