check if files exists and provides a link to it php

1.7k views Asked by At

I want to check if a directory contains a specific file(any type, image, pdf etc.) or not. If it contains the file, I want to provide a download link for this file, otherwise print "not exist". Unfortunately, my code is printing not exist all the time even if the file exists in the directory. Here is my code:

                <td>  <?php

if (file_exists('plans/'.$RID)) {
  echo"<a href='plans/$RID'>Plan</a>";
} else {
    echo "not exists";
}
?>  </td>

here is another code I also tried it but doesn't work:

<td>  <?php
    $plan= 'plans/'.$RID;
    if (file_exists($plan)) {
      echo"<a href='plans/$RID'>Plan</a>";
    } else {
        echo "not exists";
    }
    ?>  </td>
3

There are 3 answers

4
Alexandre Tranchant On

Provide an absolute path as parameter of your function :

If your script path is parent of plans directory, parameter could be __DIR__ . '/plans' for example.

edit : To catch file with some extensions, you can create an array containing allowed extensions.

<td><?php
$extensionsAllowed = ['jpg','pdf','png']; //complete it
foreach ($extensionsAllowed as $extension){    
    if (file_exists( __DIR__ . 'plans/'.$RID.'.'.$extension)) {
      echo '<a href="plans/'.$RID.'.'.$extension.'" download>Plan</a>';
    } else {
      echo "not exists";
    }
?>  </td>
0
Abhishek Gurjar On

If plans is directory where you have your php file which is used for checking file then there is no need to put plans in file_exists alongside your filename

<td>  
<?php

if (file_exists($RID)) {
      echo"<a href='plans/$RID'>Plan</a>";
    } else {
        echo "not exists";
    }
?>

</td>

Otherwise you can do it like this,

<?php

$Path = $_SERVER['DOCUMENT_ROOT'].'/plans/'.$RID;

if (file_exists($Path)) {
      echo"<a href='plans/$RID'>Plan</a>";
    } else {
        echo "not exists";
    }
?>

</td>
0
dhruv jadia On

change from

<td>  
<?php

if (file_exists('plans/'.$RID)) {
  echo"<a href='plans/$RID'>Plan</a>";
} else {
    echo "not exists";
}
?>  
</td>

to

<td>  
<?php

if (!file_exists('plans/'.$RID)) {
   mkdir('plans/'.$RID, 0777, true);
   echo"<a href='plans/$RID'>Plan</a>";  
}
?>  
</td>