How to get images from a folder one at a time and display on a page using PHP

How to get images from a folder and display them on the page, can I resize it in php itself, or do I need to resize it and upload it separately to display it as thumbnails?

+6
php image
source share
5 answers

Here's the basic structure for moving a directory and doing something with image files (this 'images' is a directory in the same directory of your script)

 $image_types = array( 'gif' => 'image/gif', 'png' => 'image/png', 'jpg' => 'image/jpeg', ); foreach (scandir('images') as $entry) { if (!is_dir($entry)) { if (in_array(mime_content_type('images/'. $entry), $image_types)) { // do something with image } } } 

Here you can send images directly to the browser, create tags for the HTML page, or create thumbnails with the GD function and save them for display.

+11
source share

I think this can help you!

 <? $string =array(); $filePath='directorypath/'; $dir = opendir($filePath); while ($file = readdir($dir)) { if (eregi("\.png",$file) || eregi("\.jpg",$file) || eregi("\.gif",$file) ) { $string[] = $file; } } while (sizeof($string) != 0){ $img = array_pop($string); echo "<img src='$filePath$img' width='100px'/>"; } ?> 
+7
source share

eregi now deprecated, so instead of preg_match you can use

 <?php $string =array(); $filePath='directorypath/'; $dir = opendir($filePath); while ($file = readdir($dir)) { if (preg_match("/.png/",$file) || preg_match("/.jpg/",$file) || preg_match("/.gif/",$file) ) { $string[] = $file; } } while (sizeof($string) != 0){ $img = array_pop($string); echo "<img src='$filePath$img' >"; } ?> 
+2
source share

Here is a single line font based on another answer to a similar question:

 // this will get you full path to images file. $data = glob("path/to/images/*.{jpg,gif,png,bmp}", GLOB_BRACE); // this will get you only the filenames $data= array_map('basename', $data); 

Initially, I wanted to use the @Imran solution , but mime_content_type not available, and the server (on which I have zero control) uses older versions of Apache and Php.

So I changed it a bit to work with the file extension, and I give it here.

 $imgDir = "images_dir"; // make sure it a directory if (file_exists($imgDir)) { // select the extensions you want to take into account $image_ext = array( 'gif', 'png', 'jpg', 'jpeg' ); foreach (scandir($imgDir) as $entry) { if (! is_dir($entry)) { // no need to weed out '.' and '..' if (in_array( strtolower(pathinfo($entry, PATHINFO_EXTENSION)), $image_ext)) { // do something with the image file. } } } } 

The code is verified and works.

+1
source share

All Articles