2016-08-23 88 views
0

我正在嘗試創建一個日誌文件,但該文件使用相同的字符串寫入兩次。我該怎麼做才能避免這種行爲?嘗試寫入文件時出現重複輸入

 $file = 'newfile.txt'; 
    $current = file_get_contents($file); 
    $current = time()."\n"; 
    file_put_contents($file, $current, FILE_APPEND | LOCK_EX); 

    /* output 
    1471958308 
    1471958308 
    1471958312 
    1471958312 
    1471958734 
    1471958734 
    */ 
+1

你是否從網上運行這個文件?嘗試從控制檯運行它。 –

+0

你的代碼如何被觸發? –

+0

嘗試使用error_log()函數 –

回答

1

由於您使用FILE_APPEND,這將增加在無論是在$current文件的最後,你可以做這個

<?php 

$file = 'newfile.txt'; 
$current = time()."\n"; 
file_put_contents($file, $current, FILE_APPEND | LOCK_EX); 

雖然與您的代碼也沒有爲我重複數據這條線

$current = time()."\n"; 

將覆蓋任何你從文件中這一發言

閱讀
$current = file_get_contents($file); 

反正

我可以給你說,你所得到的是重複的唯一方法是,如果我在$current .= time()."\n";

$file = 'newfile.txt'; 
$current = file_get_contents($file); 
$current .= time()."\n";     //<- not the .= 
file_put_contents($file, $current, FILE_APPEND | LOCK_EX); 
+0

這是如何幫助加倍時間戳的? –

+0

嗯,我不是他發佈了他正在使用的實際代碼 – RiggsFolly

+0

隨着一些服務器設置,這可以實現。 –

0

腳本使用.=代替=的,我使用的是現在是:

$file = 'newfile.txt'; 
$current = time()."\n"; 
file_put_contents($file, $current, FILE_APPEND | LOCK_EX); 

如果我使用運行通過命令行該文件(山貓-dump http://dev.test/index.php),在此之後運行通過瀏覽器(Chrome鱈魚)......這是輸出:

1472044823 
1472044856 
1472044856 

總之當我運行通過鍍鉻的代碼......時間戳添加兩次......爲什麼?