I want to get picture from few sub-folder in a directory and i want to sort them as data. with the Following code I got the images now i want to sort them as data.
Note
every image name starts with the date and time of uploading example :-
default image name = "image.jpg"
after upload image name = "24-02-2016-09-42-33-image.jpg"
<?php
$dir = 'dist/userdata/'.$username.'/photos/';
if ($opendir = opendir ($dir) ) {
$files = 0;
while (($file = readdir ($opendir)) !== false && $files <= 2 + 1 ) {
if ($file !="." && $file !="..") {
$newdir = $dir.''.$file.'/';
if ($newopendir = opendir ($newdir)) {
$imgs = 0;
while (($img = readdir ($newopendir)) !== false && $imgs <= 3 + 1) {
if ($img !=="." && $img !=="..") {
$supported_files = array(
'jpeg',
'jpg',
'png'
);
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
if (in_array($ext, $supported_files)) {
echo '<img src="'.$newdir.''.$img.'"/>';
} else {
}
}
$imgs++;
}
}
}
$files++;
}
}
?>
Instead of echoing images imidiatelly, gather them into array.
After that you can easily sort them with usort()
Also - you are not closing handles after opening them.
And, probably RecursiveDirectoryIterator would be better fit for this than nested whiles.
Related
Im trying to select random image from random directory. I make function to get random directory and another function to get random image from that directory. Okay, but its not working, its getting random directory and random image from another directory
<?php
function showRandomDir()
{
$files = glob('images/portfolio/*/', GLOB_ONLYDIR);
shuffle($files);
$files = array_slice($files, 0, 1);
foreach($files as $file)
{
return $file;
}
}
function rotate2()
{
$list = scandir(showRandomDir());
$fileRotateList = array();
$img = '';
foreach($list as $fileRotate)
{
if (is_file(showRandomDir() . htmlspecialchars($fileRotate)))
{
$ext = strtolower(pathinfo($fileRotate, PATHINFO_EXTENSION));
if ($ext == 'gif' || $ext == 'jpeg' || $ext == 'jpg' || $ext == 'png')
{
$fileRotateList[] = $fileRotate;
}
}
}
if (count($fileRotateList) > 0)
{
$imageNumber = time() % count($fileRotateList);
$img = showRandomDir() . urlencode($fileRotateList[$imageNumber]);
}
return $img;
}
At the beginning of your rotate2() function, you call showRandomDir() to get the contents of a random directory:
$list = scandir(showRandomDir());
But then at the end, you call showRandomDir() again, so you get a different random directory.
(Well, a new one, that's probably different, but could randomly be the same.)
$img = showRandomDir() . urlencode($fileRotateList[$imageNumber]);
You need to save the first call into a variable instead, and reuse that variable instead of calling showRandomDir() a second time.
$dir = showRandomDir();
$list = scandir($dir);
// ... the rest of the code in between
$img = $dir . urlencode($fileRotateList[$imageNumber]);
i have two folder.i always print mp3 folder file name but if image folder have same named file as mp3 file then print both name or no same name then print null.
format like
mp3/
image/
mp3 image
1 = 1
2 = 2
3 = null
i am trying but not success
$path = "mp3/";
$ipath = "image/";
if ($handle = opendir($path) && $ihandle = opendir($ipath))
{
while (false !== ($file = readdir($handle)) && false !==($ifile = readdir($ihandle)))
{
if ('.' === $file && $ifile) continue;
if ('..' === $file && $ifile) continue;
//var_dump($file);
// do something with the file
for($i = 1; $i <= count($file); $i++)
{
$f=current(explode(".", $file));
$f1=current(explode(".", $ifile));
if($f==$f1)
{
print''.$f.'='.$f1.'';
}
else
{
print''.$f.'='null';
}
}
}
closedir($handle);
closedir($ihandle);
}
I am wondering about a "better" way of pulling a random image from a folder.
Like say, to have php just select a random image from folder instead of searching and creating an array of it.
here is how I do it today
<?php
$extensions = array('jpg','jpeg');
$images_folder_path = ROOT.'/web/files/Header/';
$images = array();
srand((float) microtime() * 10000000);
if ($handle = opendir($images_folder_path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$ext = strtolower(substr(strrchr($file, "."), 1));
if(in_array($ext, $extensions)){
$images[] = $file;
}
}
}
closedir($handle);
}
if(!empty($images)){
$header_image = $images[array_rand($images)];
} else {
$header_image = '';
}
?>
Try this:
<?php
$dir = "images/";
$images = scandir($dir);
$i = rand(2, sizeof($images)-1);
?>
<img src="images/<?php echo $images[$i]; ?>" alt="" />
Below code validate image list by image extension.
<?php
function validImages($image)
{
$extensions = array('jpg','jpeg','png','gif');
if(in_array(array_pop(explode(".", $image)), $extensions))
{
return $image;
}
}
$images_folder_path = ROOT.'/web/files/Header/';
$relative_path = SITE_URL.'/web/files/Header/';
$images = array_filter(array_map("validImages", scandir($images_folder_path)));
$rand_keys = array_rand($images,1);
?>
<?php if(isset($images[$rand_keys])): ?>
<img src="<?php echo $relative_path.$images[$rand_keys]; ?>" alt="" />
<?php endif; ?>
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.
I searched the internet for hours on end to implement the code to what I wanted. I put together bits of various answers I found online. Here is the code:
<?php
$folder = opendir("Images/Gallery Images/");
$i = 1;
while (false != ($file = readdir($folder))) {
if ($file != "." && $file != "..") {
$images[$i] = $file;
$i++;
}
}
//This is the important part...
for ($i = 1; $i <= 5; $i++) { //Starting at 1, count up to 5 images (change to suit)
$random_img = rand(1, count($images) - 1);
if (!empty($images[$random_img])) { //without this I was sometimes getting empty values
echo '<img src="Images/Gallery Images/' . $images[$random_img] . '" alt="Photo ' . pathinfo($images[$random_img], PATHINFO_FILENAME) . '" />';
echo '<script>console.log("' . $images[$random_img] . '")</script>'; //Just to help me debug
unset($images[$random_img]); //unset each image in array so we don't have double images
}
}
?>
Using this method I was able to implement opendir with no errors (as glob() wasn't working for me), I was able to pull 5 images for a carousel gallery, and get rid of duplicate images and sort out the empty values. One downside to using my method, is that the image count varies between 3 and 5 images in the gallery, probably due to the empty values being removed. Which didn't bother me too much as it works as needed. If someone can make my method better, I welcome you to do so.
Working example (the first carousel gallery at top of website): Eastfield Joinery
I'm loading a folder full of images in, to create a jQuery Image Gallery.
There are currently 100 images being loaded in to create the gallery. I've got all that to load without issue.
All I want to do is make the image(s) that are loaded, load in randomly.
How do I achieve this?
My code is :
<?php
$folder = "images/";
$handle = opendir($folder);
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..")
{
echo ("<img src=\"".$folder.$file."\">");
}
}
?>
Thanks in advance.
Just store all the image paths in an array and do a random shuffle of the array. And then echo the elements
<?php
$folder = "images/";
$handle = opendir($folder);
$imageArr = array();
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..")
{
$imageArr[] = $file;
}
shuffle($imageArr); // this will randomly shuffle the image paths
foreach($imageArr as $img) // now echo the image tags
{
echo ("<img src=\"".$folder.$img."\">");
}
}
?>
Traverse the directory and store the image file names into an array and randomly select path names from the array.
A basic example:
$dir = new DirectoryIterator($path_to_images);
$files = array();
foreach($dir as $file) {
if (!$fileinfo->isDot()) {
$files[] = $file->getPathname();
}
}//$files now stores the paths to the images.
You can try something like this:
<?php
$folder = "images/";
$handle = opendir($folder);
$picturesPathArray;
while(($file = readdir($handle)) !== false) {
if($file != "." && $file != "..")
$picturesPathArray[] = $folder.$file;
}
shuffle($picturesPathArray);
foreach($picturesPathArray as $path) {
echo ("<img src=\"".$path."\">");
}
?>
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 ?>.