This is the code I am using for making a gallery type:
Main PHP :
<?php
$folder_path = 'images/'; //image's folder path
$num_files = glob($folder_path . "*.{JPG,jpg,gif,png,bmp}", GLOB_BRACE);
$folder = opendir($folder_path);
if($num_files > 0)
{
while(false !== ($file = readdir($folder)))
{
$file_path = $folder_path.$file;
$extension = strtolower(pathinfo($file ,PATHINFO_EXTENSION));
if($extension=='jpg' || $extension =='png' || $extension == 'gif' ||
$extension == 'bmp')
{
?>
<a href="<?php echo $file_path; ?>"><img src="<?php echo $file_path; ?>"
height="200" /></a>
<?php
}
}
}
else
{
echo "the folder was empty !";
}
closedir($folder);
What should I do to display all image-names. Please help.
Try this inside while loop:
$file_path = $folder_path.$file;
$path_parts = pathinfo($file_path);
$extension = strtolower($path_parts['extension']);
if($extension=='jpg' || $extension =='png' || $extension == 'gif' || $extension == 'bmp')
{
echo '<img src="'.$file_path.'" height="200" />'.$path_parts['filename'].'';
}
Check this line:
$file_path = $folder_path.$file;
here $file is the name of the file, you can use this to display the file name like:
echo $file;
As per your requirement it is like:
<a href="<?php echo $file_path; ?>"><img src="<?php echo $file_path; ?>"
<?php echo $file; ?>
Related
I got a problem. I need to show image - located in folder - if extencion is .png, .jpg, .jpeg or .gif . If extencion is not one of them then just show content of the file (.tex).
I made a script that works. But it shows just one of them (img or text file at once). I need show both of them at once.
<?php
$allFiles = scandir('post/');
$files = array_diff($allFiles, array('.', '..'));
foreach($files as $file)
{
$ext = substr(strrchr($file, '.'), 1);
if($ext = "jpg" || $ext = "png" || $ext = "jpeg" || $ext = "gif" ) {
echo "<div class=post>
<img width= 200px src=post/".$file.">
</div>";
}
else {
echo "<div class=post>
". file_get_contents("post/".$file) ."
</div>";
}
}
?>
Thanks a lot for help.
Problem solved: change = to ==
<?php
$allFiles = scandir('post/');
$files = array_diff($allFiles, array('.', '..'));
foreach($files as $file)
{
$ext = substr(strrchr($file, '.'), 1);
if($ext == "jpg" || $ext == "png" || $ext == "jpeg" || $ext == "gif" ) {
echo "<div class=post>
<img width= 200px src=post/".$file.">
</div>";
}
else {
echo "<div class=post>
". file_get_contents("post/".$file) ."
</div>";
}
}
?>
Try this :
$allFiles = scandir('post/');
$extArray = array('jpg', 'png', 'jpeg', 'gif');
foreach($allFiles as $file)
{
$ext = end(explode('.', $file));
if(in_array($ext, $extArray)) {
echo "<div class='post'>
<img width='200px' src='post/'". $file ." />
</div>";
}else {
echo "<div class='post'>"
. file_get_contents('post/'.$file)
."</div>";
}
}
i have a little script that scans a directory and then echos out a list of all files (jpg's)
in that directory and lists it into html image links. it works pretty well.
is there a way i can get the image dimentions for each individual jpg?
i need my output to look something like this.
<img src="albm/1.jpg" width="333" height="460" />
<img src="albm/2.jpg" width="256" height="560" />
<img src="albm/3.jpg" width="327" height="580" />
here is my current script without the image dimentions.
<?php
$albm = $_REQUEST['albm'];
$dir = 'albums/'.$albm.'/';
$files = scandir($dir);
arsort($files);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
echo '<img src="' . $dir . $file . '"/>';
}
}
?>
<?php
$albm = $_REQUEST['albm'];
$dir = 'albums/'.$albm.'/';
$files = scandir($dir);
arsort($files);
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
$info = getimagesize($dir . $file);
$width = $info[0];
$height = $info[1];
echo '<img src="' . $dir . $file . '"/>';
}
}
?>
Here how to use it:
$size = getimagesize($path);
$width = $size[0];
$height = $size[1];
You can simple use getimagesize(image location) function, it returns width,height,type and attributes. Here is the example
<?php
list($width, $height, $type, $attr) = getimagesize("image_name.jpg");
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;
?>
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 have this code set up for inserting any image that is uploaded to my "images" folder, right into a gallery I have.... My problem is that it kind of inserts them randomly.. I would like to set it up to insert the most recently uploaded picture to the end of the gallery "row", any suggestions? Thanks
<?php
$image_dir = 'uploads/images/';
$per_column = 10;
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
if ($file != '.' && $file != '..')
{
if(strstr($file,'.png'))
{
$files[] = $file;
}
if(strstr($file,'.jpg'))
{
$files[] = $file;
}
if(strstr($file,'.gif'))
{
$files[] = $file;
}
if(strstr($file,'.jpeg'))
{
$files[] = $file;
}
}
}
closedir($handle);
}
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<li><img src="',$image_dir,$file,'" width="20" height="20" title="',$file,'"/></li>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo 'no pictures yet...';
}
?>
<?php
$image_dir = 'uploads/images/';
$per_column = 10;
$validExt = array(
'png' => 'image/png',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpg',
'gif' => 'image/gif',
);
if ($handle = opendir($image_dir)) {
while (false !== ($file = readdir($handle)))
{
$ext = strtolower(substr($file, -3));
if (isset($validExt[$ext]))
{
$stats = stat($image_dir.$file);
$files[$stats['mtime']] = $file;
}
}
closedir($handle);
}
$count = 0;
krsort($files);
$cnt = count($files);
if($cnt)
{
foreach($files as $file)
{
$count++;
echo '<li><img src="' . $image_dir . $file . '" width="20" height="20" title="' . substr($file, 0, -4) . '"/></li>'.chr(10);
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo 'no pictures yet...';
}
I'm not sure what your file format is, but try setting the filename to the current time using time() when uploading.
When you list your images, try using glob() instead of readdir.
Your code might then go as follows (untested):
$image_dir = 'uploads/images/';
$per_column = 10;
$files = glob($image_dir . "*.jpg|png|gif|jpeg");
if(count($files))
{
foreach($files as $file)
{
$count++;
echo '<li><img src="',$image_dir,$file,'" width="20" height="20" title="',$file,'"/></li>';
if($count % $per_column == 0) { echo '<div class="clear"></div>'; }
}
}
else
{
echo 'no pictures yet...';
}
Coupling this with giving the uploaded file a filename of the current time, this should order your images by most recent.
The most important line here is $files = glob($image_dir . "*.jpg|png|gif|jpeg");. This will scan the directory for any file (*) ending in .jpg, .png, .gif or .jpeg. You don't need to worry about . and ..; the expression filters that out.
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 ?>.