Sam Pritchard
Sam Pritchard

Reputation: 5

How to block users from directly accessing a page, but not HTTP requests in PHP?

Before I start, I hope that this question isn't that badly written. My last questions got negative attention due to the sheer ugliness of the question formatting. Either way, here's my question:

I'm making a program where I have to send GET requests to my domain to get information and statistics, etc. Though, my problem is: how would I efficiently (and in PHP only) stop the typical user/person/cat/etc from accessing my page, and only let HTTP requests in?

Example: I send a GET request to "foo.php" on my domain from an external program. User knows I'm getting content from the page and tries to visit the page itself directly.

How would I stop the user from seeing the page in their browser directly, but perfectly allow HTTP requests (such as GET requests) to fetch my content?

Upvotes: 0

Views: 59

Answers (2)

AleFranz
AleFranz

Reputation: 771

Actually a browser is also sending a HTTP GET request, so you need a different approach to distinguish between a GET made buy your script/service and one from a browser.

You have a lot of different approaches, here 2 possible solutions:

A) Use a particular user agent when you do your get request. This is the de-facto standard for monitoring services to identify the request.

if ($_SERVER['HTTP_USER_AGENT'] != "your_user_agent") {
    die();
}

B) Use a special token to authorise your request

// if you like to send the token as parameter like foo.php?auth=bar
if ($GET['auth'] != "your_token") {
    die();
}

// or use this if you like to send it as a header named auth
if ($_SERVER['auth'] != "your_token") {
    die();
}

Upvotes: 1

redreddington
redreddington

Reputation: 408

Easiest way would be to add a condition in foo.php that checks for the $_GET parameter and then stop at that point.

if (!isset($_GET)) {
   die();
} else {
  // Regular programming 
}

Of course that doesn't then someone from visiting foo.php?doesthisvariablework=1and getting through.

Upvotes: 0

Related Questions