Search code examples
phpopendir

opendir not working for files or folders with spaced in the name


i have a chunk of code that i am using and it is working fine, the only problem is then when a folder or file name has a space in it, it only links to (or displays) the first word in the file name

please help,

thanks

<?php
$dirFiles = array();
// opens images folder
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {

        // strips files extensions      
        $crap   = array(".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF", ".bmp", ".BMP", "_", "-", "error_log", ".php");    

        $newstring = str_replace($crap, " ", $file );   

        //asort($file, SORT_NUMERIC); - doesnt work :(

        // hides folders, writes out ul of images and thumbnails from two folders

        if ($file != "." && $file != ".." && $file != "index.php" && $file != "Thumbnails") {
            $dirFiles[] = $file;
        }
    }
    closedir($handle);
}

sort($dirFiles);
foreach($dirFiles as $file)
{
    echo "<li>";
    echo "<a href=".$file.">".$file."<br></li>";
}

?>

Solution

  • You have a quotes issue. You're missing quotes around your href attribute:

    echo "<a href=".$file.">".$file."<br></li>";
    

    should be

    echo '<a href="'.$file.'">'.$file.'<br></li>';