php direct path file_exists()
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 :
if (file_exists("/full/path/to/photos/".$this->id.".jpg") ){
//
}
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 that dirname(__FILE__)
, and, from there, go with a relative one.
For example :
$path = dirname(__FILE__) . '/../../files/photos/'.$this->id.".jpg";
if (file_exists($path)) {
//
}
(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 of dirname(__FILE__)
.
Relevant manual pages :
dirname()
Magic constants
, including__DIR__
and__FILE__
.
It sounds like you just need to put the full path from the root directory into the code.
if (file_exists("/root_dir/path/to/photos/".$this->id.".jpg") )
It's more or less common to use dirname(__FILE__)
to get the path of the php file itself regardless of whether it is called directly or included . So in your situation you could write:
if(file_exists(dirname(__FILE__) . '/photos/'.$this->id.'.jpg'))
Assuming the "photos" folder at the same level of the class containing your code:
if (file_exists(dirname(__FILE__)."/../photos/".$this->id.".jpg") ){
//
}
dirname(FILE) = "../"
dirname(dirname(FILE)) = "../../"
dirname(dirname(dirname(FILE))) = "../../../"
U can try its.
精彩评论