0

I have database columns attach1 and attach2. I need to show files (pdf) from those columns, but only if they exist in directory www.domain.com/uploads. Attach1 contains real file but attach2 does not.

I tried something like this:

<?php
$file = $row['attach'];
$exists = file_exists('uploads/'.$file.''); 
if ($exists) {
  echo $file;
}
if (!$exists) {
  echo 'No file1';
}      
?>

<?php
$file2 = $row['attach2'];
$exists = file_exists('uploads/'.$file2.''); 
if ($exists) {
  echo $file2;
}
if (!$exists) {
  echo 'No file2';
}      
?> 

But everytime it echoes me back, that file exists, even when attach2 contains nothing. Why?

4
  • Not to your question, but there are a number of pointless things in your code sample. You don't need to concatenate an ampty string onto the end of the filename. you don't need to save the result of file_exists in a variable. You can use else to simplify your conditionals. Commented Dec 14, 2013 at 9:38
  • Did you try to echo $file2 and make sure it's not empty? If it is, you'd be checking file_exists('/uploads'), which is of course TRUE. Commented Dec 14, 2013 at 9:41
  • try this 'if(isset($file)' Commented Dec 14, 2013 at 9:42
  • Yes I'm sure its empty. Ok if I'm checking the directory, how can I check concrete file? Commented Dec 14, 2013 at 9:43

1 Answer 1

2

If your filename is empty, then you are passing only the directory name to file_exists. Directories are files too. And I reckon the directory does actually exist. It is not lying to you.

You can either check that the filename from the database is not empty, or you can pass the whole string to the function is_dir to see if it is a directory. I assume you only want regular files.

That would look something like this:

 <?php
 $file = $row['attach'];
 $exists = file_exists('uploads/'.$file.'') && !is_dir('uploads/'.$file.''); 
 if ($exists) {
   echo $file;
 } else {
   echo 'No file1';
 }      
 ?>

I changed the if statement to use an else clause. It is equivalent to using a second if like you did.

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

2 Comments

How would I do that? Please.
Which part? is_dir?

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.