Search code examples
phpreaddir

Why is $count not updating?


   $dir_handle = @opendir($url) or die("Unable to open $url");
   $count = "0";
   while ($file = readdir($dir_handle)) {
      if (!is_dir($url.'/'.$file) && ($file="*.jpg" || $file="*.gif" || $file="*.png") && $file!="picture0.*") {
         $galleryEventFile[$count] = $file;
         $count++;
      }
   }
   closedir($dir_handle);

I think it has something to do with this line:

if (!is_dir($url.'/'.$file) && ($file="*.jpg" || $file="*.gif" || $file="*.png") && $file!="picture0.*")

but im not sure


Solution

  • I can see two things that will be causing you problems:

    Assignment/comparison:

    You have the code:

    if ($file="*.jpg" //etc...
    

    However, a single equal sign will perform an assignment, not a comparison - you need to use two equals signs (==) for this. See http://php.net/manual/en/language.operators.comparison.php. Essentially what you are doing by doing an assignment in an if statement is:

    $file = '*.jpg';
    if ($file) { } 
    

    Wildcard matching of strings

    You also can't do wildcard matching like that ($file == "*.jpg) on a string, you could look at using preg_match() and regular expressions instead, e.g.

    if (!preg_match('/\.jpg$/i', $file)) {
        //not .jpg
    }
    

    It might be better to do something like this though:

    //get file extension
    $extension = pathinfo($file, PATHINFO_EXTENSION);
    
    $allowedExtensions = array('jpg', 'png', 'gif');
    
    //check in allowed list
    if (!in_array(strtolower($extension), $allowedExtensions)) {
        //not valid
    }