Steal My Code: Easy Images with PHP
Published 20 October 04 by Justin French, 4 comments
Image tags shit me… they’re probably my most hated HTML tag. Get the height and width, write some alternative text, and then wrap it all in some really repetitive mark-up.
I took a look at a basic image tag, and decided that PHP’s native getimagesize() function can take care of the width and height, we can make a half-decent default alt text based on the filename, and my images are always stored in an /images/ directory. So really, all I need to provide is the file name – everything else could be handled with PHP and some educated guess work.
So I created a new function imageTag(), which takes care of everything based on the file name. I won’t clutter things up by posting the code here, but you can steal my code and have a look for yourself. Just remove the .txt extension and include() it at the top of any PHP script/page you want to use it in.
imageTag() accepts two parameters, the filename of the image (eg “cat.png”) and optionally alternative text for the image. If no alternative text is provided, it will pretty up the filename and use it instead.
Yes, there’s plenty more I could add (additional parameters for forcing an alternate height and width, class, id and style attributes, long descriptions…) but all I really wanted to achieve here was a time saving way to reduce the repetitive, boring nature of using images in HTML.
Stay tuned for Part 2 in a few days!
Before you go…
Here’s some links to my most popular posts: