2014-10-09 32 views
0

我正在寫一個PHP腳本,其中我必須將系統正常運行時間,當前時間以及系統中登錄的用戶數量寫入日誌文件,並通過crontab持續更新。使用php將多個條目添加到使用crontab的輸出文件?

我需要幫助的是我想更新累積在文件中並不斷添加。到目前爲止,無論何時我的腳本被執行,最新的更新都會覆蓋以前的更新。

我所做的是我試圖聲明一個條目數組,並且在我遍歷數組時將更新內容推送到數組中(這可能是我的一部分的半成品邏輯) 。

我的代碼:

$fileName = '../so-and-so directory/output.log'; 
$dt = date('m/d/y'); 
$time = date('h:i A'); 
$data = shell_exec('uptime'); 
$uptime= explode(' up ', $data); 
$uptime = explode(', ', $uptime[1]); 
$uptime = $uptime[0].','.$uptime[1]; 
$users = system('w', $who); 
$array = new SplFixedArray(3); 



$fileLog = fopen($fileName, 'w'); 
$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n". 
"System uptime ". $uptime ."\n" ."Users " . $users; 

foreach ($array as $entry) { 

array_push(file_put_contents($fileName, $fileString)); 

} 

fclose($fileLog); 

我覺得這個解決方案很簡單,但我很想念它。請有人告訴我嗎?

+0

what $ array?它不存在 – 2014-10-09 03:36:33

+0

這是我試圖用我的腳本試驗的一部分半成品邏輯。我對PHP很陌生,所以對我來說這是一個開始。 – 2014-10-09 03:43:03

回答

0

「w」文件模式在打開時截斷文件。 「a」代替追加。有關詳細信息,請參閱fopen(3)或PHP文檔。

另外,file_put_contents()正在破壞文件。改爲嘗試fwrite()

+0

theres更多的東西比這個腳本打破了 – 2014-10-09 03:37:09

0

drop fopen;只需使用

file_put_contents($fileName, $fileString); 

file_put_contents默認會覆蓋現有的文件。

簡而言之:

$fileName = '../so-and-so directory/output.log'; 
$dt = date('m/d/y'); 
$time = date('h:i A'); 
$data = shell_exec('uptime'); 
$uptime= explode(' up ', $data); 
$uptime = explode(', ', $uptime[1]); 
$uptime = $uptime[0].','.$uptime[1]; 
$users = system('w', $who); 

$fileString = "Date: ".$dt. "\n". " Time: ".$time . "\n". 
"System uptime ". $uptime ."\n" ."Users " . $users; 

file_put_contents($fileName, $fileString); 
0

所以,事實證明,我需要修改我的crontab文件爲這樣:

* * * * * such-and-such-script.php >> ../so-and-so directory/output.log 2>&1 

爲了讓他們追加不上一個被新的所覆蓋。我也失去了fopen(),而不是做file_put_contents,而是在文件中做了fwrite()。它現在很好用。謝謝!

+0

只要腳本被調用,cron作業中的任何東西實際上都沒有什麼不同 – 2014-10-09 19:53:05

相關問題