Reputation: 1
I have a code :
<?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>
When I click submit content of the textarea is lost. How can I solve this?
Upvotes: 0
Views: 76
Reputation: 1273
If you want to keep the content of the textarea even after the form submission use the code:
<?php
$theData = '';
if(isset($_POST['data'])) {
// here is assigning the content to be displayed on form submit
$theData = $_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>
Upvotes: -2
Reputation: 2317
You need to add $theData variable in submit also because after submitting you again need to read the data in order to show them.
<?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);
?>
And put htmlspecialchars while echo that variable
<?php echo htmlspecialchars($theData); ?>
Upvotes: 2
Reputation: 6565
Make a little change in your code:
$fh = fopen($myFile, 'rb'); // Notice b here
$theData = fread($fh, filesize($myFile));
Upvotes: 1