GEEkSpoTTed GEEkSpoTTed - 3 months ago 8
PHP Question

How to view all the files in a directory using PHP?

I am making a website and i want to get the file names (file can b of any type).I want 2 display them in a table .Just show me the code to display the name of the file on the server in a table!
I want to display the contents of a directory that is server's side

Note - forget the date column (i know date should have been there ignore )

CODE



PHP


$dir = './files';
$files1 = scandir($dir);
$files2 = scandir($dir, 1);
echo '<br>';
print_r($files1);
echo '<br>';
echo '<br> &copy';
print_r($files2);

?>


HTML

<div id="uploadsdiv" >
<table id =uploads>
<tr id="tbchnggreem">
<th class="th">File Name</th>
<th class="th">Date</th>
</tr>
<tr class="tbhovchngcol">
<td class="td">Peter</td>
<td class="td">Griffin</td>
</tr>
<tr class="tbhovchngcol">
<td class="td">Lois</td>
<td class="td">Griffin</td>
</tr>
<?php if (count($files1) > 0): ?>
<tr class="tbhovchngcol">
<td class="td"><?php echo $files1 ?></td>
</tr>
<?php endif; ?>
</table>

</div>


Not necessary but take this CSS

CSS

#uploads {
border-collapse: collapse;
border-left: 1px solid black;
border-right: 1px solid black;
border-bottom: 1px solid black;
width:100%;
max-height:500px;
}

.tbhovchngcol:hover
{
background-color: #cbf7ff
}

.tbhovchngcol
{
border-bottom: 1px solid #ddd;
padding: 8px;
text-align: left;
}
.th
{
padding: 8px;
text-align: left;
}

.td
{
padding: 8px;
text-align: left;
}
#tbchnggreem {
background-color: #4CAF50;
color: white;
}

#uploadsdiv
{
overflow-x:auto;
-ms-overflow-y:auto;
overflow-y:auto;
-ms-overflow-x:auto;
}


MY ERROR

The folder files contains 3-4 img files .
When i should refresh the page i should b seeing the name of the files in the table along with the css effects applied 2 them.

$files shous this


Array ( [0] => . [1] => .. [2] => 1.jpg [3] => 2.jpg [4] => 3.jpg [5]
=> 6.jpg [6] => rt.jpg )


this array also contains . and .. in it,n i don't want 2 show them in the table
i want the file names below the name column (below Lois if u run the code)

But i see only this error


Notice: Array to string conversion in
C:\xamppNEW\htdocs\HelloWorld\NewUser\user1.php on line 118 Array

Answer

Correct Code ==

<?php

$dir    = './files';
$files1 = scandir($dir);

?>

<div id="uploadsdiv" >
<table id =uploads>
<tr id="tbchnggreem">
    <th class="th">File Name</th>
    <th class="th">Date</th>
</tr>
<tr class="tbhovchngcol">
    <td class="td">Peter</td>
    <td class="td">Griffin</td>
</tr>
    <tr class="tbhovchngcol">
    <td class="td">Lois</td>
    <td class="td">Griffin</td>
</tr>


        <?php for($i=2;$i<count($files1);$i++)
        {  ?>

        <tr class="tbhovchngcol">
        <td class="td"><?php echo $files1[$i] ?></td>
        <td class="td"><?php    echo "Last modified: ".date("d F Y",filemtime("./files/".$files1[$i])); ?></td>
        </tr>


        <?php } ?>


  </table>

   </div>
Comments