Setting the referrer in SimpleTest web tests - faking the HTTP_REFERER

Sometimes you might want to make a PHP web page do different things depending on the value that is set in the ‘HTTP_REFERER‘ attribute of the browser’s header information.

In PHP this value is accessed via the $_SERVER[’HTTP_REFERER’] predefined variable. As it says in the PHP documentation, it is

the address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

It would be quite cumbersome to test your referer-oriented behaviour by hand. But luckily we have SimpleTest which is a suite of PHP classes that make it easy to write automated tests. It includes some ‘web tester classes‘ that enable you to mimic the behaviour of a web browser in test cases. Furthermore, it has a method for setting the ‘headers’ of your ‘webtest browser’ which allows you to see how your web site reacts according to various faked values that represent ‘the referring page’.

Here is some example webtest code:

In the code above

  • The class being used extends from SimpleTest’s WebTestCase class which is doing most of the work.
  • The value of the http referer is set to “” with the addHeader() method, as in the line:
  • The page is retrieved using the get() method, as in the line:
  • We then assert that the server’s response was OK (200)
  • We then assert that the server returned the some specific text in its content.
    $this->assertText('I hope you had fun at');

Read more about how to write your own automated web tests on the SimpleTest website.

The very fact that you can fake the http referer value for testing proves that it is not the most reliable piece of info to base a page’s logic on. However, it can still be fun to play with.

Leave a Reply