Set file name using user inputted variable in PHP

梦想与她 提交于 2019-12-23 17:25:00

问题


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.


回答1:


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"');



回答2:


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




回答3:


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"');



回答4:


Use this:

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



回答5:


  <?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 } ?>


来源:https://stackoverflow.com/questions/7484736/set-file-name-using-user-inputted-variable-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!