简体   繁体   中英

Can't save textarea to file using php?

I have issue saving textarea to file. I used POST method to send the form to the other page then, in the next page I can't include the textarea content with the file Im not sure what is the problem.

Is there any idea about what is the problem?

Here are the two pages: page1:

<!DOCTYPE HTML>
<html>
<head>
    <title>Save</title>
</head>

<body>
    <form action="page2.php" method="post">
    <span>name:</span>
    <input type="text" name="name"><br>
    <span>file extension: </span>
    <select name="ext" id="ext">            
        <option value=".txt">.txt</option>
        <option value=".doc">.doc</option>          
    </select>
    <textarea name="txt1" id="txt1" cols="15" rows="10"></textarea>
    <br>
          <input type="submit" name="submit"  id="submit" value="Save">
          </form>
          <br>
</body>

  </html>

-page2.php

$txt1 = $_POST['txt1']; //textarea
$name = $_POST['name'];
$ext = $_POST['ext'];  //choose from multiple extensions
if ($ext == '.txt')    // In case if I want to add more than extension.
{   
    $file = "'. $name$ext.'" ;
    $output = "$txt1";
    file_put_contents($file, $output);
    $text = file_get_contents($file);

    header("Content-Description: File Transfer");
    header("Content-Type: application/text/plain");
    header("Content-Disposition: attachment; filename=".basename($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
}

$file = "'. $name$ext.'";

should be:

$file = $name.$ext;

At least that's what I had to change to get it to work on my server.

Without seeing your html I can't be sure of what the problem is. But its been my experience that when your having trouble accessing POST vars on the server side that it's probably a simple spelling error. Make sure the name attributes in your form line up with your POST vars. Just my two cents.

I have no idea what did you mean with your code, so, I'd just rewrite it

To save a file on the server you need these 2 lines

$name = basename($_POST['name']).'.txt';
file_put_contents($name, $_POST['txt1']);

You need to add an id to the form, then add the form Id to the textarea element. For example:

<form action="page2.php" method="post" id="myform">
    <textarea name="txt1" id="txt1" cols="15" rows="10" form="myform"></textarea>

Try using the wrap element in your textarea

<textarea name="txt1" id="txt1" cols="15" rows="10"></textarea>

add wrap

<textarea name="txt1" id="txt1" cols="15" rows="10" wrap="virtual"></textarea>

you can also use wrap: off, hard, soft and physical

In your database make sure the field txt1 is defined properly (ie type text).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM