1

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.

4

3 回答 3

5

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

于 2013-08-31T14:13:39.803 回答
1

此示例将使用指令中的<noscript></noscript>标记。echo

<?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>
于 2013-08-31T14:39:08.673 回答
0

您可以让JavaScript触发对页面的请求,设置会话变量以启用对网站的访问,然后重新加载页面。这绝不是安全的。

在所有文件中,除了enable.php(可以通过包含/等完成)之前,任何内容都被回显。

...
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();
}
....

enable.php,然后你会做

$_SESSION['enabled'] = 1;

enable.php每个会话只需要点击一次,如果JavaScript之后被禁用,或者通过将浏览器指向那里手动点击,您的服务器将不知道其中的区别。假设如果页面在此会话中到达,则客户端必须为此会话启用JavaScript 。

于 2013-08-31T14:55:40.220 回答