简体   繁体   中英

Is there a way to make sure PHP is being loaded only by JS?

Is there a way to make a PHP file so that it can only be loaded and executed by the Javascript code that I write? Ie can I make sure that someone can't read my JS, load up the PHP page in their browser with their own variables, and make unauthorized changes to my database? Any help much appreciated.

No.

You can check if $_SERVER['HTTP_X_REQUESTED_WITH'] is set and equals "XMLHttpRequest", but this is just an HTTP header that can be faked.

Javascript just makes standard HTTP requests which can be reproduced in any number of ways. HTTP is a very simple protocol that does not offer the possibility to distinguish between clients in any reliable way. Identical requests are identical. You need to build your user identification and authorization scheme yourself on top of HTTP, it's not part of the protocol. The server needs to decide and enforce what is authorized and what isn't based on rules (that you establish), not on who asked.

Is there a way to make a PHP file so that it can only be loaded and executed by the Javascript code that I write?

Not reliably, no. Any request can be forged on client side. This method is not acceptable to establish security. You will have to use some kind of authentication on server side.

No. It is simple to write a 10 line program in eg Python, to spoof any useragent. You can not ever trust anything that any user sends you ever under any circumstances.

Doing so will bring shame on your entire family, all of your ancestors and cause your descendents to be forever stigmatized as the offspring of "that guy".

Maybe you can check the request header sent by Javascript. AJAX calls should send this line:

X-Requested-With: XMLHttpRequest

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