Jake
Jake

Reputation: 3486

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.

Upvotes: 1

Views: 7708

Answers (5)

KingRider
KingRider

Reputation: 2257

dirname(FILE) = "../"

dirname(dirname(FILE)) = "../../"

dirname(dirname(dirname(FILE))) = "../../../"

U can try its.

Upvotes: 0

Fabrizio D'Ammassa
Fabrizio D'Ammassa

Reputation: 4769

Assuming the "photos" folder at the same level of the class containing your code:

if (file_exists(dirname(__FILE__)."/../photos/".$this->id.".jpg") ){ 

//

}

Upvotes: 0

Pascal MARTIN
Pascal MARTIN

Reputation: 401142

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 :

Upvotes: 2

vstm
vstm

Reputation: 12537

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'))

Upvotes: 0

Jeremy Z
Jeremy Z

Reputation: 106

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") )

Upvotes: 0

Related Questions