How to view modify and save text file using PHP

Last updated on February 27th, 2022 at 08:15 am

Click to rate this tutorial!
[Total: 3 Average: 4.7]

We are using fopen to open the file and fputs to save the file. There will be a text area where you can edit the file and submit the changes.

Here is the PHP code, make sure to update the filename and the location to be redirected.

<?php
//your file name here
$fn = "My_File.txt";
if (isset($_POST['content']))
{
    $content = stripslashes($_POST['content']);
    $fp = fopen($fn,"w") or die ("Error opening file in write mode!");
    fputs($fp,$content);
    fclose($fp) or die ("Error closing file!");
    header('Location: ANY_FILE_TO_BE_REDIRECTED.php');
}
?>

Add this HTML code after the PHP section

<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
    <textarea rows="15" cols="80" name="content"><?php readfile($fn); ?></textarea>
    <br />
    <input type="submit" value="Save"/>
</form>

Let us say I have a file named modify.php, then the code inside that will look like this

<?php
//your file name here
$fn = "My_File.txt";
if (isset($_POST['content']))
{
    $content = stripslashes($_POST['content']);
    $fp = fopen($fn,"w") or die ("Error opening file in write mode!");
    fputs($fp,$content);
    fclose($fp) or die ("Error closing file!");
    header('Location: modify.php');
}
?>
<form action="<?php echo $_SERVER["PHP_SELF"] ?>" method="post">
    <textarea rows="15" cols="80" name="content"><?php readfile($fn); ?></textarea>
    <br />
    <input type="submit" value="Save"/>
</form>

Demo

Click to rate this tutorial!
[Total: 3 Average: 4.7]

Leave a Reply

Your email address will not be published.