Jump to content

Show Image From Folder


nopelken

Recommended Posts

Hello,

 

I'm very newbie at PHP level. Someone told me to ask the question here.

 

I have made a html page, on which the user must enter his entry code. Eg:2012 / 2013

 

I also have a folder on the webserver with that name. When the user enters his code, I want him to show the images in the folder. There is no database relied to it.

How can I show eg. image201201 and 201202 when user 1 is entering code 2012 and show image201301 and image 201302 when user is entering code 2013.

 

Thanks in advance.

Link to comment
https://forums.phpfreaks.com/topic/270417-show-image-from-folder/
Share on other sites

I only have some javascript code I tried, but nothing in php,

 

<script type="text/javascript">

var imageID=0

function ShowPicture {

var code = prompt("Enter code:");

 

if (code == 2012) {

alert('Hallo');

image1 = newImage();

image1.src = "/pict/2012/01.jpg";

image2=newimage();

image1.src = "/pict/2012/02.jpg";

}

 

if (code == 2013) {

alert('Hallo');

image1 = newImage();

image1.src = "/pict/2013/01.jpg";

image2=newimage();

image1.src = "/pict/2013/02.jpg";

}

}

</script>

</head>

<body onload=ToonFoto()>

</body>

[code]

 

That's what I tried in javascript, but doesn't work.

<?php
$path_to_dir = '/path/to/images/dir/2012/';
if ($handle = opendir($path_to_dir))
{
while (FALSE !== ($entry = readdir($handle)))
{
 if ($entry != '.' && $entry != '..' && !is_dir($entry) && preg_match('/jpg|gif|png/i', $entry))
{
	 echo "<img src=\"" . $path_to_dir . $entry . "\" />\n";
 }
}
closedir($handle);
}
?>

A suggestion to the above code would be to strengthen the regex filter a little. As is, a file named jpg.exe would pass the filter. Something such as:

preg_match('/^[a-z0-9]+\.(jpg|gif|png)$/i', $entry)

 

should be fine for what you are using it for.

You could try glob as in:

 

$ArrayOfFileNames = glob('/path/to/images/dir/2012/*.{jpg,gif,png}', GLOB_BRACE);

 

which might not be disabled, and eliminates the need for the preg_match. Then use foreach to walk the array of files. I can't remember right off if the filenames in the array will include the full path or just the names.

 

Also, remember glob() will return false if it does not find any files that match

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.