【问题标题】:PHP, Changing directory not workingPHP,更改目录不起作用
【发布时间】:2016-12-21 06:23:59
【问题描述】:

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() 失败时,它必须返回警告。为您的 chdir 代码执行 var_dump
  • 哦,哇,我刚刚启用了错误报告,我收到“警告:chdir(): Permission denied (errno 13) in /var/www/html/note_interaction.php on line 39”警告
  • @Tom 我希望很清楚,您的 apache 用户必须有权访问该文件夹。但更有可能的是,所有必需的文件都应该位于 apache 可以访问的文件夹中。无论如何,如果您无法自己修复权限,请更新您的帖子以适应新问题。 (P.S.阅读这篇文章serverfault.com/questions/357108/…

标签: php linux


【解决方案1】:

我不确定您的 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);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 2019-01-23
    • 2016-03-14
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    • 2022-10-06
    相关资源
    最近更新 更多