I'm making this program and I'm trying to find out how to write data to the beginning of a file rather than the end. "a"/append only writes to the end, how can I make it write to the beginning? Because "r+" does it but overwrites the previous data.
$datab = fopen('database.txt', "r+");
Here is my whole file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Facebook v0.1</title>
<style type="text/css">
#bod{
margin:0 auto;
width:800px;
border:solid 2px black;
}
</style>
</head>
<body>
<div id="bod">
<?php
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$comment = $_REQUEST['comment'];
$datab = $_REQUEST['datab'];
$gfile = $_REQUEST['gfile'];
print <<<form
<table border="2" style="margin:0 auto;">
<td>
<form method="post" action="">
First Name :
<input type ="text"
name="fname"
value="">
<br>
Last Name :
<input type ="text"
name="lname"
value="">
<br>
Comment :
<input type ="text"
name="comment"
value="">
<br>
<input type ="submit" value="Submit">
</form>
</td>
</table>
form;
if((!empty($fname)) && (!empty($lname)) && (!empty($comment))){
$form = <<<come
<table border='2' width='300px' style="margin:0 auto;">
<tr>
<td>
<span style="color:blue; font-weight:bold;">
$fname $lname :
</span>
$comment
</td>
</tr>
</table>
come;
$datab = fopen('database.txt', "r+");
fputs($datab, $form);
fclose($datab);
}else if((empty($fname)) && (empty($lname)) && (empty($comment))){
print" please input data";
} // end table
$datab = fopen('database.txt', "r");
while (!feof($datab)){
$gfile = fgets($datab);
print "$gfile";
}// end of while
?>
</div>
</body>
</html>
There is no way to write to the beginning of a file like you think. This is I guess due to reason how OS and HDD are seeing the file. It has got a fixed start and expanding end. If you want to add something in the middle or beggining it requires some sliding. If it is a small file just read it all and do your manipulation and write back. But if not, and if you are always adding to the beginning just reverse line order, consider the end as beginning...
This code remembers data from the beginning of the file to protect them from being overwritten. Next it rewrites the all the data existing in file chunk by chunk.
do these steps, while EOF