2014-02-21 74 views
0

我似乎无法确定为什么当客户端IP存在时,它不附加到该文件。file_put_contents()不写入文件

我一直运行echo语句直到file_put_contents()函数,我可以看到变量中的内容。

$file = 'log.txt'; 

$now = new DateTime(); 
$timestamp = $now->format('Y-m-d H:i'); 

if (isset($_SERVER['REMOTE_ADDR'])){ 
    $log = $_SERVER['REMOTE_ADDR'].' '. $timestamp; 
}else{ 
    $log = 'SERVER '.$timestamp; 
} 

$log = strval($log); //convert to string 
$log .= "\n\r"; 

file_put_contents($file,$log,FILE_APPEND); 
+1

明显的问题在这里...你有写log.txt权限吗? –

+0

你检查了文件的权限吗? – TimWolla

+0

您应该始终检查'file_put_contents'的返回值以查看它是否返回FALSE。 –

回答

-2

您需要打开该文件,然后才能写入文件,在这里你可以试试这个 -

<?php 
$my_file = fopen("log.txt", "r+"); 
    ?> 

你甚至可以做一个检查,看看是否该文件是存在性,以及,如果不是,你可以创建它!

这里是一个网页,可能会帮助你

File opening for php

+3

'file_put_contents'不需要fopen或fclose:http://es1.php.net/manual/en/function.file-put-contents.php – JBES

0

首先,你问这个问题,就意味着你还没有掌握基本的调试方法。

调试代码需要打开错误报告。通过添加 error_reporting(E_ALL); ini_set('display_errors','on'); 在代码的开头或修改php配置文件 error_reporting = E_ALL display_errors =在 可以做到这一点。

无法写入文件通常是因为权限问题。

祝你好运!