3

Im trying to verify if file exists in directory. When I use this code it works - image is displayed:

<?php 

  $imgId=0; 
  $filename='../uploadedimages/project-'.$item->id.'-'.$imgId;

  echo "<img src='".$filename."' ></img>";

?>  

When I use the same code with file_exists function, it doesn't work:

<?php 

  $imgId=0; 
  $filename='../uploadedimages/project-'.$item->id.'-'.$imgId;

  if (file_exists($filename)) {                             
    echo "<img src='".$filename."' ></img>";                
  }

?>  

My question is simple: WTF??

9
  • 1
    Your documentroot is not the same as the server documentroot... So file_exists() uses the folder where the script resides in as the reference directory. Loading the <img> takes it referenced from the root of your webserver. Commented Dec 3, 2014 at 14:52
  • 4
    file_exists expects the filesystem path. Commented Dec 3, 2014 at 14:52
  • 1
    Sidenote: </img> you don't need that. Commented Dec 3, 2014 at 14:53
  • Also relative path's are a pain to calculate for a server Commented Dec 3, 2014 at 14:53
  • Read the "WTF" manual php.net/manual/en/function.file-exists.php ;) $filename='/var/user/you/httpdocs/uploadedimages/project... Commented Dec 3, 2014 at 14:54

2 Answers 2

2

You can use: $_SERVER['DOCUMENT_ROOT'] to know where you are.

And then try something like this:

$filename=$_SERVER['DOCUMENT_ROOT'].'uploadedimages/project-'.$item->id.'-'.$imgId;

But first you need to make sure the path exist.

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

Comments

0

on linux server, try to change file access permission to 755 before using file_exists function

chmod 755 filename.ext

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.