2

I've created an API in my site in PHP

Now I want to protect it because I don't want that other sites and/or users can call it from a website that it isn't mine

The calls can be made only from my site

How can I do?

Thanks.

1
  • There is multiple way to do that, You could simply create a hardcoded password that you have to supply with the credential Or have only static IPs Commented Apr 12, 2016 at 18:12

1 Answer 1

2

You can just use this at the start of your API

if($_SERVER['REMOTE_ADDR'] != '127.0.0.1'){
    die;
}

It will kill any API attempts that aren't being called from your server.

Edit

Or if you want users to be able to call the API, you can gave them an API key, that you will store in your database.

Ex.

$con = mysqli_connect("localhost","my_user","my_password","my_db");
$key = mysqli_real_escape_string($con, $_GET['key']);
$search = mysqli_query("SELECT * FROM user WHERE api_key = '$key'");
if(mysqli_num_rows($search)==0){
    // kill the request
    die;
}
else{
    // Allow the request and do your business
}
Sign up to request clarification or add additional context in comments.

3 Comments

the problem is that the users can call the API (it's a registration confirm) and the $_SERVER['REMOTE_ADDR'] tag needs to match site's IP, not user's IP, in your suggestion...
127.0.0.1 is your site's server ip, not the user's. Why not just make an API key?
I've edited my answer to show you a way of accepting API keys.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.