file_put_contents无法在包含的路径中创建文件


file_put_contents fails to create file in the included path

我正试图在桌面上创建一个文本文件。我使用set_include_path()创建了一个包含路径,但该文件是在我的examplep/htdocs文件夹中创建的。如何在桌面上创建文件夹??有可能吗??

set_include_path(',;c:/users/shimantta/Desktop');
echo file_put_contents("/test.txt","Hello World. Testing!",FILE_USE_INCLUDE_PATH);

include路径是PHP在包含/需要文件时搜索的路径,而不是在写入文件时搜索。

include_path指定require、include、fopen()所在的目录列表,file()、readfile()和file_get_contents()函数查找文件。

只需给出完整的路径:

file_put_contents("c:/users/shimantta/Desktop/test.txt", "Hello World. Testing!");

只有当运行脚本的用户或运行Web服务器的用户有权写入该目录时,这才会起作用。

set_include_path没有指定活动目录,而是指定要查找的目录,以防您想要包含文件。例如:

set_include_path('C:'php'libs'');
include_once('lib.php');

您要查找的是chdir会更改活动目录。因此,以下代码将把您的文件写入C:'documents':

chdir('C:'documents'');
file_put_contents('test.txt',"Test");

或者你可以自己指定整个路径:

file_put_contents('C:'documents'test.txt',"Test");

您的"/"将其放在安装的根文件夹中

file_put_contents("test.txt","Hello World. Testing!");

将其放在当前主页的当前目录中

file_put_contents(dirname(__FILE__)."/test.txt","Hello World. Testing!");

wil将其放在当前脚本目录中(如果包含)。

如果你想把它放在另一个目录中,只需告诉路径

file_put_contents("/path/to/test.txt","Hello World. Testing!");

对于windows,您可能需要将反斜杠/path/to/test.txt替换为双反斜杠''path''to''test.txt

如果要使用FILE_use_INCLUDE_PATH,则必须删除斜线(表示绝对路径),并在包含路径定义中使用windows反斜线,请在第一个选项中指定Desktop。我认为这个文件以前应该存在。

set_include_path("c:''users''shimantta''Desktop;.");
echo file_put_contents("test.txt","Hello World. Testing!", FILE_USE_INCLUDE_PATH);

EDIT:您可以通过函数 stream_resolve_include_path("test.txt") 来知道test.txt的路径

For在网站根文件夹中动态创建robots.txt。

$data = "User-agent: *'nAllow: /wp-content/uploads/'nAllow: /wp-content/plugins/'nDisallow: /wp-admin/'n'n";
$data .= "Sitemap: {$site_url[ 'scheme' ]}://{$site_url[ 'host' ]}/sitemap_index.xml";
file_put_contents( $_SERVER['DOCUMENT_ROOT'] .'/robots.txt', $data, 0 );