<script src="test.php"></script>
I want my test.php
executed 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With