需要在文件的开头写PHP

我正在编写此程序,并且试图找出如何将数据写入文件的开头而不是结尾。“ a” /追加仅写入结尾,如何使它写入开头?因为“ r +”会执行此操作,但会覆盖先前的数据。


$datab = fopen('database.txt', "r+");

这是我的整个文件:


<!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

            ?>

        </div>

    </body>

</html>


海绵宝宝撒
浏览 554回答 3
3回答

函数式编程

快速而肮脏:<?php$file_data = "Stuff you want to add\n";$file_data .= file_get_contents('database.txt');file_put_contents('database.txt', $file_data);?>

倚天杖

以w +模式而非a +模式打开文件。获取要添加的文本长度($ chunkLength)如果需要,将文件光标设置到文件的开头从文件中读取$ chunkLength个字节将光标返回到$ chunkLength * $ i;写$ prepend从步骤4设置$ prepend一个值执行这些步骤,而EOF$handler = fopen('1.txt', 'w+');//1rewind($handler);//3$prepend = "I would like to add this text to the beginning of this file";$chunkLength = strlen($prepend);//2$i = 0;do{&nbsp; &nbsp; $readData = fread($handler, $chunkLength);//4&nbsp; &nbsp; fseek($handler, $i * $chunkLength);//5&nbsp; &nbsp; fwrite($handler, $prepend);//6&nbsp; &nbsp; $prepend = $readData;//7&nbsp; &nbsp; $i++;}while ($readData);//8fclose($handler);
打开App,查看更多内容
随时随地看视频慕课网APP