PHP images from directory - Random order - php

I have a page of my website which I use to store reference images..
Currently I just drop all of the images into a directory on my server and the php displays them how I like.
What i'd like to ask is how to I get them to display in a different random order every time the page is refreshed?
code is below:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}

To guarantee that the order is different every time requires that you carry the data about the order in which they were displayed between page loads. However, this is not necessarily what you require - if you simply randomise the order every time then the higher the number of images in the directory the lower the chance you will get the same order twice.
You can simply use shuffle() to randomise the order of the array:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}

Look at shuffle function. http://php.net/manual/en/function.shuffle.php Since PHP is stateless, you'll either rescan your directory each time or assign the $dir_contents to a session variable. Then you could simple shuffle the session variable.
if ($file !== '.' && $file !== '..' && in_array($file_type, suffle($file_display)) == true) {
Try that.

Use php shuffle to the array of images created by scandir
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
if(shuffle($dir_contents)) {
foreach ($dir_contents as $file) {
$info = new SplFileInfo($file);
// scandir returns an array of files and,or directories
// so we should check if $file is a file
// and that it's extension matches the allowed ones
// which are ('jpg', 'jpeg', 'png', 'gif')
if(is_file($file) && in_array($info->getExtension(),$file_display)) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
} else {
echo 'Error applying random order!';
}
}

Please, follow this instruction: create a folder "php" into root of your website and put inside the following php file rotate.php... now create a folder "pic" and "xmas" into your root... you can chose the folder name or other things by editing the var $my_folder_holiday and $my_folder_default...
<?php
##########################################################
# Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
# Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
##########################################################
function rotate($folder) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
$list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
$fileList = array();
$img = '';
foreach ($list as $file) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file"))) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
$fileList[] = $file;
}
}
}
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder . '/' . $fileList[$imageNumber];
}
return $img;
} else {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
}
}
$my_gallery_month = date('m');
$my_folder_default = 'pic';
$my_folder_holiday = 'xmas';
if ($my_gallery_month == 12) {
$my_gallery = rotate($my_folder_holiday);
} else {
$my_gallery = rotate($my_folder_default);
}
?>
The usage is very easy and works very well under PHP 7.4... if you have in the root of your website a folder "pic" and "xmas" containing your images, please, put into your index.php (or other file php located in the root):
<img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67">
This is another usage using FancyBox library:
Hope this helps...

Related

Display images present on server using PHP

I need to display images on web page from the folder present on server.
I tried this:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
It didn't work, so I made some changes and tried this:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \''. $dir. '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file))); \\ERROR
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="'. $dir. '/'. $file. '" alt="'. $file. '" />';
}
}
}
But there was an error "only variables should be passed by reference", so I tried:
$dir = 'images';
$file_display = array ('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) ==false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
$tmp = explode('.', $file); \\CHANGED THIS LINE
$file_type = end($tmp); \\CHANGED THIS LINE
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img class="photo" src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
Any ideas how to display images present on server using PHP dynamically?
In one of my projects I used RecursiveDirectoryIterator and RegexIterator that will take care on multiple folders inside images directory and create a array of valid files(that matches the regular expression, in our case files with extension jpg|jpeg|png|gif)
<?php
$folder = 'images';
try {
$directory = new RecursiveDirectoryIterator(realpath($folder));
$iterator = new RecursiveIteratorIterator($directory);
$files = new RegexIterator($iterator, '/^.+\.(jpg|jpeg|png|gif)$/i', RecursiveRegexIterator::GET_MATCH);
} catch (Exception $e) {
echo "Invalid Directory: ".$e->getMessage();
}
//$files is an array with file name of all the valid images
if(isset($files) && $files != null){
foreach($files as $filepath => $value){
echo "<img src='".$filepath."'><br>";
}
}
?>
Hope this helps

How can I sort my image - the latest on top

I found on YT a php code to display images from directory.
Everything works perfect, but I need to display the latest photos on the top.
Can anyone help me?
<?php
$dir = 'foto';
$file_display = array('jpg', 'jpeg');
if (file_exists($dir) == false) {
echo 'Gallery \'', $dir, '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower (end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<div id="', $file, '"><img src="', $dir, '/', $file, '" alt="', $file, '" /></div>';
}
}
}
?>
Less code:
array_multisort((
array_map(
'filemtime', ($files = glob(
"$dir/*.{jpg,jpeg}", GLOB_BRACE)))), SORT_DESC, $files);
Glob for the specific files and store in $files
Get the file modification time for each and sort $files on the times
foreach on $files and display.
I think you will need to sort images by date. Someone has written another variant of scandir() function here: https://stackoverflow.com/a/11923516/1644017
You can get that function and change $dir_contents = scandir($dir); to: $dir_contents = scan_dir($dir); in your code.

