2

I have a page with php and other stuff in the code. What I need to do is a way to check with php if there is javascript enabled in the browser. This way, the whole page source will be prevented to be loaded, instead of using that only prevents the page from loading, but allows the source code.

3
  • 4
    Why? What's wrong with <noscript>? Commented Aug 31, 2013 at 14:14
  • Hehe.. you were 1 second earlier! Commented Aug 31, 2013 at 14:14
  • I think the same question has asked here : stackoverflow.com/questions/4454551/… Commented Aug 31, 2013 at 14:16

3 Answers 3

6

PHP is a server-side language. There is no way to do this with PHP since it is run on the server, and then the result is sent to the client. The server has no knowledge of whether the client has JavaScript enabled or not.

If you don't want to show the code in your .html file when JS is disabled, then you don't have to use PHP. You could put the essential stuff in the .html file and load the rest in with JavaScript. If JavaScript is disabled, the rest of the stuff never gets loaded in the first place. (This is called progressive enhancement.)

Sign up to request clarification or add additional context in comments.

Comments

2

This example will use the <noscript></noscript> tag inside an echo directive.

<?php

echo "<noscript>You need JS enabled to view the text on this page.</noscript>";

?>

<!DOCTYPE html>

<html>
<head>

</head>

<body>

<script>
document.write("<h1>Heading Text</h1>");
document.write("<p>This message appeared because you have JS enabled.</p>");
</script>



</body>

</html>

2 Comments

what browser you are using? version?
@itachi Strange indeed. Seems like "Standards" just aren't as they used to be, "conform".
0

You could make JavaScript fire a request to a page, setting a session variable enabling access to the website, then reload the page. This is by no means secure.

In all files except enable.php (could be done via an include/etc) before anything is echoed.

...
if (!isset($_SESSION['enabled']) { ?>
<!doctype html>
<html>
    <head>
        ...
        <script>
var xhr = new XMLHttpRequest();
xhr.open('GET', '/enable.php', false);
xhr.send();
window.location.reload();
        </script>
    </head>
    <body></body>
</html>
<?php die();
}
....

In enable.php, you would then do

$_SESSION['enabled'] = 1;

enable.php would only need to be hit once-per-session and if JavaScript was disabled afterwards, or it was hit manually by pointing the browser there, your server will not know the difference. The assumption is the client must have JavaScript enabled for this session if the page was reached this session.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.