views:

946

answers:

4

I am trying to make a basic API for my website so certain other websites that I approve of can show content from my site. I have a PHP script on my server that the other websites can access to pull content in XML format. How can I make sure that only certain websites can access this php page on my server?

+4  A: 

Most APIs that need a similar sort of "authentication" opt for API keys. Just a big long string that gets passed through in the request.

You can reinforce that by resolving the domain's IP and checking that against the incoming request. This is slow and expensive so cache IP lookups (but make sure you clean them out as domain IPs do legitimately change!)

Oli
+4  A: 

Allowing only specific users by IP address is pretty simple with .htaccess.

Normally you use it to block specific IP addresses like this

Order allow, deny
Deny from 192.168.0.10
Deny from 212.155.
Deny from 1.2.3.4  5.6.7.8 127.0.0.1
Allow from all

But you can also use it to only allow access from specific users, like this

Deny from all
Allow from 1.2.3.4

EDIT: If you absolutely need to do this from a script (upon second careful reading of your question, I think you do), then you can do it like this.

<?
    $allowed[0]="xxx.xxx.xxx.xxx";
    $allowed[1]="yyy.yyy.yyy.yyy";

    // add as many as you need

    if (!in_array($_SERVER['REMOTE_ADDR'],$allowed)) header("HTTP/1.1 403 Forbidden");
?>
Bill the Lizard
+2  A: 

A simple option would be to put the pages into a directory and then turn on basic HTTP authentication. You would issue usernames & passwords to those you want to be able to access the content.

A url can encode the username and password as: http://username:password@hostname/...

This way no changes are needed on your end beyond modifying the .htaccess file or the remote end, other than specifying a slightly different url.

The usernames and passwords are passed in cleartext over the internet, so you need to decide if that is an acceptable risk.

Rob Walker
The normal way of getting past the fact that it's sent in cleartext is either to use digest auth instead of basic, or use https. Either solution is acceptable and secure.
Matthew Scharley
A: 

Thanks for the quick help guys, these all look like very good ideas! Unfortunately I can't post a comment or vote up your posts because I am too new a member or something.