32,000+ SUBSCRIBERS CAN'T GO WRONG !!!

phpans
GET TOP ARTICLES, SNIPPETS, SCRIPTS IN YOUR INBOX FOR FREE!

Delivered by GET EMAIL UPDATES FeedBurner
We always respect your privacy and take protecting it seriously.
We won't Spam You

Get random image from directory in PHP

, 0,
Get random image from directory in PHP
This article about gets random image from a directory. If you want to use a random image for a link or an article then you can do that easily using PHP. There are a nice and cool tricks to do this program. It's so easy for a developer to make this script and it's easy to use also. Let's see how we make this script for make a random image viewer in PHP. we will use PHP glob function fo that. this function will extract images from a folder.
first we will create a function name as RandImg() then put this code into this function.
function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)];
return $randomImage;
}

we used $dir variable in RandImg() function to pass directory in this function so that we can use this function for mutiple directory. We also used $dir . '*.{jpg,jpeg,png,gif} this script will detect only jpg,jpeg,png and gif images and GLOBE_BRACE for match jpg,jpeg,png,gif.
Let's see how this script will work, create a index.php file into your server then create a directory name as images and put some images into this directory. In index.php file write down this script and run this script into your server.
<?php
function RandImg($dir)
{
$images = glob($dir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);

$randomImage = $images[array_rand($images)];
return $randomImage;
}
$link = "http://phpans.com";
$the_images = RandImg('images/');
$ImageWithLink = '<a href="'.$link.'"><img src="'.$the_images.'"></a>';
echo $ImageWithLink;
?>

This script is ready for use. this script will execute random image as result.

Download PDF
Is this article helpful for you?





captcha

  • Connect
  •       
Top
Create an free account and start learning & sharing! Sign Up