1

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.

1
  • i have this structure: /classes/class.php and /photos Commented Jul 23, 2011 at 16:23

5 Answers 5

2

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 :

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

How do I find out this path? Thanks
Just log into your server via ssh or ftp, traverse to the webroot and that is where your path should start. So if your webroot is "public_html" (common among most hosts), your path would begin with a / to dictate that you are starting from the root directory. So it would be /public_html/another_directory/etc/photos/
0

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

Comments

0

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

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

//

}

1 Comment

i have this structure: /classes/class.php and /photos
0

dirname(FILE) = "../"

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

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

U can try its.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.