开发者

Is it possible to check whether a request is from <script> tag in PHP?

<script src="test.php"></script>

I want my test.php execut开发者_如何学JAVAed only when it's from <script>, is it possible?


No, that's not possible. Stuff in the <script> tag just gets requested as normal pages and (AFAIK) no browser sends any special headers or anything that would help you (reliably) identify it's coming from a <script> tag.

Perhaps if you explained why you want to do this, we could come up with a better solution?

I'll go ahead and warn you that if you plan on using this to stop people from seeing or copying your JS source code, forget about it. There is just no way to do that. JS code has to be available to the browser, which means it'll be available to the user as well.


The browser will usually send a "Referer" (sic) header for script requests which contain the URL of the page that containing the script link, regardless of how that script element was created.

This is accessible by checking the $_SERVER['HTTP_REFERER'] variable (note unusual spelling) in PHP.

The idea is that you can check this variable and see if it refers to part of your site.

Note that this variable is not always accurate; a user may elect to protect their privacy by not sending a referer header (using some sort of dinky privacy tool) and they may even modify their browser to send whatever they want in this field. So it shouldn't be relied upon for authentication, unless you also take into account that even a legitimate user may have left it blank or put an arbitrary string in it.


what if "test.php?source=script">?

Edit: Testing the referrer solution $_SERVER['HTTP_REFERER'] and $_SERVER['HTTP_USER_AGENT'] results below

localhost/a.php calls testjs.php

in a.php (caller) <script type="text/javascript" src="testjs.php"></script>

in testjs.php

document.writeln("<p><?php echo $referrer = $_SERVER['HTTP_REFERER'];?></p>");
//outputs http://localhost/a.php

document.writeln("<p><?php echo $browser = $_SERVER['HTTP_USER_AGENT']?></p>");
// outputs //Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.9) Gecko/20100824 Firefox/3.6.9

Am I missing where it says its a call from script src?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