I have a php function that renames two separate image files from a temporary to permanent path after first confirming that the temporary path exists.
When it checks for the fist file it works fine but, for some reason, the second file never passes the if(file_exists()) even though I can confirm with 100% certainty that the file path being checked does, in fact, exist.
The image files have different names but the codes are otherwise structured exactly the same so I can't see why one would work and the other wouldn't.
if(file_exists('temp/'.strtolower($option['image1']))){
$path1 = 'images/'.strtolower($option['image1']); // upload directory
$tmp1 = 'temp/'.strtolower($option['image1']);
if(rename($tmp1, $path1)){
$error = 0;
}else{
$error = 4;
}
}
if(file_exists('temp/'.strtolower($option['image2']))){
$path2 = 'images/'.strtolower($option['image2']); // upload directory
$tmp2 = 'temp/'.strtolower($option['image2']);
if(rename($tmp2, $path2)){
$error = 0;
}else{
$error = 5;
}
}
Is there an issue with calling file_exists() twice? How else can I check for both paths?
Edit
As per Marco-A's suggestion, I added clearstatcache(); between the two if/then blocks and it worked like a charm.
The only two possibilities (if you're absolutely sure the file path exists) I'm seeing are either 1.) a stat cache problem (you can clear the cache with clearstatcache) or 2.) a permission issue. Consider this:
$ touch /tmp/locked/file
$ php is_file_test.php
$ bool(true)
$ chmod -x /tmp/locked
$ php is_file_test.php
$ bool(false)
So it might be, that the parent directory of that file doesn't have the x (executable) permission bit set. This prevents any process from iterating and accessing the directory's content.
The uploaded file names can have uppercase characters. If you use strtolower in the file_exists function, you probably wouldn't be looking for the original file path.
if(file_exists('temp/' . strtolower($option['image']))){
// ...
}
Should be changed to:
if(file_exists('temp/' . $option['image'])){
// ...
}
Strange behaviour, exentially:
(the name of the folder depends on the date - the purpose is a hit counter of the website, broken down by day)
if (!is_dir($folder)) { // first access in the day
mkdir($folder);
}
Well: on the server in internet all works well.
But when i try in local, with the server simulator of Easy PHP, happens that:
(a) The first time, no problem. The folder doesn't exists and it is created.
(b) subsequently, for example to a page refresh, the program flow again goes in the IF (!!!) generating the error (at line of mkdir) of kind: "Warning: mkdir(): No such file or directory in [...]".
All parent part of the directory $folder exists.
Thanks
.
Try using a recursive directory creation function:
function mkdir_r($dirName, $rights = 0777)
{
$dirs = explode(DIRECTORY_SEPARATOR , $dirName);
$dir = '';
if (strpos($dirs[count($dirs) - 1], '.')) {
array_pop($dirs);
}
foreach ($dirs as $part) {
$dir .= $part . DIRECTORY_SEPARATOR ;
if (!is_dir($dir) && strlen($dir) > 0) {
mkdir($dir, $rights);
}
}
}
This way all directories up to the directry you wanted to create are created if they don't exist.
mkdir doesn't work recursively unfortunately.
If anyone faces the issue; Use the native clearstatcache() function after you delete the file.
I'm quoting the interesting part of the original documentation
You should also note that PHP doesn't cache information about non-existent files. So, if you call file_exists() on a file that doesn't exist, it will return false until you create the file. If you create the file, it will return true even if you then delete the file. However unlink() clears the cache automatically.
For further information here is the documentation page: https://www.php.net/manual/en/function.clearstatcache.php
Here's my code; I've renamed the directories, obviously. ;)
$thepath = "/var/www/vhosts/sub.domain.co.uk/web/apps/storage/".$userclient."/evidence/".$scid."/".$doctype."/";
$testdir = is_dir($thepath);
if ($testdir == false) {
mkdir($thepath, 0777);
}
In this case, the following variables apply;
$userclient = '000';
$scid = '9263';
$doctype = 'Insurance Policy';
So, the path should be;
/var/www/vhosts/sub.domain.co.uk/web/apps/storage/000/evidence/9263/Insurance Policy/
I know this works, EVERYWHERE else in my code, I have other applications using an almost identical setup. But the one above, appears to be tripping up on /evidence/ - it sets the permissions to 755, but will then create the directories per time I run the code, if I set evidence to 777 (Octal).
I get the following error message using;
if (!#mkdir($thepath)) {
$error = error_get_last();
echo $error['message'];
}
mkdir(): No such file or directory
Any help would be greatly appreciated, I have to finish this application by Thursday - and this file upload part is the last bit!
Thank you!
PHP can't find directory in which you want to create other directory.
You need to set $recursive param as true:
mkdir($thepath, 0777, true);
Maybe you want to try mkdir($path,$mode,true) to create missing links as well?
I have the following folder structure:
images/photo-gallery/2e/
72/
rk/
u3/
va/
yk/
... and so on. Basically, each time an image is uploaded it hashes the name and then creates a folder with the first two letters. So inside of 2e is 2e0gpw1p.jpg
Here's the thing... if I delete an image, it will delete the file but it will keep the folder that it's in. Now when I have a TON of images uploaded, that will be fine since a lot of images will share the same folder.. but until then, I will end up having a bunch of empty directories.
What I want to do is search through the photo-gallery folder and go through each directory and see which folders are empty.. if there are any empty folders then it will remove it.
I know how to do that for a single directory, like the 2e folder. But how would I do it for all the folders inside the photo-gallery folder?
The PHP function rmdir() will throw a warning if the directory is not empty, so you can use it on non-empty directories without risking deleting them. Combine that with scandir() and array_slice (to remove . and ..), and you can do this:
foreach(array_slice(scandir('images/photo-gallery'),2) as $dir) {
#rmdir('images/photo-gallery/' . $dir); // use # to silence the warning
}
while you could do with with php, i'm inclined to use the os for such a task. Of course you can call the below with php
find <parent-dir> -depth -type d -empty -exec rmdir -v {} \;
PLEASE READ THIS WARNING I DID NOT TEST BUT HAVE USED SIMILAR CODE DOZENS OF TIMES. FAMILURIZE YOURSELF WITH THIS AND DO NOT USE IF YOU DO NOT UNDERSTAND WHAT IT IS DOING THIS COULD POTENTIALLY WIPE YOUR SITE FROM THE SERVER.
EDIT BACKUP EVERYTHING BEFORE TRYING THIS YOUR FIRST TIME THE PATH IS VERY VERY IMPORTANT!
Ok with that said this is quite easy :)
<?php
function recursiveDelete($path){
$ignore = array(
'cgi-bin',
'.',
'..'
); // Directories to ignore
$dh = opendir($path); // Open the directory
while(false !== ($file = readdir($dh))){ // Loop through the directory
if(!in_array($file, $ignore)){ // Check that this file is not to be ignored
if(is_dir($path."/".$file)){ // Its a directory, keep going
if(!iterator_count(new DirectoryIterator($path."/".$file)))
rmdir($path."/".$file); // its empty delete it
} else {
recursiveDelete($path."/".$file);// Recursive call to self
}
}
}
}
closedir($dh); // All Done close the directory
}
// WARNING IMPROPERLY USED YOU CAN DUMP YOUR ENTIRE SERVER USE WITH CAUTION!!!!
// I WILL NOT BE HELD RESPONSIBLE FOR MISUSE
recursiveDelete('/some/directoy/path/to/your/gallery');
?>
I'm having a very weird issue with file_exists(). I'm using this function to check if 2 different files in the same folders do exist. I've double-checked, they BOTH do exist.
echo $relative . $url['path'] . '/' . $path['filename'] . '.jpg';
Result: ../../images/example/001-001.jpg
echo $relative . $url['path'] . '/' . $path['filename'] . '.' . $path['extension'];
Result: ../../images/example/001-001.PNG
Now let's use file_exists() on these:
var_dump(file_exists($relative . $url['path'] . '/' . $path['filename'] . '.jpg'));
Result: bool(false)
var_dump(file_exists($relative . $url['path'] . '/' . $path['filename'] . '.' . $path['extension']));
Result: bool(true)
I don't get it - both of these files do exist. I'm running Windows, so it's not related to a case-sensitive issue. Safe Mode is off.
What might be worth mentioning though is that the .png one is uploaded by a user via FTP, while the .jpg one is created using a script. But as far as I know, that shouldn't make a difference.
Any tips?
Thanks
file_exists() just doesn't work with HTTP addresses.
It only supports filesystem paths (and FTP, if you're using PHP5.)
Please note:
Works :
if (file_exists($_SERVER['DOCUMENT_ROOT']."/folder/test.txt")
echo "file exists";
Does not work:
if (file_exists("www.mysite.com/folder/test.txt")
echo "file exists";
Results of the file_exists() are cached, so try using clearstatcache(). If that not helped, recheck names - they might be similar, but not same.
I found that what works for me to check if a file exists (relative to the current php file it is being executed from) is this piece of code:
$filename = 'myfile.jpg';
$file_path_and_name = dirname(__FILE__) . DIRECTORY_SEPARATOR . "{$filename}";
if ( file_exists($file_path_and_name) ){
// file exists. Do some magic...
} else {
// file does not exists...
}
Just my $.02: I just had this problem and it was due to a space at the end of the file name. It's not always a path problem - although that is the first thing I check - always. I could cut and paste the file name into a shell window using the ls -l command and of course that locates the file because the command line will ignore the space where as file_exists does not. Very frustrating indeed and nearly impossible to locate were it not for StackOverflow.
HINT: When outputting debug statements enclose values with delimiters () or [] and that will show a space pretty clearly. And always remember to trim your input.
It's because of safe mode. You can turn it off or include the directory in safe_mode_include_dir. Or change file ownership / permissions for those files.
php.net: file_exists()
php.net: safe mode
Try using DIRECTORY_SEPARATOR instead of '/' as separator. Windows uses a different separator for file system paths (backslash) than Linux and Unix systems.
A very simple trick is here that worked for me.
When I write following line, than it returns false.
if(file_exists('/my-dreams-files/'.$_GET['article'].'.html'))
And when I write with removing URL starting slash, then it returns true.
if(file_exists('my-dreams-files/'.$_GET['article'].'.html'))
I have a new reason this happens - I am using PHP inside a Docker container with a mounted volume for the codebase which resides on my local host machine.
I was getting file_exists == FALSE (inside Composer autoload), but if I copied the filepath into terminal - it did exist! I tried the clearstatche(), checked safe-mode was OFF.
Then I remembered the Docker volume mapping: the absolute path on my local host machine certainly doesn't exist inside the Docker container - which is PHP's perspective on the world.
(I keep forgetting I'm using Docker, because I've made shell functions which wrap the docker run commands so nicely...)
It can also be a permission problem on one of the parent folders or the file itself.
Try to open a session as the user running your webserver and cd into it. The folder must be accessible by this user and the file must be readable.
If not, php will return that the file doesn't exist.
have you tried manual entry. also your two extensions seem to be in different case
var_dump(file_exists('../../images/example/001-001.jpg'));
var_dump(file_exists('../../images/example/001-001.PNG'));
A custom_file_exists() function inspired by #Timur, #Brian, #Doug and #Shahar previous answers:
function custom_file_exists($file_path=''){
$file_exists=false;
//clear cached results
//clearstatcache();
//trim path
$file_dir=trim(dirname($file_path));
//normalize path separator
$file_dir=str_replace('/',DIRECTORY_SEPARATOR,$file_dir).DIRECTORY_SEPARATOR;
//trim file name
$file_name=trim(basename($file_path));
//rebuild path
$file_path=$file_dir."{$file_name}";
//If you simply want to check that some file (not directory) exists,
//and concerned about performance, try is_file() instead.
//It seems like is_file() is almost 2x faster when a file exists
//and about the same when it doesn't.
$file_exists=is_file($file_path);
//$file_exists=file_exists($file_path);
return $file_exists;
}
This answer may be a bit hacky, but its been working for me -
$file = 'path/to/file.jpg';
$file = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/'.$file;
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}else{
$exists = true;
}
apparently $_SERVER['REQUEST_SCHEME'] is a bit dicey to use with IIS 7.0 + PHP 5.3 so you could probably look for a better way to add in the protocol.
I found this answer here http://php.net/manual/en/function.file-exists.php#75064
I spent the last two hours wondering what was wrong with my if statement: file_exists($file) was returning false, however I could call include($file) with no problem.
It turns out that I didn't realize that the php include_path value I had set in the .htaccess file didn't carry over to file_exists, is_file, etc.
Thus:
<?PHP
// .htaccess php_value include_path '/home/user/public_html/';
// includes lies in /home/user/public_html/includes/
//doesn't work, file_exists returns false
if ( file_exists('includes/config.php') )
{
include('includes/config.php');
}
//does work, file_exists returns true
if ( file_exists('/home/user/public_html/includes/config.php') )
{
include('includes/config.php');
}
?>
Just goes to show that "shortcuts for simplicity" like setting the include_path in .htaccess can just cause more grief in the long run.
In my case, the problem was a misconception of how file_exists() behaves with symbolic links and .. ("dotdot" or double period) parent dir references. In that regard, it differs from functions like require, include or even mkdir().
Given this directory structure:
/home/me/work/example/
www/
/var/www/example.local/
tmp/
public_html -> /home/me/work/example/www/
file_exists('/var/www/example.local/public_html/../tmp/'); would return FALSE even though the subdir exists as we see, because the function traversed up into /home/me/work/example/ which does not have that subdir.
For this reason, I have created this function:
/**
* Resolve any ".." ("dotdots" or double periods) in a given path.
*
* This is especially useful for avoiding the confusing behavior `file_exists()`
* shows with symbolic links.
*
* #param string $path
*
* #return string
*/
function resolve_dotdots( string $path ) {
if (empty($path)) {
return $path;
}
$source = array_reverse(explode(DIRECTORY_SEPARATOR, $path));
$balance = 0;
$parts = array();
// going backwards through the path, keep track of the dotdots and "work
// them off" by skipping a part. Only take over the respective part if the
// balance is at zero.
foreach ($source as $part) {
if ($part === '..') {
$balance++;
} else if ($balance > 0) {
$balance--;
} else {
array_push($parts, $part);
}
}
// special case: path begins with too many dotdots, references "outside
// knowledge".
if ($balance > 0) {
for ($i = 0; $i < $balance; $i++) {
array_push($parts, '..');
}
}
$parts = array_reverse($parts);
return implode(DIRECTORY_SEPARATOR, $parts);
}
I just encountered this same problem and I solved it in a mysterious way. After inserting a a filepath I copied from Windows File explorer. file_exists() keeps returning false continuously, but if I copy same path from VSCode editor it works perfectly.
After dumping variables with var_dump($path); I noticed something mysterious.
For path I copied from file explorer it shows length 94.
For path I copied from VSCode Editor it shows length 88.
Both path look same length on my code Editor.
My suggestion: if string contain hidden characters, it may fail and not work.