I am trying to look for a file called test.txt
within the folder called .test
.
<?php
$path = '/localhost/joshcms/.test/test.txt';
$fileexists = file_exists($path);
if ($fileexists == '1') {
$result = 'true';
} else {
$result = 'false';
}
?>
Please excuse the horrible formatting, I am creating this PHP within Jade.
I, first of all, had the $path
variable set to .test/test.txt
so when it searched for the file, it looked in: localhost/joshcms/.test/test.txt
because it was a relative path; because that never worked, I then changed the code to look the way it is above and yet, it still does not work. I then tried with a file that was in the same folder and that worked fine.
I'm not too sure if this error is occurring due to me trying to find something in a hidden folder or if it's just the function doesn't work unless the file is in the same directory as the PHP script/file itself.
file_exists() returns bool(true|false)
, so checking the response against a string '1'
like so if ($fileexists == '1')
will not pass.
The following will work:
$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)
}
Aside: $result
will now, per your code, hold a string value of true/false. If you want $result
to hold a boolean value of true/false, remove the single-quotes, ie. $result = true;
and $result = false;
, respectively.
Your issue is just path-related. It has nothing to do with the dot in the Directory name. That, anyways, has other implications of its own that are not applicable in the current context. You could always use the __DIR_ _ Constant or the dirname( __FILE_ _) Function and work your way up or down to the location of the 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.");
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.