Need to write at beginning of file with PHP

2019-01-02 21:07发布

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>

标签: php file append
9条回答
骚的不知所云
2楼-- · 2019-01-02 21:18

If you don't want to load the entire contents of the file into a variable, you can use PHP's Streams feature:

function prepend($string, $orig_filename) {
  $context = stream_context_create();
  $orig_file = fopen($orig_filename, 'r', 1, $context);

  $temp_filename = tempnam(sys_get_temp_dir(), 'php_prepend_');
  file_put_contents($temp_filename, $string);
  file_put_contents($temp_filename, $orig_file, FILE_APPEND);

  fclose($orig_file);
  unlink($orig_filename);
  rename($temp_filename, $orig_filename);
}

What this does is writes the string you want to prepend to a temporary file, then it writes the contents of the original file to the end of the temporary file (using streams instead of copying the whole file into a variable), and then it removes the original file and renames the temporary file to replace it.

Note: This code was originally based on a now-defunct blog post by Chao Xu. The code has since diverged, but the original post can be viewed in the Wayback Machine.

查看更多
忆尘夕之涩
3楼-- · 2019-01-02 21:25

The quick and dirty:

<?php
$file_data = "Stuff you want to add\n";
$file_data .= file_get_contents('database.txt');
file_put_contents('database.txt', $file_data);
?>
查看更多
倾城一夜雪
4楼-- · 2019-01-02 21:29

You can use the following code to append text at the beginning and end of the file.

$myFile = "test.csv";<br>
$context = stream_context_create();<br>
  $fp = fopen($myFile, 'r', 1, $context);<br>
  $tmpname = md5("kumar");<br>

//this will append text at the beginning of the file<br><br>
  file_put_contents($tmpname, "kumar");<br>
  file_put_contents($tmpname, $fp, FILE_APPEND);<br>
  fclose($fp);<br>
  unlink($myFile);<br>
  rename($tmpname, $myFile);<br><br>
  //this will append text at the end of the file<br>
  file_put_contents($myFile, "ajay", FILE_APPEND);
查看更多
笑指拈花
5楼-- · 2019-01-02 21:29

You can use fseek to change the pointer in the note.

It has to be noted that if you use fwrite it will erase the current content. So basically you have to read the whole file, use fseek, write your new content, write the old data of the file.

$file_data = file_get_contents('database.txt')
$fp = fopen('database.txt', 'a');
fseek($fp,0);
fwrite($fp, 'new content');
fwrite($fp, $file_data);
fclose($fp);

If your file is really huge and you don't want to use too much memory, you might want to have two file approach like

$fp_source = fopen('database.txt', 'r');
$fp_dest = fopen('database_temp.txt', 'w'); // better to generate a real temp filename
fwrite($fp_dest, 'new content');
while (!feof($fp_source)) {
    $contents .= fread($fp_source, 8192);
    fwrite($fp_dest, $contents);
}
fclose($fp_source);
fclose($fp_dest);
unlink('database.txt');
rename('database_temp.txt','database.txt');

The solution of Ben seems to be more straightforward in my honest opinion.

One last point: I don't know what you are stocking in database.txt but you might do the same more easily using a database server.

查看更多
柔情千种
6楼-- · 2019-01-02 21:32

file_get_contents() and file_put_contents() use more memory than using the fopen(), fwrite(), and fclose() functions:

$fh = fopen($filename, 'a') or die("can't open file");
fwrite($fh, $fileNewContent);
fclose($fh);
查看更多
孤独寂梦人
7楼-- · 2019-01-02 21:33

I think what you can do is first read the content of the file and hold it in a temporary variable, now insert the new data to the beginning of the file before also appending the content of the temporary variable.

$file = file_get_contents($filename);
$content = 'Your Content' . $file;
file_put_contents($content);  
查看更多
登录 后发表回答