Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要在文件的开头用PHP写_Php_File_Append - Fatal编程技术网

需要在文件的开头用PHP写

需要在文件的开头用PHP写,php,file,append,Php,File,Append,我正在制作这个程序,我试图找出如何将数据写入文件的开头而不是结尾。“a”/append仅写入结尾,如何使其写入开头?因为“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>

我正在制作这个程序,我试图找出如何将数据写入文件的开头而不是结尾。“a”/append仅写入结尾,如何使其写入开头?因为“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

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

Facebook v0.1
#生化需氧量{
保证金:0自动;
宽度:800px;
边框:纯色2px黑色;
}
又快又脏:

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

我认为您可以首先读取文件内容并将其保存在临时变量中,现在将新数据插入文件开头,然后再附加临时变量的内容

$file = file_get_contents($filename); $content = 'Your Content' . $file; file_put_contents($content); $file=文件获取内容($filename); $content='Your content'$文件 文件内容($content);
没有办法像您所想的那样写入文件的开头。我想这是由于操作系统和硬盘驱动器看到文件的原因。它有一个固定的起点和扩展终点。如果你想在中间加些东西,否则就需要滑动。如果它是一个小文件,只需将其全部读取,然后进行操作并写回即可。但是如果不是,如果你总是添加到开始只是反向行顺序,考虑结束作为开始…< /p> 你可以用它来改变注释中的指针。< /P> 必须注意的是,如果您使用
fwrite
,它将删除当前内容。因此,基本上你必须阅读整个文件,使用
fseek
,写下你的新内容,写下文件的旧数据

$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);
$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);
如果您的文件非常大,并且您不想使用太多内存,那么您可能希望使用两个文件的方法,如

$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');
在我看来,本的解决方案似乎更为直截了当


最后一点:我不知道您在
database.txt中储存了什么,但您可以使用数据库服务器更轻松地储存这些内容。

如果您不想将文件的全部内容加载到变量中,可以使用PHP的功能:

这样做的目的是将您要预加的字符串写入临时文件,然后将原始文件的内容写入临时文件的末尾(使用流而不是将整个文件复制到变量中),最后删除原始文件并重命名临时文件以替换它


注意:这段代码最初是基于赵旭的一篇现已不存在的博文编写的。此后,代码出现了分歧,但可以查看原始帖子。

此代码会记住文件开头的数据,以防止它们被覆盖。接下来,它逐个块重写文件中存在的所有数据

$data = "new stuff to insert at the beggining of the file";
$buffer_size = 10000;

$f = fopen("database.txt", "r+");
$old_data_size = strlen($data);
$old_data = fread($f, $old_data_size);
while($old_data_size > 0) {
  fseek($f, SEEK_CUR, -$old_data_size);
  fwrite($f, $data);
  $data = $old_data;
  $old_data = fread($f, $buffer_size);
  $old_data_size = strlen($data);
}
fclose($f);
file\u get\u contents()
file\u put\u contents()
使用的内存比使用
fopen()
fwrite()
fclose()
函数要多:

$fh = fopen($filename, 'a') or die("can't open file");
fwrite($fh, $fileNewContent);
fclose($fh);

您可以使用以下代码在文件的开头和结尾追加文本

$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);
$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);
$myFile=“test.csv”
$context=stream_context_create()
$fp=fopen($myFile,'r',1,$context)
$tmpname=md5(“kumar”)
//这将在文件开头追加文本

文件内容($tmpname,“kumar”)
文件内容($tmpname、$fp、文件附加)
fclose($fp)
取消链接($myFile)
重命名($tmpname,$myFile)

//这将在文件末尾追加文本
文件内容($myFile,“ajay”,file\u APPEND);
  • 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);
    
  • 一行:

    file_put_contents($file, $data."\r\n".file_get_contents($file));
    
    或:


    我认为没有更好的方法在文件开头插入数据。您必须移动文件中当前包含的所有数据。对于较大的文件,您可能需要逐部分读取文件以将其放入内存中。使用fopen的“c”模式如何?这不会写入文件的开头吗?@ssh这是的,但它也会以如下方式重写任何内容:)使用file\u APPEND避免覆盖该文件的最大使用大小?那么多个进程同时写入文件的情况又如何呢?fopen()调用和flock()调用可以避免这种情况吗?谢谢!这非常有效,但只有在文件存在的情况下(我遇到过一个文件可能丢失的情况。非常容易解决:if(!file_exsists($filename)[…])。PHP使用tempnam()生成唯一的文件名。md5()与现有文件发生冲突的风险很小。请参阅,我使用了此解决方案,但将
    $tmpname
    更改为定义为
    $tmpname=tempnam(sys\u get\u temp\u dir(),'tmp\u prepend\u0');
    通过这种方式,它将系统文件夹用于临时文件,将标准php方法用于临时名称,从而减少了文件系统权限错误的发生。@dubrox VincentNikkelen谢谢。我已经更新了代码。如果您在目标文件上有错误权限的问题(例如Apache无法读取),尝试在与目标相同的文件夹中而不是在系统文件夹中创建临时文件。这对我来说很有效。这并没有说明OP要求的“预结束”功能。在这种情况下,$i*$chunkLength不是始终为0吗?