Listing and previewing images in a directory using PHP - php

I'm trying to improve the administrator panel of my website. I need to preview the images in the thumbnails folder so that when i'm using thumbnails for news I dont have to upload the image for the second time. I found a great script, but I get failed to read the directory error. Here is the script:
<?php
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif", "image/png");
// Original PHP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
// fetch image details
$images = getImages("../images/thumbnails");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
I really appreciate if someone could help..
EDIT:
<div style=" height: 200px; width: 600px; overflow: auto;">
<?PHP
foreach(glob("../thumbnail/".'*') as $filename){
echo "<div style=\"display:inline-table; font-size:10px; font-family:'Tahoma'; margin:5px;\">";
echo "<img width=\"100px\" height=\"100px\" src=\"../thumbnail/$filename\"/>";
echo "<br>".basename($filename) . "<br>";
echo "</div>";
}
?>
</div>
This method works perfect. No need to use complicated scripts.
Anyway, can somebody please tell me how to check images less than 100px x 100px displayed?

<?PHP
foreach(glob("../thumbnail/".'*') as $filename){
list($width, $height, $type, $attr) = getimagesize("../thumbnail/".$filename);
if($width>=100 || $height >=100) continue;
$rest = substr($filename, 3);
?>
That should do it..

Related

WordPress PHP Random Image Script

I've been displaying using the below code for a few years to display a random image in WordPress without any issues. The code broke today when I upgraded to PHP 7.4. I'm stuck on how to make the code work again or replace it with new code so that images from a directory are randomly displayed.
*Update: Broken code means images are you no longer being displayed. There are no error messages our outputs, just a blank section where the random image would usually display.
<?php
$folder = '';
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1;
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) {
if (preg_match('/\.'.$ext.'$/i', $file, $test)) {
$files[] = $file;
++$i;
}
}
}
closedir($handle);
mt_srand((double)microtime()*1000000);
$rand = mt_rand(0, $i);
header('Location: '.$folder.$files[$rand]); // Voila!
?>
The file is called rotate.php and it's located within the images directory. I call the rotate.php script from within the website's css style sheet using the following code:
background: #ffffff url(images/rotate.php) no-repeat center top;
Thanks for your help.

How can I have a PHP Image Gallery load on HTML?

I have a PHP based image gallery using the Lightbox plug-in. When I run on MAMP, it works fine on a local server.
However, it fails when I upload the files to an SFTP client for my website.
I have the following code:
<?php
$directory = 'SpringPhotos17';
$thumbsdirectory = 'SpringPhotos17/_thumb';
$allowed_types=array('jpg','jpeg','gif','png');
$file_parts=array();
$ext='';
$title='';
$i=0;
$dir_handle = #opendir($directory) or die("There is an error with your image directory!");
while ($file = readdir($dir_handle))
{
if($file=='.' || $file == '..') continue;
$file_parts = explode('.',$file);
$ext = strtolower(array_pop($file_parts));
$title = implode('.',$file_parts);
$title = htmlspecialchars($title);
$nomargin='';
if(in_array($ext,$allowed_types))
{
if(($i+1)%4==0) $nomargin='nomargin';
echo '
<div class="pic '.$nomargin.'" style="background:url('.$thumbsdirectory.'/'.$file.') no-repeat 50% 50%;">
'.$title.'
</div>';
$i++;
}
}
closedir($dir_handle);
?>
I inserted this PHP code within the HTML code for an image gallery. On the website, it comes up as:
'.$title.'
How can I resolve this issue? Thank you for your time and help in advance!

PHP GLOB skips the first image in each folder

I am trying to understand why GLOB is skipping the first image in whatever folder I direct it too. I work around it by placing a dummy image named so it is listed first but I would like to solve this irk in a more efficient way. Here is my code.
<?php
// This retrieves images from a selected folder - anchor with a data-xx-xx attribute
// via jQuery - click - the data-xx-x value is put into a hidden field : foldpath
// It all works fine BUT, it always fails to return the first image in a folder
// I get around it by placing within each folder a dummy image called aa.jpg
// which hopefully will always be the first image but it is not really a
// satisfactory solution.
if($_POST && isset($_POST["foldsub"]) && isset($_POST["foldpath"]) ){
// hidden field $_POST["foldpath"];
//A typical path might be :
// ../images/products/CLIENTS_images/bridal_whatnots/bridal_belts
//the ../ prefix is reoved via php when the page is displayed and replaced by DIR
// for testing between admin folders and the main root folders I use the relative paths.
$fp = $_POST["foldpath"];
$files = glob($fp ."/" ."*.*");
//this is a pop up page which needs to stay open after the selection has been made
echo "<script> $(\"#imgstuff\").css({\"display\":\"block\"});</script>";
//the form closed on whgen the close x is selected
}else
{
//default
$files = glob("../images/bannerImgs/*.*");
}
for ($i=0; $i<count($files); $i++)
{
$image = $files[$i];
$supported_file = array(
'jpg',
'jpeg',
'png'
);
$ext = strtolower(pathinfo($image, PATHINFO_EXTENSION));
if (in_array($ext, $supported_file)) {
// print $image ."<br />";
$path = $image;
$path1 = DIR;
if (strpos($path, $path1) !== false) {
$path2 = $path;
}else{
$path2 = str_replace('../', '', $path);
$path2 = $path1.$path2;
}
$fn = basename($path);
$fn = basename($path, PATHINFO_EXTENSION);
if($fn!="aa.jpg"){
echo '<p class="imgdet">';
// echo '<span class="imglongpath">' . $path2 .'</span>';
echo '<img src="'.$image .'" alt="Random image" />';
echo '<span class="imgname">' . $fn .'</span>';
// echo '<span class="imgmesg">Now click Confirm / Set Choice</span>';
// "<br /><br />";
echo "</p>";
}
} else {
continue;
}
}
?>

