Home > Back-end >  PHP display image or video
PHP display image or video

Time:03-14

I have this code that sort files by date and create pagination. It works well with images, but when file is a video,〈img〉tag don't work with it of course. How to modify this code to display file in〈video〉tag when file is a video or〈img〉when file is an image?

 <?php 
        
        $limit = 10;
        $adjacents = 3;
        $targetpage = 'index.php';
        $allImages = [];
          
          function mtimecmp($a, $b) {
                $mt_a = filemtime($a);
                $mt_b = filemtime($b);
        
                if ($mt_a == $mt_b)
                    return 0;
                else if ($mt_a > $mt_b)
                    return -1;
                else
                    return 1;
            }
        
            $images = glob($dirname."uploads/*.*");
              usort($images, "mtimecmp");
        
            for ($i = count($images) - 1; $i >= 0; $i--) {
                $image = $images[$i];
                 }
        
            {
              array_push($images);
            }
          
        
        $total_pages = count($images);
         
        $page = isset($_GET['page']) ? $_GET['page'] : 1;
         
        $start = $page ?  (($page - 1) * $limit) : 0;
         
         
        $images = array_slice( $images, $start, $limit );;
         
(code for pagination)
        ?>


    

Display pictures on page:

<?php
if(count($images) > 0) {
  foreach($images as $image) {
     ?>
  <img src="<?php echo $image; ?>">
<?php }
} else {
  echo 'No images';
}
 
 
echo $pagination;
?>

CodePudding user response:

you just need to add this

<video controls>
   <source src="file_path.mp4" type="video/mp4">
</video>

so it will be some think like this

<?php
if(count($videos) > 0) {
  foreach($videos as $video) {
     ?>
    <video controls>
      <source src="<?php echo $video; ?>" type="video/mp4">
    </video>
<?php }
} else {
  echo 'No videos';
}
 
 
echo $pagination;
?>

CodePudding user response:

I edited the code and it works:

foreach($images as $image) {
         $ext = pathinfo($image, PATHINFO_EXTENSION);
    
       if ($ext == "mp4") {
         ?>
      <video width="320" height="240" controls>
      <source src="<?php echo $image; ?>" type="video/mp4">
    </video> <?php
    }
        if ($ext == "jpg" || $ext == "png") {
         ?>
      <div ><img src="<?php echo $image; ?>"></div> <?php
    } }
        
     ?>
  • Related