Create a File, Write, read and update Content using PHP

In this tutorial, we will look into how to create a file in the server as well as read and update the data in the file using PHP.

Overview

To continue in this we will need to create the following file.

  • Index.php

Index.php

In this file, we first render an HTML form which can be used to specify a name to file as well as the description which is needed to be written in the file.
Initially, it will check if there is a file with the specific name in the Server, if there is a file it will show an exception saying File already exists.
When a file Is created we can write and update data on the file using file_put_content(); PHP built-in method after we specify the target file in the parameters.

<?php
extract($_POST);

if(isset($s))
{
if(file_exists($f))
{
echo "<font color='red'>File Exists</font>";
}
else
{
$fo=fopen("$f","w");
fwrite($fo,$c);
echo "<font color='blue'>File Saved</font>";
}
}
if(isset($d))
{
if(file_exists($f))
{
$fo=fopen($f,"r");
$filesize=filesize($f);
$c=fread($fo,$filesize);
}
else
{
echo "<font color='red'>No File Found</font>";
}

}
//update contents
if(isset($u))
{
$file = $f;
$current = file_get_contents($file);
$current .=$c;
file_put_contents($file,$current);
}
?>

<style>
input,textarea{width:250px}

input[type=submit]{width:70px}
</style>
<div align="center">
<form method="post">
<table width="250" border="0">

<tr>
<td><input placeholder="your file name with extension" type="text" name="f" value="<?php echo @$f; ?>"/></td>
</tr>

<tr>
<td><textarea placeholder="your contents you want to write" name="c">
<?php echo @$c; ?>
</textarea></td>
</tr>
<tr>
<td><input type="submit" value="Save" name="s"/>
<input type="submit" value="Disp" name="d"/>
<input type="submit" value="Update" name="u"/></td>
</tr>
</table>
</form>
</div>

Bonus

You can download the Full source code here.

If you face any challenge during the process feel free to comment or direct a mail I would happy to help you.
If you find this post helpful don’t forget to share it with your friends and community.

Download the complete source code.

Grab the the free working demo Intantly!

You have Successfully Suscribed!

Leave a Reply

Your email address will not be published. Required fields are marked *