How can I prevent a page from loading if there is no javascript, but using php instead of <noscript>?

1.7k views Asked by At

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

There are 3 answers

0
tckmn On

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.)

2
Funk Forty Niner On

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>
0
Paul S. On

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.