简体   繁体   中英

Allow only certain websites to access a PHP page

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?

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!)

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");
?>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM