Getting the domain that calls an PHP file on your server through AJAX

后端 未结 2 1923
感动是毒
感动是毒 2020-12-17 04:56

I\'m building out an API and have a question about how to track/know which domains use the call.

The API call is built in PHP, and doesn\'t require any authenticatio

2条回答
  •  借酒劲吻你
    2020-12-17 05:25

    You could generate a hash based on the domain name, and let the users of your API send the domain name and the hash in each request. Now since you're API uses PHP you'll have set the 'Access-Control-Allow-Origin' somewhere in the header. If you do this in PHP you can play around with that a bit. The script below is a simple example of an implementation that doesn't require php on the caller side (domain that uses you're API).

    Caller Side (no php required):

    
    

    Ajax Server Side (PHP):

    
    

    This way the header would also be placed if the call came from a malicious domain, but rest will bounce because of a Cross Origin Exception, and thus no result will be given.

    For the sake code space I used a md5 hash in this example, but you could use more complex hashes if you want. Note that you should (as always) keep the used salt secret.

    I put a working example online at the following (sub)domains. The pages are identical.

    cors1.serioushare.com - Only works on 'CORS 1' button.
    cors2.serioushare.com - Only works on 'CORS 2' button.

提交回复
热议问题