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.

davideakc
  • 49
  • 1
  • 9
  • 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 – Nicolas Racine Apr 12 '16 at 18:12

1 Answers1

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
}
Adam Lynch
  • 331
  • 2
  • 6