使用php中的file_put_contents将文件/内容放在目录中

时间:2013-09-08 10:58:08

标签: php

我在使用

时遇到了一个非常简单的问题
 file_put_contents("somefile.txt",$content)

它有效,但是当我尝试将文件放在某个目录中时,如 -

file_put_contents("somedirectory/sonefile.txt",$content);
它不起作用。知道我错过了什么吗?

确切的代码是 -

file_put_contents($_SERVER['DOCUMENT_ROOT']."/temp_code/code.txt",$code);

3 个答案:

答案 0 :(得分:1)

使用realpath()作为@ Amal的答案或使用$_SERVER['DOCUMENT_ROOT'],如下所示,

file_put_contents($_SERVER['DOCUMENT_ROOT']."path/to/your/folder/somefile.txt",$content);

并且在编程时也关心拼写

sonefile.txt - > somefile.txt

最后检查文件夹和文件的权限是否具有写入权限。

答案 1 :(得分:0)

尝试使用绝对路径:

file_put_contents(realpath("somedirectory/sonefile.txt"),$content);

答案 2 :(得分:0)

尝试'chmod($dir, 0777); //make it writable'

    $dir="somedirectory";
    if (!is_dir($dir)) 
    {
      mkdir($dir); //create the directory
      chmod($dir, 0777); //make it writable
   }

    file_put_contents($dir."/somefile.txt",$content);