Tutorial – Pull in Images from a Folder with PHP

This tutorial will go over how to pull any image, or file from within a folder in the same directory as the code. Here is all you need to generate a tile for each image as well as load each image.

Something to note, as this is being done with XHTML lines of code generated by PHP they are SEO friendly.

'.str_replace('.jpg', ' ', str_replace('name', 'Name', $file)).'';
echo ''.str_replace('name', 'Clean Name', $file).'
'; } ?>

Now lets take a look at the code a little more closely:

This is what scans the directory defined as $dir_handle with “scandir”. It then compares the array created with files from $dir_handle to the “array(‘.’, ‘..’)” which means anything you include into that array will be excluded from the final list of files, for example if you wanted to exclude “image03.jpg” you’d add that to the list. Now the last thing it does is go through the array you’ve created by scanning the directory and filtered with “array_dif” will execute anything you put inside of the “{” and “}” for each file in the directory.

Now lets take a look at the echo lines I used:

echo '

'.str_replace('.jpg', ' ', str_replace('name', 'Name', $file)).'

'; echo ''.str_replace('name', 'Clean Name', $file).'

These are 2 lines of code with a lot happening. First it creates an H2 title by getting the file name and Changing it to whatever you want it to say (for example image to Photo). Then it replaces the file extension with a space, again to further clean up the look of the title.

The second line of code is doing a bit more, it generates an XHTML image tag which has a class to help formatting with CSS later. It also cleans up the alt and title tags in a similar fashion as the H2 tile is cleaned up. It also tells the image tag where the source image file is located.

That’s all there is to it, this code will pull in any images inside of the images/gallery/ directory and load them on the page. This can be helpful for a few reasons such as being able to load all images from a folder with a few lines of code. Thus automating the process instead of creating individual image tags for each image in the folder. Another good reason is if you decide to add more images into the folder they will automatically be called in through the code and you won’t need to change anything.

Leave a Reply