Simple PHP Colour Manipulation Functions

The other day I was updating my WordPress plugin, BM Custom Login, and I need some simple colour manipulation functions. In the plugin you can pick colours for different elements of the WordPress login interface, and I wanted to colour the login button. I used the users selected colour, but then I wanted to have a darker border colour, and I wanted to make sure the button text was always readable.

So I made a couple of simple functions for doing these two things. I also made a simple colour sanitisation function to ensure the colours are nice and safe.

Adjust Colour Brightness

This function adjusts the brightness of the colour the specified amount by adding or subtracting a value from the red, green and blue channels. I know it’s not the ideal way to do this as it doesn’t keep the colour the same, but as a quick function for limited use I think it works quite nicely.

    /**
     * adjust brightness of a colour
     * not the best way to do it but works well enough here
     *
     * @param type $hex
     * @param type $steps
     * @return type
     */
    function bm_adjust_colour_brightness( $hex, $steps ) {

        $steps = max( -255, min( 255, $steps ) );

        $hex = str_replace( '#', '', $hex );
        if ( strlen( $hex ) == 3 ) {
            $hex = str_repeat( substr( $hex, 0, 1 ), 2 ) . str_repeat( substr( $hex, 1, 1 ), 2 ) . str_repeat( substr( $hex, 2, 1), 2 );
        }

        $color_parts = str_split( $hex, 2 );
        $return = '#';

        foreach ( $color_parts as $color ) {
            $color = hexdec( $color );
            $color = max( 0, min( 255, $color + $steps ) );
            $return .= str_pad( dechex( $color ), 2, '0', STR_PAD_LEFT );
        }

        return $this->sanitize_hex_color( $return );

    }

Create Readable Text Based on Colour

I wanted to ensure the text on the button was readable so I use this function to calculate the brightness of the colour and then return either black or white.

    /**
     * Calculate whether black or white is best for readability based upon the brightness of specified colour
     *
     * @param type $hex
     */
    function bm_readable_colour( $hex ) {

        $hex = str_replace( '#', '', $hex );
        if ( strlen( $hex ) == 3 ) {
            $hex = str_repeat( substr( $hex, 0, 1 ), 2 ) . str_repeat( substr( $hex, 1, 1 ), 2 ) . str_repeat( substr( $hex, 2, 1), 2 );
        }

        $color_parts = str_split( $hex, 2 );

        $brightness = ( hexdec( $color_parts[0] ) * 0.299 ) + ( hexdec( $color_parts[1] ) * 0.587 ) + ( hexdec( $color_parts[2] ) * 0.114 );

        if ( $brightness > 128 ) {
            return '#000';
        } else {
            return '#fff';
        }

    }

Sanitize Colour

You should always sanitize data before outputting it. This ensures things are as secure as can be. This function is a slightly modified version of the sanitize_hex_color function one included in the WordPress Customizer – however that one is not available on the front-end so I made my own.

    /**
     * sanitize hexedecimal numbers used for colors
     *
     * @param type $color
     * @return string
     */
    function bm_sanitize_hex_color( $color ) {

        if ( '' === $color ) {
            return '';
        }

        // make sure the color starts with a hash
        $color = '#' . ltrim( $color, '#' );

        // 3 or 6 hex digits, or the empty string.
        if ( preg_match( '|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) {
            return $color;
        }

        return null;

    }

Let me know what you think on Mastodon, or BlueSky (or Twitter X if you must).

WordPress News

The latest WordPress updates from the WPBriefs Podcast.

Related Posts

20 Mar 2013

Mastering the Psychology of Colour Theory in Web Design

As an aspiring or established blog writer, you will probably be thinking of how you can attract more readers to your blog. Of course, there are many ways to build a loyal audience, but one aspect which is often overlooked...
01 Mar 2018

Website Colour Analyzer

In January I published Colour, a simple app that analyses the colours used in a website and suggests ways you can merge the colour to make the design simpler.I don’t know if it’s an age thing, or a generational thing,...
27 May 2013

WordPress: 10 Years Young, What Does The Future Hold?

WordPress is now 10 years old. I started using wordpress 9 years ago – which means I joined the WordPress community early on. The reason I chose WordPress is simply because of the fabled 5 minute install process – I...
14 May 2013

Redesigning the WordPress Post Editor

Ghost is a project born from frustration with WordPress. Ironically it seems to be mostly WordPress power users who want to use it. The Ghost team – led by John O’Nolan – put Ghost on KickStarter last week and it...
05 Oct 2021

Randomness with PHP

When I was making my generative art I needed to generate a lot of random things. The simplest way to do that with PHP is to use the rand() function.The rand() function selects a random integer (whole number) between 0...