file_put_contents会覆盖数据

时间:2015-11-16 07:49:16

标签: php file-put-contents

每次数据库中有条目时,我都会使用file_put_content在文件中写入数据。它不是附加新条目而是用new覆盖旧数据。这是我正在使用的代码的一部分。我尝试使用APPEND In flag但不起作用。 `       

  include_once(CLASS_PATH."fetch_service.php"); 
  $objfetch = new fetchService();


  $res = $objfetch->fetch_proxy("*","where account_id='".$_SESSION['account_id']."'");
  foreach($res as $result)
  {
  $proxyname=$result['proxyname'];
  $ip=$result['proxyip'];
  $proxyport=$result['port'];
  $proxyuser=$result['username'];
  $proxypwd=$result['password'];
  $proxydomain=$result['domain'];
  $account_id=$result['account_id'];


  $content2 = "";
  $content2 .= ";/*----*-------------------*----------"."\n";
  $content2 .= "; * Created On ".date("Y-m-d")."\n";
  $content2 .= "; * Adding Proxy"."\n";
  //                $content2 .= "; * By ".$_SESSION['username']."\n";
  $content2 .= "; *----*-------------------*----------"."\n\n";



  $content2 .="[$proxyname]"."\n"; //context Name//
  $content2 .="username=$proxyuser"."\n";
  $content2 .="secret=$proxypwd"."\n";
  $content2 .="fromdomain=$proxydomain"."\n";
  $content2 .="host=$ip"."\n";
  $content2 .="port='$proxyport'"."\n";


  $content2 .="canreinvite=yes"."\n";
  $content2 .="nat=force_rport,comedia"."\n";
  $content2 .="type=peer"."\n";
  $content2 .="disallow=all"."\n";
  $content2 .="allow=g729"."\n";
  $content2 .="allow=ulaw"."\n";
  $content2 .="allow=alaw"."\n";


  $file2 = 'trunk_test.conf';
  error_log("======FILE path ====$file2======");
  file_put_contents($file2, $content2, LOCK_EX);




  }

  }
  ?>      `

2 个答案:

答案 0 :(得分:5)

如果要将新数据附加到文件中

你应该使用这个标志

// this will append the content to the end of the file, 
// and prevent anyone else writing to the file at the same time
file_put_contents($file2, $content2, FILE_APPEND | LOCK_EX); 

答案 1 :(得分:0)

foreach(){ //your code for getting data and put into single variable }之后添加以下代码。从foreach内部删除它,并删除$content2 = "";

$file2 = 'trunk_test.conf';
error_log("======FILE path ====$file2======");
file_put_contents($file2, $content2, LOCK_EX);
相关问题