为了账号安全,请及时绑定邮箱和手机立即绑定

需要在文件的开头写PHP

需要在文件的开头写PHP

PHP
海绵宝宝撒 2019-09-24 16:41:16
我正在编写此程序,并且试图找出如何将数据写入文件的开头而不是结尾。“ 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>
查看完整描述

3 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

快速而肮脏:


<?php

$file_data = "Stuff you want to add\n";

$file_data .= file_get_contents('database.txt');

file_put_contents('database.txt', $file_data);

?>


查看完整回答
反对 回复 2019-09-24
?
倚天杖

TA贡献1828条经验 获得超3个赞

以w +模式而非a +模式打开文件。

获取要添加的文本长度($ chunkLength)

如果需要,将文件光标设置到文件的开头

从文件中读取$ chunkLength个字节

将光标返回到$ chunkLength * $ i;

写$ prepend

从步骤4设置$ prepend一个值

执行这些步骤,而EOF


$handler = fopen('1.txt', 'w+');//1

rewind($handler);//3

$prepend = "I would like to add this text to the beginning of this file";

$chunkLength = strlen($prepend);//2

$i = 0;

do{

    $readData = fread($handler, $chunkLength);//4

    fseek($handler, $i * $chunkLength);//5

    fwrite($handler, $prepend);//6


    $prepend = $readData;//7

    $i++;

}while ($readData);//8


fclose($handler);


查看完整回答
反对 回复 2019-09-24
  • 3 回答
  • 0 关注
  • 551 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信