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>
Provide an absolute path as parameter of your function :
If your script path is parent of plans directory, parameter could be __DIR__ . '/plans'
__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>
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>
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.