There're couple of valid approaches but the simpliest is to convert your color to grayscale and then check if result value is in upper half or lower. If in upper, then it's light color and you should use i.e. black as text color, if in lower, then it's dark, so white will work best. Something like this:
function getReadableTextColor( $backgroundColor ) {
$R = ($backgroundColor >> 16 ) & 0x000000ff;
$G = ($backgroundColor >> 8 ) & 0x000000ff;
$B = ($backgroundColor ) & 0x000000ff;
// grayscale: 0.3RED + 0.59GREEN + 0.11Blue
$K = (($R * 0.3) + ($G * 0.59) + ($B * 0.11));
// black fg color for light background, white for dark ones
return ( $K > 128 ) ? 0x000000 : 0xffffff;
}
then use like this
$bgColor = rand(0, 16777215);
$bgcolorHTML = '#' . base_convert($bgColor, 10, 16);
$fgColor = getReadableTextColor( $bgColor );
$fgColorHtml = '#' . base_convert($fgColor, 10, 16);