How to display images from a folder using php - PHP

It would be great if someone could help me figure out why the browser cannot load the images (error 404). The code works, and the image source is correct, but I cannot figure out what is wrong. (using localhost)
$dir = '/home/user/Pictures';
$file_display = array(
'jpg',
'jpeg',
'png',
'gif'
);
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir($dir);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
You had a mistake on the statement below. Use . not ,
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
to
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
and
echo 'Directory \'', $dir, '\' not found!';
to
echo 'Directory \''. $dir. '\' not found!';
Here is a possible solution the solution #3 on my comments to blubill's answer:
yourscript.php
========================
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if (file_exists($dir) == false)
{
echo 'Directory "', $dir, '" not found!';
}
else
{
$dir_contents = scandir($dir);
foreach ($dir_contents as $file)
{
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)
{
$name = basename($file);
echo "<img src='img.php?name={$name}' />";
}
}
}
?>
img.php
========================
<?php
$name = $_GET['name'];
$mimes = array
(
'jpg' => 'image/jpg',
'jpeg' => 'image/jpg',
'gif' => 'image/gif',
'png' => 'image/png'
);
$ext = strtolower(end(explode('.', $name)));
$file = '/home/users/Pictures/'.$name;
header('content-type: '. $mimes[$ext]);
header('content-disposition: inline; filename="'.$name.'";');
readfile($file);
?>
You have two ways to do that:
METHOD 1. The secure way.
Put the images on /www/htdocs/
<?php
$www_root = 'http://localhost/images';
$dir = '/var/www/images';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
break;
}
}
}
?>
METHOD 2. Unsecure but more flexible.
Put the images on any directory (apache must have permission to read the file).
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
break;
}
}
}
?>
And create another script to read the image file.
<?php
$filename = base64_decode($_GET['file']);
// Check the folder location to avoid exploit
if (dirname($filename) == '/home/user/Pictures')
echo file_get_contents($filename);
?>

Get files from a directory in random order using php (xampp)

i'm building a wordpress theme and i'm trying to get the all the jpg files from a directory in random order using php....
im using Xampp on win7 (localhost).
this is the code:
<?
$dir = get_template_directory_uri().'/images/top/';
$file_display = array ('jpg', 'jpeg');
if(file_exists($dir) == false){
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true){
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
?>
i always get
Directory 'http://localhost/ni/wp-content/themes/A/images/top/' not found
i also tried to change
$dir = get_template_directory_uri().'/images/top/';
to:
$dir = "C:\xampp\htdocs\Ni\wp-content\themes\A\images\top\";
but still no luck, any help would be appreciated!
This is how i made it work.
<?
$dir = get_template_directory().'/images/top';
$imageDir= get_template_directory_uri().'/images/top';
$file_display = array ('jpg', 'jpeg');
if (file_exists($dir) == false) {
echo 'Directory \'', $dir, '\' not found';
} else {
$dir_contents = scandir($dir);
shuffle($dir_contents);
foreach ($dir_contents as $file) {
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true) {
echo '<img src="', $imageDir, '/', $file, '" />';
}
}
}
?>

How to get random image from directory using PHP

