How to prevent a PHP page from being accessed directly?
ajax, javascript, php, token
Solution
There is no point in protecting javascript code, you need to protect only the server-side code.
Anyway, I think your approach is not the right one; if you already have a logged-in user / a user ID, I would just use the user ID from the session instead of a user ID that is supplied by the javascript. That way there is no way anybody can tamper with it.
So you could start your page with:
session_start();
if (isset($_SESSION['user_id'))
{
// do stuff with the user ID
}
else
{
// display error message?
}
Problem
Below is a javascript snippet that I am using as part of a AJAX script. How do I prevent user_back_end_friends.php from being accessed directly? I don't want people to be able to go to domain.com/user_back_end_friends.php and see a list of friends. Javascript Code: ``` <script type="text/javascript"> $(document).ready(function() { $("#user_friends").tokenInput("/user_back_end_friends.php", { theme: "sometheme", userid: "<?php echo $id; ?>" }); }); </script> ``` This is what I found but not sure how to implement it with the javascript code above: I use this in the page I need to call it in: ``` $included=1;include("user_back_end_friends.php"); ``` When I have to prevent direct access I use: ``` if(!$included){ die("Error"); } ``` But how do I add this $included part of the script in my javascript code?