Secure PHP to be accessed by other site

Viewed 51

I have a PHP page where only other sites can access for polling (sort of like a webhook). I don't want any users to try to access/visit it. How can I make sure it is accessed by a specific source/way?

For example:

When the website checks for new data on my site, they will visit a page called check.php. They will be sending POST and GET info to check. Here is an example code I have for that page:

<?php
if(empty($_GET['name']) || empty($_GET['email']) || $_POST['secret-code'] !== 'abc123') {
    echo "error";
    exit();
} else {
    $name = $_GET['name'];
    $email = $_GET['email'];
    echo 'Here is the info you requested...';
}
?>

How can I secure this even more? I want to make sure no one can access this if they were to send their own $_GET and $_POST parameters to request data. Anything I can do with code or even headers? Thank you for any help

2 Answers

One option would be to verify the specific user data from the request, such as a predetermined password or key. This is the least secure method.

Another option would be to only allow network connections from a single source. You could do this by checking the IP of the client each time they make a request. If you take this route make sure to verify by password as well since IP spoofing is possible.

An even more secure way would be to take a part of the client information request and send it right back to the client, verifying that they sent you this information (this would be like 2-factor authentication).


The most secure method would be having the client create a cryptographically signed key, which you could then verify only could have been signed by them.

This could be done using the openssl_sign() and openssl_verify() functions.

Why not just use a token that you can store on your database and read it from the headers just like an API?.

You can just check if the header exists and have the token value and check against your database that the token is valid and you can do some other things like logging the requests and stuff like that and add new tokens easily.

If the header doesn't exists and the token is not valid, then, remove the access...

Or, you can do an "ip whitelist" so only the requests from certain IPs can pass or domains like a "CORS" but limited to certain IPs and domains.

Because in that way is easier to manage the access to certain users on your service. Another options (including the safer) is like @shn said.

Related