Creating a Dynamic Vertical Gradient in PHP

Preface

This tutorial was written in a different era — before CSS gradients, before shadows, before material design; when the major browser vendors Internet Explorer, Firefox, and Chrome still had single-digit version numbers. The Internet had not yet realized the importance of minimalist design, and web pages took on the appearance of billboards over paper.

I recently dug up my old publications to bring them into the modern era on Medium and LinkedIn. This tutorial in particular is one of the first I ever wrote. I had the intention of rewriting each publication to remove obsolete information and appeal to a new target audience of junior developers and students. However, no amount of refactoring will make this particular tutorial less obsolete. With the CSS capabilities of modern browsers, there should never be another time to generate gradients on the server.

I present this tutorial for two purposes:

  • Logic. While one should not apply the principles of this tutorial to a production-facing environment, the ability to dynamically generate images and step through coding logic is still relevant.
  • Entertainment; an insight into the thought processes of myself as a junior developer and design of the early 2000’s. At the time of original writing, dynamically generated gradients were a big deal. Templates needed transitions from their “call to actions” and their flashy banners to their content. Designers and developers had to open PhotoShop any time they wanted to change a color on their website; the resulting gradients and shadows simply could not be rendered dynamically by the browser. Enter generating them on the server.

While I have opted to republish this tutorial, I will remove any content that may cause a reader to become a worse developer, and I am open to alterations suggested by comments. That said, I am leaving myself vulnerable by exposing a mindset of design from another decade, to show how far we have come in the front end development world.

Introduction

This is a tutorial for a script that I find indispensable. Gradients are a necessary and simple tool of web design, providing the perfect transition from color to color. The problem that I often find is the limitations the use of images puts on dynamic templates. I am a huge fan of dynamic templates — allowing color customization to match user preference.

It’s simple enough to add PHP to your CSS files to alter basic colors. Unfortunately, it’s not that easy with more complex templates. Designs are comprised of more than string literals in CSS. They include images, which are created in programs like PhotoShop, not browsers or web servers.

At least, that’s how the majority of web developers view images. Fortunately, they’re wrong. Starting at the basics, this tutorial is going to show you how to create dynamic gradients for your templates. Not only will this save you time in creating gradients (since you won’t have open PhotoShop), but this will allow you to use a greater variety of template choices for your users. Limiting template choice due to the cost, time, or effort of image creation is a thing of the past — at least when it comes to gradients.

For example, say you allow members to enter their own color values, similar to vBulletin’s profile customization. The user enters #A0A0FF for the header background color and #008000 for the navigation bar. But there’s a problem: there is a gradient that fades the header to the navbar. You don’t want to have to manually create every possible combination of colors! So what do you do? This a hurdle that this tutorial will help you jump.

Example

example gradient connecting two background colors
HTML and CSS for an example gradient connecting two background colors

Using a static image, when the user selects the two colors #A0A0FF and #008000, they will receive these undesired results:

a gradient that does not match the background colors

Dynamically generating a gradient from #A0A0FF to #008000 will instead produce:

a smoother transition, despite the terrible color choice

You didn’t even have to lift a finger or open PhotoShop to create the gradient. It created itself!

Setting Up the Parameters

The first things we need to establish when setting up a dynamic gradient are what parameters need to be dynamic. The height, start color, and/or end color? If any of these need to change on a per-image basis, they will need to be set via a $_GET variable. Otherwise, you can set them statically in the PHP file itself (e.g. $height = $_GET['height']; versus $height = 16;).

Using mod_rewrite for this is recommended. This isn’t a mod_rewrite tutorial, so I won’t provide extensive code for that. Here is one for having all three variables be dynamic, where gradient.php is the gradient generating file:

example use of Apache’s mod_rewrite

Check the Variables for Validity

Something that isn’t done often enough in programs is checking for legitimate variable values of user input. While mod_rewrite uses regular expressions to prevent the redirection of bogus requests, if the user knows the URL to the gradient.php file, they may input what they please. For that reason, to prevent PHP errors from clogging error logs, to get into the habit of checking variable input, and to prevent worse-case-scenario injected code in complicated color algorithms, we check for appropriate values.

the lost art of input validation

Calculate the Steps

If only PHP understood hex innately, my job would be easier. There are three things we’ll need to calculate before generating the image: the RGB value of the start color, the RGB value of the end color, and the basic algorithm for determining every shade in between.

the algorithm for the color change of each pixel

Here is an example of $step values:

example of expected end result

Create the Image

Now that the variables are calculated, we can just use PHP’s image functions to actually create and output the image.

the magic: creating images server-side

And there you have it! A gradient that creates itself. Here is the full code:

a finished product

You’re done! Just call upon your gradient.php file whenever you need to use a gradient! I even use it when the gradient isn’t dynamic, simply because it saves so much time, especially when tweaking colors by only a few values.

Conclusion

Enjoy this? You can find more by following me on Twitter and LinkedIn or by checking out my portfolio and other Medium posts.

Senior front end engineer / charlesstover.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store