I have one directory called images/tips.
Now in that directory I have many images which can change.
I want the PHP script to read the directory, to find the images, and out of those images found to pick a random image.
Any idea on how to do this?
$imagesDir = 'images/tips/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)]; // See comments
You can send a 2nd argument to array_rand() to get more than 1.
$images = glob('images/tips/*');
return $images[rand(0, count($images) - 1)];
However, this doesn't ensure that the same image isn't picked twice consecutively.
<?php
foreach (glob("gallery/*") as $filename) {
echo '<li><img src="'.$filename.'" alt="" /> </li>';
}
?>
Look at this code, use it definitely if useful for you. It loads all files from folder and prints them in above format. I made this code to use with lightbox.
function get_rand_img($dir)
{
$arr = array();
$list = scandir($dir);
foreach($list as $file)
{
if(!isset($img))
{
$img = '';
}
if(is_file($dir . '/' . $file))
{
$ext = end(explode('.', $file));
if($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png' || $ext == 'GIF' || $ext == 'JPEG' || $ext == 'JPG' || $ext == 'PNG')
{
array_push($arr, $file);
$img = $file;
}
}
}
if($img != '')
{
$img = array_rand($arr);
$img = $arr[$img];
}
$img = str_replace("'", "\'", $img);
$img = str_replace(" ", "%20", $img);
return $img;
}
echo get_rand_img('images');
replace 'images' with your folder.
Agreed with alexa.
Use simple function.
function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$randomImage = $images[array_rand($images)];
return $randomImage;
}
$the_image = RandImg('images/tips/');
echo $the_image;
$folder = "images";
$results_img_arr = array();
if (is_dir($folder))
{
if ($handle = opendir($folder))
{
while(($file = readdir($handle)) !== FALSE)
{
if(!in_array($file,array(".","..")))
$results_img_arr[] = $folder."/".$file;
}
closedir($handle);
}
}
$ran_img_key = array_rand($results_img_arr);
$img_path = $results_img_arr[$ran_img_key];
You can use opendir() to read in the filenames from that directory, storing each filename in an array. Then use rand() with a min and max corresponding to your array keys to select an item from the array.
Simpler:
$directory = "medias/photos/";
$img = glob($directory . "*.jpg");
shuffle($img);
I wrote a simple php script for my personal use. Now I want share it with stackoverflow's community. Usage is simple: create a folder "php" into root of your Web Server and put inside this file php rotate.php... now create two folders into your root called "pic" and "xmas"... you can adjust the folder names by editing the var $my_folder_holiday and $my_folder_default...
<?php
##########################################################
# Simple Script Random Images Rotator • 1.4 • 04.01.2020 #
# Alessandro Marinuzzi [alecos] • https://www.alecos.it/ #
##########################################################
function rotate($folder) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder")) && (is_dir($_SERVER['DOCUMENT_ROOT'] . "/$folder"))) {
$list = scandir($_SERVER['DOCUMENT_ROOT'] . "/$folder");
$fileList = array();
$img = '';
foreach ($list as $file) {
if ((file_exists($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file")) && (is_file($_SERVER['DOCUMENT_ROOT'] . "/$folder/$file"))) {
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png') {
$fileList[] = $file;
}
}
}
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder . '/' . $fileList[$imageNumber];
}
return $img;
} else {
mkdir($_SERVER['DOCUMENT_ROOT'] . "/$folder", 0755, true);
}
}
$my_gallery_month = date('m');
$my_folder_default = 'pic';
$my_folder_holiday = 'xmas';
if ($my_gallery_month == 12) {
$my_gallery = rotate($my_folder_holiday);
} else {
$my_gallery = rotate($my_folder_default);
}
?>
This script was tested under PHP 7.0/7.1/7.2/7.3 and PHP 7.4 and works fine. Usage (for example in root you may have a folder "pic" and "xmas" containing your images):
<img src="/<?php echo $my_gallery; ?>" alt="Random Gallery" width="90" height="67">
Other usage using FancyBox library:
Hope this Helps.
Load folder with images:
$folder = opendir(images/tips/);
Build table out of files/images from directory:
$i = 0;
while(false !=($file = readdir($folder))){
if($file != "." && $file != ".."){
$images[$i]= $file;
$i++;
}
}
Pick random:
$random_img=rand(0,count($images)-1);
Show on page:
echo '<img src="images/tips'.$images[$random_img].'" alt="" />';
Hope it helps. Of course enclose it in <?php ?>.

Categories