That's a good question. It depends on how and when the PHP script is being called.
You can do it anytime that you know that the PHP script is being called from a link on your page. You can make it work everytime if you are willing to play some Javascript tricks.
Consider two ways of accessing a page on your site:
- user types in a url in their web browser.
- user clicks a link on your page
In situation 1, we have already established that the browser does not announce to the PHP script whether or not JS is active so no, the PHP would not know whether or not to execute.
In situation 2, you can include a variable in the link maybe "javascript=no". Then you can use Javascript to change the value of that variable to "javascript=yes" and the PHP script would know whether or not to execute.
But then if you wanted to play some games with Javascript, you could probably make situation 1 work if you put a meta refresh in the page that forced a page to redirect to another page essentially forcing the page to report back to the server. So hypothetically, if the user types http://www.yourdomain.com into their browser, you could have an index.html page that displays, Javascript code that sets a variable, and then a meta refresh that forces the page to redirect to another page (maybe index2.php). Then, index2.php should be able to check for the presence of that variable and know whether or not JS is present in the browser.
I've never tried that but it should work as long as you can write some Javascript that is able to modify the URL in the metarefresh before the metarefresh happens.
If that works, you might find that the timing (or order of operations) might vary from browser to browser which would cause a situation where sometimes you are able to tell that JS is present and sometimes the PHP gets the wrong information.
But all of that applies to situation 1 only.
In situation 2, the timing and the order of operations are irrelevent so you will always get a correct reading of when JS is present.
So now you need to determine whether or not this function can be limited to just pages where the user is clicking a link on your page.
What I would do is this:
write a header that gets included on every page
in the header, check for the presence of a cookie called "JS_enabled"
if no cookie, then make a form, use JS to set a variable in the form
tell the user that they must click the button to continue
in the header, check for the presence of that form's message
if it's there, set a cookie called JS_enabled
then have the page perform as desired (that is, the PHP executes if no JS present)
That way, you are forcing the user to do an extra step the first time they are at the site but then you have a clean way of knowing whether or not they have JS after that. Of course, this would make your web site useless to anyone without cookies turned on. 🙂 (but who needs those people anyway!)