2014-08-29 152 views
0

正如标题所说,我试图用PHP编写创建一个文本文件(最终是一个日志文件),它将不断用字符串更新。本来我试过这样的:用PHP创建+写入文本文件

<?php 
    $myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); 
    $txt = "John Doe\n"; 
    fwrite($myfile, $txt); 
    fclose($myfile); 
?> 

而结果输出是“无法打开文件!”。 有人告诉我,这可能是一个权限问题,所以我想这也:

<?php 

$dir = '/home/Documents'; 

// create new directory with 744 permissions if it does not exist yet 
// owner will be the user/group the PHP script is run under 
if (!file_exists($dir)) { 
    mkdir ($dir, 0744); 
} 

file_put_contents ($dir.'/log.txt', 'Hello File'); 
?> 

而且仍然没有运气。我是PHP和Web服务器管理的新手。我正在运行Ubuntu 14.04LTS,并设置了lighttpd,我正在Firefox和Chrome上测试它。我使用URL:localhost/index.php来运行它。

帮助!我爱你。

+0

对第二个不起作用的是什么?它创建目录吗? – Mattigins 2014-08-29 05:40:54

+0

如果它不创建目录,我会说这是因为您正在尝试创建新目录下的目录没有权限。 – Mattigins 2014-08-29 05:41:23

+0

我认为你需要设置适当的权限,因为它是Ubuntu上的大问题。每次创建新目录时,都需要设置其权限。你也可以用图形来做。右键单击该文件夹并在弹出的窗口上选择权限并设置适当的权限。 – 2014-08-29 05:52:05

回答

0
I think you need to use chmod() 

    $dir = '/home/Documents'; 

    // create new directory with 744 permissions if it does not exist yet 
    // owner will be the user/group the PHP script is run under 
    if (!file_exists($dir)) { 
     mkdir ($dir, 0744); 
    } 
    // use chmod 
    chmod($dir, 755); 
    file_put_contents ($dir.'/log.txt', 'Hello File'); 
+0

此外,你可以通过is_writable()来检查是否可以写入http://stackoverflow.com/questions/5425891/check-if-directory-exists-php – 2014-08-29 05:45:06