vendredi 9 février 2018

Read files from a local folder and asign a video or img tag with php

Im trying to read some files from a local folder and make an array with it. Then I need to asign to every file an "img" or "video" tag according to the file. To read the files from the folder and make an array Im using this working code:

<?php
   $dir = 'video/';
   $dh  = opendir($dir);
    while (false !== ($fileName = readdir($dh))) {
       $ext = substr($fileName, strrpos($fileName, '.') + 1);
       if(in_array($ext, array("jpg","jpeg","png","gif","mp4")))
          $files1[] = $fileName;
   }
?>

The problem starts with the next step. I'm using "foreach" and "if" but is not working:

            <?php
            foreach($files1 as $fileName) 
            {
               if ($ext == "jpg") 
                 { ?>
                   <img  src="video/<?php echo $fileName; ?>"/>
                  <?php } 
               else if ($ext =="mp4")
                { ?>
                  <video><source src="video/<?php echo $fileName; ?>"></video>  
             <?php }
             }
            ?>

When I run this code, it tag all the files (including the mp4 files) with the "img" tag.

What Am i doing wrong?

Thanks!

Hector

Aucun commentaire:

Enregistrer un commentaire