我正在名为.test
的文件夹中查找名为test.txt
的文件。
<?php
$path = '/localhost/joshcms/.test/test.txt';
$fileexists = file_exists($path);
if ($fileexists == '1') {
$result = 'true';
} else {
$result = 'false';
}
?>
请原谅糟糕的格式,我正在Jade中创建这个PHP。
I、 首先,将$path
变量设置为.test/test.txt
,因此当它搜索文件时,它会查找:localhost/joshcms/.test/test.txt
,因为它是一个相对路径;因为这从来都不起作用,所以我修改了代码,使其看起来像上面的样子,但它仍然不起作用。然后,我尝试使用同一文件夹中的一个文件,效果很好。
我不太确定这个错误是因为我试图在隐藏的文件夹中找到什么而发生的,还是因为除非文件与PHP脚本/文件本身在同一目录中,否则函数不起作用。
file_exists()返回bool(true|false)
,因此根据字符串'1'
检查响应,这样if ($fileexists == '1')
就不会通过。
以下将起作用:
$path = '/localhost/joshcms/.test/test.txt';
if ( file_exists($path) ) { // returns bool(true|false) response
$result = 'true'; // if file exists, this condition will satisfy as the file does exist bool(true)
} else {
$result = 'false'; // if the file at $path does not exist, this will satisfy; bool(false)
}
此外:根据您的代码,$result
现在将持有true/false的字符串值。如果希望$result
包含true/false的布尔值,请删除单引号,即分别为$result = true;
和$result = false;
。
您的问题只是与路径有关。它与目录名称中的点无关。无论如何,这本身也有其他不适用于当前情况的含义。您可以始终使用__DIR__常量或dirname(__FILE__)函数,并向上或向下移动到文件的位置。
<?php
$file1 = __DIR__ . "/.test/test.txt"; //THIS SCRIPT LIVES IN THE SAME DIRECTORY AS THE ".test" FOLDER
$file2 = __DIR__ . "/../.test/test.txt"; //THIS SCRIPT LIVES 1 DIRECTORY BELOW THE ".test" FOLDER
if( file_exist($file1) ){
var_dump("THE FILE: {$file1} EXISTS.");
}else{
var_dump("CANNOT FIND THE FILE: {$file1} EXISTS.");
}