Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

php

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

I want my test.php executed only when it's from <script>, is it possible?

like image 833
COMer Avatar asked Dec 28 '22 07:12

COMer


2 Answers

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.

like image 132
NullUserException Avatar answered Dec 30 '22 21:12

NullUserException


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.

like image 30
thomasrutter Avatar answered Dec 30 '22 19:12

thomasrutter