开发者

how can i know if a php file was only called from js on the client side?

I have a javascript on my webpage which makes a call to a php file and passes some value开发者_如何学Pythons to the php file. How can i know for sure that the call to the php file was from the js on my webpage and not directly entering the php url from the browsers address bar?


You'll want to use check if $_SERVER['HTTP_X_REQUESTED_WITH'] is XMLHttpRequest. That will prevent people from directly typing the URL in their browsers while allowing Ajax requests.

if ( ! empty($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' )
{
  // Do something useful
}

You might want to see Do all browsers support PHP's $_SERVER['HTTP_X_REQUESTED_WITH']? for an explanation of what browsers/JavaScript libraries send the HTTP_X_REQUESTED_WITH header.


you can use the following info:

  1. The headers that are being sent (usually Ajax calls adds special headers)
    X-Requested-With: XMLHttpRequest
  2. refering URL in the $_SERVER

Both can be hacked though.

If you need a very safe solution, you need to create a unique code for each request and send it to the server from your JS. This code needs to change after each time it is used.


You can't. Anything you expose to ajax you expose to the world. What's more is that someone wanting to get into that page could just run their own javascript on the page anyway and spoof any HTTP headers they want. These are the people you presumably want to keep out anyway. You shouldn't use measures that will limit non-malicious users but provide relatively little, if any, trouble to malicious users.

That said, I have never heard of HTTP_X_REQUESTED_WITH and based on preliminary reading it's not a good idea to use. I usually use POST and check that the _SERVER[REQUEST_METHOD] is POST because most modern browsers will use GET for any requests made by the url bar (that's my experience anyway). Again, this is not to keep bad people out, it's just to prevent accidents.

Another measure you should take is to check that a flag is sent to the page to help signal it's coming from a verified source. Depending upon how secure the ajax page is supposed to be, you may also want to verify session, etc. A somewhat safe way is to create a unique hash (e.g. md5) and store it in the DB with a timestamp. That hash indicates the page can be visited, say, up to three times. When the user clicks your ajax link, it sends the hash. The hash is flagged as consumed and cannot be reused. The hash should also go stale some time after creation (5 minutes? It depends and it's up to you).

Finally, make sure that this page is ignored by friendly robots (robots.txt, meta if possible, etc.). This will prevent people reaching it accidentally via search engines.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