WordPress PHP Random Image Script - php

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.

Related

Search for latest image in multiple subfolders,grab it rename it and delete subfolders and images

I have the following script for a webcam that upload pics every minute that runs with cron job.
It searches for images in a specific folder grabs and renames the latest, copy it to a new destination and delete the rest images.
Here is the script:
<?php
date_default_timezone_set("Europe/Athens");
//
//Watch Folder
$dir = "../upload";
//File extention to watch
$pattern = '/^.(jpg)$/';
//Newest file check
$newstamp = 0;
$newname = "";
if ($handle = opendir($dir)) {
while (false !== ($fname = readdir($handle))) {
// Eliminate current directory, parent directory
if (preg_match(' /^\.{1,2}$/',$fname)) continue;
// Eliminate other pages not in pattern
if (! preg_match('/\.(jpg)$/',$fname)) continue;
// -------------
// Collecting images
$pinakas[] = $fname;
}
// Sort Images
sort($pinakas);
// Count
$posot = count($pinakas);
// Take the before last position
if ($posot>1) $newname = $pinakas[$posot-2];
if ($posot==1) $newname = $pinakas[$posot-1];
}
closedir ($handle);
// $newname NEW IMAGE NAME
//COPY NEW IMAGE TO NEW PLACE
copy("../upload/$newname", "../camera1.jpg");
//DELETE IMAGES
$filesa = glob('../upload/*.jpg');
array_walk($filesa,'myunlink');
function myunlink($t)
{
unlink($t);
}
?>
Now i have a new ip camera that upload a pic every minute but everytime in a different folder like this:
Time: 10:01 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/01/05[R][0#0][0].jpg
Time: 10:02 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/02/06[R][0#0][0].jpg
Time: 10:03 ..upload/GSDGSDGSDGS/19-07-2018/001/jpg/10/03/07[R][0#0][0].jpg
How do i now make the script to search all the subfolders of ..upload for latest jpg grab it, copy it to new place and delete all the subfolders and .jpg images of the ..upload folder?
Any help appreciated.
You can do this with recursive function:
function getJpgImages($dir, &$pinakas = array()){
$files = scandir($dir);
foreach($files as $key => $value){
$path = realpath($dir.DIRECTORY_SEPARATOR.$value);
if(!is_dir($path)) {
if ( preg_match('/\.(jpg)$/',$path) )
$pinakas[] = $path;
} else if($value != "." && $value != "..") {
getDirContents($path, $pinakas);
}
}
return $pinakas;
}
and then remove your while loop and get images like this:
$pinakas = getJpgImages($dir);

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!

How to display image from server (newest-oldest) to a new php page?

i have a form that create images (using imagejpeg, imagettftext and imagecreatefromjpeg) and save it on a folder in the server. What i need to do is to display ALL created images to another page, the newest on the top and so that the oldest is at the bottom. i have a form called formdisplay.php but it's just displaying a broken image and not newest to oldest. hope you can help me with this. really need to get this working. thanks in advance for your help.
i have read the posts but none of those worked for me.
Pull dedicated images from folder - show image + filename (strip part of filename + file-extension)
How can I display latest uploaded image first? (PHP+CSS)
getting images from the server and display them
Displaying images from folder in php
display image from server embedding php in html
formcreatesave.php
imagecopymerge($im, $img2, 10, 350, 0, 0, imagesx($img2), imagesy($img2), 100);
$date_created = date("YmdHis");//get date created
$img_name = "-img_entry.jpg"; //the file name of the generated image
$img_newname = $date_created . $img_name; //datecreated+name
$img_dir =dirname($_SERVER['SCRIPT_FILENAME']) ."/". $img_newname; //the location to save
imagejpeg($im, $img_dir , 80); //function to save the image with the name and quality
imagedestroy($im);
formdisplay.php
$dir = '/home3/site/public_html/Master/uploader/uploader';
$base_url = 'http://mysite.com/Master/uploader/uploader/20131027024705-img_entry.jpg';
$newest_mtime = 0;
$show_file = 'BROKEN';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (($file != '.') && ($file != '..')) {
$mtime = filemtime("$dir/$file");
if ($mtime > $newest_mtime) {
$newest_mtime = $mtime;
$show_file = "$base_url/$file";
}
}
}
}
print '<img src="' .$show_file. '" alt="Image Title Here">';
please feel free to edit my code. thanks :)
This goes after the while loop that creates the $images array (list of image filenames
foreach ($images as $image)
{
$filetime = filemtime("images1/$image");
$sortedimages[]$filetime => $image;
}
krsort($sortedimages);
echo "<pre>";
print_r($sortedimages);
echo "</pre>"
?>
Read images from folder.
Loop through them and insert into array with the key filetime of image.
Use krsort function to sort them according to date.
Loop and display them.
I think this link will help you:
http://forums.phpfreaks.com/topic/219466-php-displaying-images-from-folder-with-most-recent-first/

Listing and previewing images in a directory using 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..

Filename image as Automatic caption

I am using this script to display random images from a folder. I have hundreds of images with significant filenames, So I’m looking for a way to display each image file name as an image caption. Is this possible?
this is the script Im using:
<?php
/*
By Matt Mullenweg > http://photomatt.net
Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
Latest version always at:
http://photomatt.net/scripts/randomimage
*/// Make this the relative path to the images, like "../img" or "random/images/".
// If the images are in the same directory, leave it blank.
$folder = '';
// Space seperated list of extensions, you probably won't have to change this.
$exts = 'jpg jpeg png gif';
$files = array(); $i = -1; // Initialize some variables
if ('' == $folder) $folder = './';
$handle = opendir($folder);
$exts = explode(' ', $exts);
while (false !== ($file = readdir($handle))) {
foreach($exts as $ext) { // for each extension check the extension
if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
$files[] = $file; // it's good
++$i;
}
}
}
closedir($handle); // We're not using it anymore
mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
$rand = mt_rand(0, $i); // $i was incremented as we went along
header('Location: '.$folder.$files[$rand]); // Voila!
?>
If all you want to do is continue to display a single random image then remove (or comment out so you can restore it if you later want to) the header line and at the end of the file add the following lines underneath it:
//header('Location: '.$folder.$files[$rand]); // Voila!
echo $files[$rand];
?>
<br />
<img src="<?php echo $folder.$files[$rand] ?>" />
You might want to add some css styling to set the display size of the image, and to format the caption above it.

Categories