How to stop access of a PHP file from other sites

One programmatic way is to check the referrer to make sure the request came from your site:

<?php
    $yoursite = "yoursite.com"; //Your site url without http://
    $yoursite2 = "www.yoursite.com"; //Type your domain with www. this time

    $referer = $_SERVER['HTTP_REFERER'];

    //Check if browser sends referrer url or not
    if ($referer == "") { //If not, set referrer as your domain
        $domain = $yoursite;
    } else {
        $domain = parse_url($referer); //If yes, parse referrer
    }

    if($domain['host'] == $yoursite || $domain['host'] == $yoursite2) {

        //Run your image generation code

    } else {

        //The referrer is not your site, we redirect to your home page
        header("Location: http://yoursite.com");
        exit(); //Stop running the script

    }    
?> 

Edit
This article presents an alternate method using PHP sessions.