PHP 版本:5.4.16
我在 Centos Linux 机器上运行 Apache 服务器,但我用于更改目录的 PHP 代码不起作用。我的最终目标是尝试读取位于不同目录中的文件,但它不会读取该文件。我的第一次尝试是
$filename=("/home/tom/notes/test_notes.txt");
$file = fopen( $filename, "r" );
这没有用,所以我用这个问题的答案修复了它:Reading a file in a different directory php
$filename=(__DIR__."/home/tom/notes/test_notes.txt");
$file = fopen( $filename, "r" );
但是那也不会读取文件,然后我检查它是否可以读取同一目录中的文本文件并且它有效,所以我决定将目录更改为文本文件所在的目录可以工作。
我用这段代码四处走动,但它没有改变目录:
echo getcwd();
chdir("/home/tom/notes");
echo getcwd();
它返回:
/var/www/html
/var/www/html
(没有换行..)
该目录与 shell 中的 cd/home/tom/notes 一样有效,有效
知道是什么不允许它更改目录吗? 或者有没有其他更好的方法来读取位于另一个目录中的文件?
(我使用这段代码来查看打开文件是否有效)
if( $file == false )
{
echo "ERROR: Unable to open file";
}
最佳答案
我不确定您的chdir()
代码有什么问题,如果它失败,则必须有一些警告 请参阅文档here尝试调试您的代码,如下所示并启用 error reporting .
echo getcwd();
$response = chdir("/home/tom/notes");
var_dump($response);
echo getcwd();
要读取文件,请参见下面的示例。 More Details
<?php
$myfile = fopen("/path/of/your/file", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
关于PHP,更改目录不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41256406/