Estoy haciendo este programa y estoy tratando de averiguar cómo escribir datos al principio de un archivo en lugar de al final. "a"/append solo escribe hasta el final, ¿cómo puedo hacer que escriba al principio? Porque "r +" lo hace, pero sobrescribe los datos anteriores.Necesito escribir al comienzo del archivo con PHP
$datab = fopen('database.txt', "r+");
Aquí es toda mi archivo:
<!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>
creo que no hay mejor manera de insertar los datos al comienzo de el archivo. Tienes que mover todos los datos actualmente contenidos en el archivo de todos modos. Para archivos más grandes, puede que necesite leer el archivo parte por parte para que quepa en la memoria. –
¿Qué hay de usar el modo "c" de fopen? ¿No escribe esto al comienzo del archivo? –
@SSHEsto sí, pero también reescribe cualquier cosa en el camino :) –