I have the following code in my PHP file – initializes $uploaded_files variable and then calls getDirectory (also listed below).
Now if I do a vardump($uploaded_files) I see the contents of my variable, but for some reason when I call <?php echo $uploaded_files; ?> in my HTML file I get a message stating “No Files Found” – am I doing something incorrect?
Can someone assist? Thank you.
/** LIST UPLOADED FILES **/
$uploaded_files = "";
getDirectory( Settings::$uploadFolder );
// Check if the uploaded_files variable is empty
if(strlen($uploaded_files) == 0)
{
$uploaded_files = "<li><em>No files found</em></li>";
}
getDirectory Function:
function getDirectory( $path = '.', $level = 0 )
{
// Directories to ignore when listing output. Many hosts
// will deny PHP access to the cgi-bin.
$ignore = array( 'cgi-bin', '.', '..' );
// Open the directory to the handle $dh
$dh = @opendir( $path );
// Loop through the directory
while( false !== ( $file = readdir( $dh ) ) ){
// Check that this file is not to be ignored
if( !in_array( $file, $ignore ) ){
// Its a directory, so we need to keep reading down...
if( is_dir( "$path/$file" ) ){
// We are now inside a directory
// Re-call this same function but on a new directory.
// this is what makes function recursive.
getDirectory( "$path/$file", ($level+1) );
}
else {
// Just print out the filename
// echo "$file<br />";
$singleSlashPath = str_replace("uploads//", "uploads/", $path);
if ($path == "uploads/") {
$filename = "$path$file";
}
else $filename = "$singleSlashPath/$file";
$parts = explode("_", $file);
$size = formatBytes(filesize($filename));
$added = date("m/d/Y", $parts[0]);
$origName = $parts[1];
$filetype = getFileType(substr($file, strlen($file) - 4));
$uploaded_files .= "<li class=\"$filetype\"><a href=\"$filename\">$origName</a> $size - $added</li>\n";
// var_dump($uploaded_files);
}
}
}
// Close the directory handle
closedir( $dh );
}
You either need to add:
At the top of your getDirectory function, or
Pass it by reference.
You could also make $uploaded_files the return value of getDirectory.
More reading about globals and security: http://php.net/manual/en/security.globals.php