Yes, this is expected from what you have posted. Like Paul Denisevich says, javascript is client side, PHP is server side, so as far as restricted.php is concerned, your ajax request could be coming from anywhere. Although you say that you want "other php files" to be able to access it, I get the impression that you want your ajax to be able to access it, but you don't want other client side scripting to be able to access it. You don't want someone to be able to load the file directly, like http://example.com/restricted.php.
You need a piece of information that index.php and restricted.php both know about, but an outsider will not, then hash it. I don't know what information you might have available to these scripts. If there is a user logged into this, maybe you want to hash the users name and date of birth or something. It would be good to use something from a database that is never output to the UI and include that in the hash.
For example purposes, maybe I'll just have a file:
<?php
$key = "some string" . date('DNi');
// weird date format that changes every minute. This is no good for production as
// the minute may tick by during the request from the ajax to restricted.php. You
// are better off using some values from a database that are not shown anywhere.
?>
in both index.php and restricted.php:
require_once('hash.php');
in your ajax:
$.ajax({
url: "restricted.php",
dataType: "text",
data {hash:"<?php echo md5($key) ?>"},
success: function(data) {
//use data
}
});
then in restricted, something like:
if($_GET['hash'] == md5($key)) {
// do your thing and send some output for ajax to use
} else {
// bail
}