Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top