Printable Version of Topic

Click here to view this topic in its original format

Forums _ Webmasters' Corner Resolved Topics _ PHP List all files in directory

Posted by: Mikeplyts Aug 28 2010, 10:51 AM

I was working on a little file upload thing for a website and I'm pretty much done. However, I have a page where I list all files based on the current user. My current script works fine, but it only lists the most recent file uploaded. I'd rather have a full list of all files in the directory instead of the most recent one.

Here's my current script:

CODE
<?php
$directory = $user;
if (!is_dir($directory)) {
mkdir($directory);
$list = '<tr>
<td>No files to display.</td>
</tr>';
}

else {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$name = ucfirst($file);
$list = '<tr>
<td>' . $name . '</td>
<td><a href="/files/' . $directory . '/?delete=' . $file . '" class="delete">Delete this file</a> <a href="/files/' . $directory . '/?open=' . $file . '">Open this file</a></td>
</tr>';
}

else {
$list = '<tr>
<td>No files to display.</td>
</tr>';
}
}
closedir($handle);
}

echo $list;
}
?>


It works exactly like I want it to when it comes to listing, but I want to make it so it lists all files as opposed to one. Oh, and, $user is just variable I defined in another script that contains the current user's username.

Hilfe?

Posted by: ahmad Aug 28 2010, 06:38 PM

CODE
while (false !== ($file = readdir($handle))) {
if ($file != '.' && $file != '..') {
$name = ucfirst($file);
$list = '<tr>
<td>' . $name . '</td>
<td><a href="/files/' . $directory . '/?delete=' . $file . '" class="delete">Delete this file</a> <a href="/files/' . $directory . '/?open=' . $file . '">Open this file</a></td>
</tr>';

}

else {
$list = '<tr>
<td>No files to display.</td>
</tr>';
}
}


IF you look at this part of your code is where your error lies. The WHILE LOOP iterate over the $file which is an array... and you are store the data in a variable which is not an array $list, so it just keeps overwriting the file name with a new one every time.

CODE
<?php
$directory = $user;

$list = array();

if (!is_dir($directory)) {
mkdir($directory);
$list = '<tr>
<td>No files to display.</td>
</tr>';
}

else {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if( $file != "." && $file != ".." )
$list[] .= $file;
}
}
else {
$list = '<tr>
<td>No files to display.</td>
</tr>';
}
}
closedir($handle);


foreach ( $list as $key => $val )
{
echo "<tr><td> {$val} </td></tr>";
}
?>

Posted by: Mikeplyts Aug 29 2010, 05:19 AM

Oh, okay. Thanks man, worked great!

Posted by: manny-the-dino Aug 30 2010, 04:06 PM

Topic Closed and Moved