Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php get jpg file from a folder as array

Tags:

php

random

help me to get files from a folder in array. I am trying to get all jpg file name in array from a folder images. and after that use rand to change css background Randomly.

JPG files from a folder in arry;

$images=array("image1.jpg", "image2.jpg");

then use the rand to load images randomly

echo '<style>body{background:url('.$images[array_rand($images)].')no-repeat;';

1 Answers

Pass a directory to scandir to get an array of all files in that directory. Maybe use array_filter then to filter out any non-images by file extension.

    $files = scandir( '/image/path' );

    function images_only( $file )
    {
      return preg_match( '/\.(gif|jpg|png)$/i', $file );
    }

    $files = array_filter( $files, 'images_only' );

$files should now contain only the images from the image path.

like image 111
Poe Avatar answered Feb 01 '26 03:02

Poe