Search code examples
phpimagecodeigniterreaddiropendir

opendir error with first two images codeigniter


i am reading from a directory which everything it looks fine. I am able to display all the data inside the folder but i have a problem, in the beginning of the list it shows 2 broken images which are not mine they have a strange path it looks like is generated it self, here is the strange path in the source file:

(Resource id #33< ul >< li >< a href="#">< img src="img/test/.">< / a>< / li>< li>< a href="#" >< img src="img/test/..">< /a> )

The code continue normally as it should reading the images inside the folder after these two lines.

And here is the code i am using:

class HomeModel extends CI_Model{

public function getData(){

$dir = 'img/test';

echo opendir($dir);

if (is_dir($dir)) {

    if ($dh = opendir($dir)) {

     $display_models = '<ul>';

        while (($file = readdir($dh)) !== false) {

    $display_models .= '<li><a href="#"><img src="'.$dir.'/'.$file.'"></a></li>';

        }

    $display_models .= '</ul>';

        closedir($dh);

    }

      return $display_models;
}

}

}

Solution

  • hi add one if condition to check . and .. like this

    while (($file = readdir($dh)) !== false) {
        if($file != '.' && $file != '..'){
            $display_models .= '<li><a href="#"><img src="'.$dir.'/'.$file.'"></a></li>';
         }
    
    }
    

    check this tutorial can also help you scanning folder with php