如何使用 file_put_contents() 将数据附加到文件?

Bmb*_*iah 3 php foreach android loops

我有一个 android 应用程序,它从 okhttp3 发送多个数据,但我找不到记录在 php 中发送的所有数据的方法。我当前的日志只包含最后一条记录(如下所示)。我最好的猜测是 php 文件数据正在被覆盖,直到最后一条记录..如何记录所有发送的数据?是的,所有数据都是从 android 应用程序发出的...

索引.php

if (isset($_POST))
 {
file_put_contents("post.log",print_r($_POST,true));
}
Run Code Online (Sandbox Code Playgroud)

示例 post.log

 Array
(
    [date] =>  02 Aug, 12:22
    [company] => Assert Ventures
    [lattitude] => 32.8937542
    [longitude] => -108.336584
    [user_id] => Malboro
    [photo_id] => 1
)
Run Code Online (Sandbox Code Playgroud)

我想要的是

(
   [date] =>  02 Aug, 12:22
   [company] => Three Ventures
   [lattitude] => 302.8937542
   [longitude] => -55.336584
   [user_id] => Malboro
   [photo_id] => 1
),
(
   [date] =>  02 Aug, 12:22
   [company] => Two Ventures
   [lattitude] => 153.8937542
   [longitude] => -88.336584
   [user_id] => Malboro
   [photo_id] => 1
),
(
    [date] =>  02 Aug, 12:22
    [company] => Assert Ventures
    [lattitude] => 32.8937542
    [longitude] => -108.336584
    [user_id] => Malboro
    [photo_id] => 1
)
Run Code Online (Sandbox Code Playgroud)

kuc*_*har 10

我认为你应该添加 FILE_APPEND 标志。

<?php
$file = 'post.log';
// Add data to the file
$addData = print_r($_POST,true);
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
file_put_contents($file, $addData, FILE_APPEND | LOCK_EX);
?>
Run Code Online (Sandbox Code Playgroud)


Alo*_*tel 7

您需要传递第三个参数FILE_APPEND

所以你的 PHP 代码看起来像这样,

if (isset($_POST))
 {
file_put_contents("post.log",print_r($_POST,true),FILE_APPEND);
}
Run Code Online (Sandbox Code Playgroud)

FILE_APPEND标志有助于将内容附加到文件末尾而不是覆盖内容。