Content Negotiation

PHP Output

HTTP_ACCEPT header: text/html,application/xhtml+xml,text/xml;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5

Prefered MIME types: application/xhtml+xml and image/png

Using XHTML.

Using PNG.

This is a PNG.

Information

Content Negotiation code from Autistic Cuckoo:
http://www.autisticcuckoo.net/archive.php?id=2004/11/03/content-negotiation

The $use_alternative variable is assigned a value of either true or false depending on the user agent's HTTP accept header, though the W3C Validator doesn't send an accept header, so the function will always use the default MIME type specified for it. Therefore you can add ?html&gif or ?xhtml&png (and various combinations thereof) to the URL to force particular MIME types for validating purposes or viewing preferences.

Code

function test_mime($default, $alternative){

  $use_alternative	= false;

  if( preg_match('/'.make_regexp_safe($alternative).'(;q=(\d+\.\d+))?/i', $_SERVER['HTTP_ACCEPT'], $matches) ){

    $alternativeQ	= isset($matches[2]) ? $matches[2] : 1;

    if( preg_match('/'.make_regexp_safe($default).'(;q=(\d+\.\d+))?/i', $_SERVER['HTTP_ACCEPT'], $matches) ){

      $defaultQ		= isset($matches[2]) ? $matches[2] : 1;
      $use_alternative	= ($alternativeQ >= $defaultQ);

    } else {

      $use_alternative	= true;

    }

  }

  return $use_alternative;

}