I'm trying to deny direct url access to a php file that is called upon ajax for form validation. The code I currently have works up until the form is validating, which then it doesn't work. I DON'T want to use .htaccess.
Current code:
<?php
$url = strtolower(basename($_SERVER['PHP_SELF'])); // Gets url (parent that uses the include)
$fil = strtolower(basename(__FILE__)); // gets filename (the included file)
if ($url == $fil){
// if they are the same (file is accessed through url
// redirect to forbidden page
header("HTTP/1.0 403 Forbidden");
exit;
}
// require my configuration
require_once("config.php");
// code to be executed for ajax validation
$username = $_POST['username'];
$conn = mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
mysql_select_db(DB_NAME,$conn) or die(mysql_error());
$query = mysql_query("SELECT * FROM " . TB_USER . " WHERE username = '{$username}'",$conn) or die(mysql_error());
$result = mysql_num_rows($query);
mysql_close($conn);
if ($result == 0){
echo "true";
}else{
echo "false";
}
?>
If I access the file directly from url, it redirects like planned, but when the form is being validated via ajax, it doesn't do anything if the username is unavailable. Taking out the first two lines of code ($url, $fil) as well as the if statement makes the ajax validation work, but the page is not denied on url access. Any suggestion on what to do from here?