Question: I want users on my website to be able to pick a hex colour, and I just want to display white text for dark colours and black text for light colours. Can you work out the brightness from a hex code (preferably PHP)?

Answer: 
I made one similar - but based on weightings of each colour [(based on the C# version of this thread)](https://stackoverflow.com/a/2241471/174034)

```
function readableColour($bg){
    $r = hexdec(substr($bg,0,2));
    $g = hexdec(substr($bg,2,2));
    $b = hexdec(substr($bg,4,2));

    $contrast = sqrt(
        $r * $r * .241 +
        $g * $g * .691 +
        $b * $b * .068
    );

    if($contrast > 130){
        return '000000';
    }else{
        return 'FFFFFF';
    }
}

echo readableColour('000000'); // Output - FFFFFF

```

**EDIT:** 
Small optimisation:
Sqrt is known as an expensive math operation, which is probably neglectable in most scenarios, but anyway, it could be avoided by doing something like this.

```
function readableColour($bg){
    $r = hexdec(substr($bg,0,2));
    $g = hexdec(substr($bg,2,2));
    $b = hexdec(substr($bg,4,2));

    $squared_contrast = (
        $r * $r * .299 +
        $g * $g * .587 +
        $b * $b * .114
    );

    if($squared_contrast > pow(130, 2)){
        return '000000';
    }else{
        return 'FFFFFF';
    }
}

echo readableColour('000000'); // Output - FFFFFF

```

It simply doesn't apply the sqrt, instead it powers the desired cut off contrast by two, which is a much cheaper calculation
You need to convert the RGB values to HLS/HSL (Hue Lightness and Saturation) you can then use the Lightness to determine whether you need light text or dark text.

[This page](http://www.serennu.com/colour/rgbtohsl.php) has some details on how to the conversion in PHP as well as selecting complementary colour from this.

*I've only just spotted that the site is an astrology site - so apologies if anyone's offended.*