Random images in php

I am currently using this PHP code to display images in a php page with some text provided by the user using an input tag.

My php code:

<?php
header('Content-type: image/jpeg');
$jpg_image = imagecreatefromjpeg('img/1.jpg');
$white = imagecolorallocate($jpg_image, 73, 41, 236);
$font_path = 'OpenSans-Italic.TTF';
$text= $_GET['name']; 
imagettftext($jpg_image, 25, 0, 75, 50, $white, $font_path, $text);
imagejpeg($jpg_image);
imagedestroy($jpg_image);
?>

      

This code works great. I am using $_GET['name'];

to get input from user as you can see. I have selected a picture that will display my user-supplied text, any name of my image 1.jpg

I have more photos in my library that I want them to be randomly selected and print user-supplied text on them, my other image names 2.jpg

, 3.jpg

, 4.jpg

I hope that you will find any solution for me.

+3


source to share


3 answers


Assuming you have 15 images, you can use:



$randomNumber = rand(1, 15);
$jpg_image = imagecreatefromjpeg('img/' . $randomNumber . '.jpg');

      

+1


source


Other answers suggest that you always use numeric values ​​for filenames, but if you cannot put filenames in an array and use array_rand()

to get a random filename from an array like this:

$image_files = array("1.jpg", "2.jpg", "3.jpg", "4.jpg");
$image_filename = $image_files[array_rand($image_files)];
$jpg_image = imagecreatefromjpeg("img/{$image_filename}");

      

Remember that array_rand()

returns a random key from an array, not a value.



From here you can easily take it one step further and use glob()

to get the filenames from the directory. That being said, keep in mind that it glob()

returns full paths, so you'll need to use basename()

to get just the filename:

$image_files = glob("img/*.jpg");
$image_path = $image_files[array_rand($image_files)];
$image_filename = basename($image_path);

      

+2


source


$countImages = 10; // your last number
$jpg_image = imagecreatefromjpeg('img/' . rand(1,$countImages). '.jpg');

      

0


source







All Articles