you are checking the referer properly
what I would do to see what's going on is
echo _SERVER['HTTP_REFERER'] . "<BR />";
then you'll know why your if loop is failing.
When I said check a query string parameter I ment do something like this:
in calling script
echo "<a href=\"mypage.php?valid=";
echo md5("mypage.php");
echo "\">My Page</a>\n";
in mypage.php
if($_GET['valid'] == md5('mypage.php')) {
// allowed to access
} else {
//not allowed to access
} //end if
this allows you to be able to call this script from anywhere easily and people can email links to it to their friends and have them work but people can't just type in or link to mypage.php.