Shell_Exec error for directory listing?

I found a useful php code which displays the photos in a folder directory as a image preview. The issue is my host provider blocks one of the script commands, "Shell_exec()", so the php code doesn't work.
Any way of getting the code to run without using shell_exec?
<?PHP
// filetypes to display
$imagetypes = array("image/jpeg", "image/gif");
?>
<?PHP
function getImages($dir)
{
global $imagetypes;
// array to hold return value
$retval = array();
// add trailing slash if missing
if(substr($dir, -1) != "/") $dir .= "/";
// full server path to directory
$fulldir = "{$_SERVER['DOCUMENT_ROOT']}/$dir";
$d = #dir($fulldir) or die("getImages: Failed opening directory $dir for reading");
while(false !== ($entry = $d->read())) {
// skip hidden files
if($entry[0] == ".") continue;
// check for image files
$f = escapeshellarg("$fulldir$entry");
$mimetype = trim(`file -bi $f`);
foreach($imagetypes as $valid_type) {
if(preg_match("#^{$valid_type}#", $mimetype)) {
$retval[] = array(
'file' => "/$dir$entry",
'size' => getimagesize("$fulldir$entry")
);
break;
}
}
}
$d->close();
return $retval;
}
?>
<?PHP
// fetch image details
$images = getImages("images");
// display on page
foreach($images as $img) {
echo "<div class=\"photo\">";
echo "<img src=\"{$img['file']}\" {$img['size'][3]} alt=\"\"><br>\n";
// display image file name as link
echo "",basename($img['file']),"<br>\n";
// display image dimenstions
echo "({$img['size'][0]} x {$img['size'][1]} pixels)<br>\n";
// display mime_type
echo $img['size']['mime'];
echo "</div>\n";
}
?>
You can get the mime type of a file using the PHP function mime_content_type(). This way you can get rid of the shell_execute used to detect the mime type in your code.

Gallery Is Missing Files From Directory- How To Retrieve All Files From Directory

I finally got my code to populate a gallery from a directory while using fancybox. It's a basic thumbnail gallery that shows the larger image upon clicking. The only problem is that it is missing a lot of files from the thumbnail directory.
The code retrieves all of the links for the larger images but it won't retrieve ALL of the thumbnails, only a few of them and they're not even in order.
What is wrong in my code?
<?php
$directory = 'thumb'; //where the gallery thumbnail images are located
$allowed_types=array('jpg','jpeg','gif','png');//allowed image types
$file_parts=array(); $ext=''; $title=''; $i=0;//try to open the directory
$dir_handle = #opendir($directory) or die("There is an error with your image directory!");
while ($file = readdir($dir_handle)) //traverse through the files
{ if($file=='.' || $file == '..') continue; //skip links to the current and parent directories
$file_parts = explode('.',$file); //split the file name and put each part in an array
$ext = strtolower(array_pop($file_parts)); //the last element is the extension
$title = implode('.',$file_parts); //once the extension has been popped out, all that is left is the filename
$title = htmlspecialchars($title); //make the filename html-safe to prevent potential security issues
natsort($file_parts); //sort by filename--NOT WORKING
$nomargin='';
if(in_array($ext,$allowed_types)) //check if the extension is an allowable type
{
if(($i+1)%4==0) $nomargin='nomargin'; //the last image on the row is assigned the CSS class "nomargin"
//Begin thumbs containers with fancybox class
echo '<div class="thumbs fancybox '.$nomargin.'" style="background:url('.$directory.'/'.$file.') no-repeat 50% 50%;"> <a rel="group"
href="images/'.$file.'" title="'.$title.'">'.$title.'</a>
</div>';
$i=0; //increment the image counter
} } closedir($dir_handle); //close the directory
?>
An alternative approach you may want to use to secure your list of thumbnails:
$directory = 'thumb'; //where the gallery thumbnail images are located
$files = glob($directory."/*.{jpg,jpeg,gif,png}", GLOB_BRACE);
natsort($files); //sort by filename
Then to render it out simply do this:
<?php
for($x = 0; $x < count($files); $x++):
$thumb = $files[$x];
$file = basename($thumb);
$nomargin = $x%4 == 0?" nomargin":"";
$title = htmlspecialchars($file);
?>
<div class="thumbs fancybox<?= $nomargin ?>"
style="background:url('<?= $thumb ?>') no-repeat 50% 50%;">
<a rel="group" href="images/'.<?= $file ?>" title="<?= $title ?>"><?= $title ?></a>
</div>
<?php
endfor;

Categories