Display random image when filename starts with a specific name

images php coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
Indro
New php-forum User
New php-forum User
Posts: 7
Joined: Mon May 07, 2018 5:06 am

Sat Jul 07, 2018 12:03 am

Hello,

I am currently using this PHP code that randomly displays one image from a folder.

I would like to modify it so that, out of the folder, it only display a random image when the image filename starts with a specific name, for example, only choose the image among those whose filename starts with "2018_" and avoid all others.

Here is the complete code I use to display a random image:

Code: Select all

<?php

	$folder = '.';

    $extList = array();
	$extList['gif'] = 'image/gif';
	$extList['jpg'] = 'image/jpeg';
	$extList['jpeg'] = 'image/jpeg';
	$extList['png'] = 'image/png';
	
$img = null;

if (substr($folder,-1) != '/') {
	$folder = $folder.'/';
}

if (isset($_GET['img'])) {
	$imageInfo = pathinfo($_GET['img']);
	if (
	    isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
        file_exists( $folder.$imageInfo['basename'] )
    ) {
		$img = $folder.$imageInfo['basename'];
	}
} else {
	$fileList = array();
	$handle = opendir($folder);
	while ( false !== ( $file = readdir($handle) ) ) {
		$file_info = pathinfo($file);
		if (
		    isset( $extList[ strtolower( $file_info['extension'] ) ] )
		) {
			$fileList[] = $file;
		}
	}
	closedir($handle);

	if (count($fileList) > 0) {
		$imageNumber = time() % count($fileList);
		$img = $folder.$fileList[$imageNumber];
	}
}

if ($img!=null) {
	$imageInfo = pathinfo($img);
	$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
	header ($contentType);
	readfile($img);
} else {
	if ( function_exists('imagecreate') ) {
		header ("Content-type: image/png");
		$im = @imagecreate (100, 100)
		    or die ("Cannot initialize new GD image stream");
		$background_color = imagecolorallocate ($im, 255, 255, 255);
		$text_color = imagecolorallocate ($im, 0,0,0);
		imagestring ($im, 2, 5, 5,  "IMAGE ERROR", $text_color);
		imagepng ($im);
		imagedestroy($im);
	}
}

?>
I am not an expert but I feel the answer is to add "2018_" somewhere here

Code: Select all

$img = $folder.$imageInfo['basename'];
not sure in what format.

Thank you for your help.

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 708
Joined: Mon Feb 22, 2016 5:52 pm

Sat Jul 07, 2018 5:02 am


Indro
New php-forum User
New php-forum User
Posts: 7
Joined: Mon May 07, 2018 5:06 am

Sun Jul 08, 2018 10:11 pm

Thanks Hyper.

Post Reply