2017-08-02 140 views
3

我使用php dir()函数从目录获取文件,并通过它循环。即使文件存在,php dir函数也会返回null

$d = dir('path'); 

while($file = $d->read()) { 
    /* code here */ 
} 

但这返回false,并给出

上的空

调用成员函数read()方法,但该目录是否存在以及文件在那里。

此外,是否有任何替代我的上述代码?

+0

是路径的绝对路径?相对路径?相对于哪里? –

+0

使用'is_dir(path);'函数 – Jer

回答

0

如果你看看到documentation您将看到:

返回目录的实例,或NULL以错误的参数,或 FALSE在另一个错误的情况。

所以Call to member function read() on null意味着你有一个错误(我认为这是failed to open dir: No such file or directory in...)。

您可以使用file_existsis_dir来检查给定的路径是否是目录以及它是否真的存在。

例子:

<?php 
... 
if (file_exists($path) && is_dir($path)) { 
    $d = dir($path); 

    while($file = $d->read()) { 
     /* code here */ 
    } 
} 
1

尝试使用此:

if ($handle = opendir('/path/to/files')) { 
    echo "Directory handle: $handle\n"; 
    echo "Entries:\n"; 

    /* This is the correct way to loop over the directory. */ 
    while (false !== ($entry = readdir($handle))) { 
     echo "$entry\n"; 
    } 

    /* This is the WRONG way to loop over the directory. */ 
    while ($entry = readdir($handle)) { 
     echo "$entry\n"; 
    } 

    closedir($handle); 
} 

来源: http://php.net/manual/en/function.readdir.php

0

如有检查您的文件路径的路径是正确的。那么请试试这个代码,这可能会帮助你。由于

<?php 
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); 
// Output one character until end-of-file 
while(!feof($myfile)) { 
    echo fgetc($myfile); 
} 
fclose($myfile); 
?> 
相关问题