I’m using file_exists() in a class and I want to use it on the root as well as when included in another folder to see if a file exists.
I currently have:
if (file_exists("./photos/".$this->id.".jpg") ){
//
}
It works when included in the root but not when included in a folder (for ajax).
What can I do to make it direct (I think thats the correct word)? I am unable to put my site URL into it because of the nature of the function.
The easiest way is to use an absolute (full) path :
This way, no matter from where your script is executed, the full path, that will never change, will always work.
Of course, you probably don’t want to hard-code the full path into your PHP script…
So you can use
dirname(__FILE__)to get the full path to the directory which contains the file into which you wrote thatdirname(__FILE__), and, from there, go with a relative one.For example :
(while testing this, you might want to display the value of
$path, first, to make sure you got the path right)Note : if you are working with PHP >= 5.3, you can use
__DIR__instead ofdirname(__FILE__).Relevant manual pages :
dirname()Magic constants, including__DIR__and__FILE__.