如何保持textarea内容

时间:2017-12-08 12:25:16

标签: php

我有一个代码:

<?php
    if(isset($_POST['data'])) {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'w');
        fwrite($fh, $_POST['data']);
    } else {
        $myFile = "/var/www/vhosts/domain/subdomain/index.php";
        $fh = fopen($myFile, 'r');
        $theData = fread($fh, filesize($myFile));
    }
    fclose($fh);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <title>Untitled Document</title>
    </head>
    <body>
        <form name="test" method="post" action="">
            <textarea name="data"><?php echo $theData; ?></textarea>
            <input type="submit" name="submit" value="Update File" />
        </form>
    </body>
</html>

当我点击提交内容时,textarea丢失了。 我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您还需要在提交中添加$ theData变量,因为再次提交后需要读取数据才能显示它们。

<?php
if(isset($_POST['data'])) {
    $myFile = "/var/www/vhosts/domain/subdomain/index.php";

    //here I changed the permission with read/write mode.
    $fh = fopen($myFile, 'rw');
    fwrite($fh, $_POST['data']);
    //this line to be added for getting the data after inserting.
    $theData = fread($fh, filesize($myFile));
} else {
    $myFile = "/var/www/vhosts/domain/subdomain/index.php";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, filesize($myFile));
}
fclose($fh);
?>

将htmlspecialchars放回到该变量

<?php echo htmlspecialchars($theData); ?>

答案 1 :(得分:1)

对代码进行一些更改:

$fh = fopen($myFile, 'rb'); // Notice b here
$theData = fread($fh, filesize($myFile));

答案 2 :(得分:-2)

如果您想在表单提交后保留textarea的内容,请使用以下代码:

console.log(this.options);
console.log(typeof this.options[Symbol.iterator] === 'function');

for (let option of this.options) {
    console.log(option.id);
}