Check if JavaScript is enabled with PHP

Is there a way to check if JavaScript is enabled with PHP? If so, how?

+50
javascript php
Dec 15 '10 at 20:27
source share
25 answers

No, this is impossible, because PHP is a server language, it does not have access to the client’s browser in any way or form (client requests from the PHP server).

The client may provide some meta-information via HTTP headers, but they do not necessarily tell you whether the JavaScript user is enabled or not, and you cannot rely on them anyway.

+47
Dec 15 '10 at 20:29
source share

perhaps a simpler option ...

<html> <head> <noscript> This page needs JavaScript activated to work. <style>div { display:none; }</style> </noscript> </head> <body> <div> my content </div> </body> </html> 
+60
Feb 29 2018-12-12T00:
source share

Technically not, because other answers said, PHP is strictly connected to the server, but you could do it ...

On the PHP page, the server displays (a lot of HTML has been removed for brevity)

 <html> <head> <script type="text/javascript" src="jquery1.4.4.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.get("myPage.php"); }); </script> </head> </html> 

Then in myPage.php set the session variable to indicate that the client supports JS

 <?php session_start(); $_SESSION['js'] = true; ?> 

But really just use the <script></script><noscript></noscript> tags, much less effort ...

+18
Dec 15 '10 at 20:34
source share

// Here is the solution: // works fine

 <?php if(!isset($_SESSION['js'])||$_SESSION['js']==""){ echo "<noscript><meta http-equiv='refresh' content='0;url=/get-javascript-status.php&js=0'> </noscript>"; $js = true; }elseif(isset($_SESSION['js'])&& $_SESSION['js']=="0"){ $js = false; $_SESSION['js']=""; }elseif(isset($_SESSION['js'])&& $_SESSION['js']=="1"){ $js = true; $_SESSION['js']=""; } if ($js) { echo 'Javascript is enabled'; } else { echo 'Javascript is disabled'; } ?> 

// And then inside get-javascript-status.php:

 $_SESSION['js'] = isset($_GET['js'])&&$_GET['js']=="0" ? "0":"1"; header('location: /'); 
+9
Oct 29
source share

You cannot determine if the browser is enabled in JS, but you can find out if the browser supports JS http://php.net/manual/en/function.get-browser.php

$js_capable = get_browser(null, true)=>javascript == 1

Having said that, probably not very much. You should redefine JS detection from PHP. There should not be a need if you use progressive improvement , which means that JS only adds functionality to what is already on the page.

+6
Dec 15 '10 at 20:45
source share

Here is the small part I made up that I have on top of my pages to determine if js is enabled. Hope this helps ...

 <?php //Check if we should check for js if ((!isset($_GET['jsEnabled']) || $_GET['jsEnabled'] == 'true') && !isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ //Check to see if we already found js enabled if (!isset($_SESSION['javaEnabled'])){ //Check if we were redirected by javascript if (isset($_GET['jsEnabled'])){ //Check if we have started a session if(session_id() == '') { session_start(); } //Set session variable that we have js enabled $_SESSION['javaEnabled'] = true; } else{ $reqUrl = $_SERVER['REQUEST_URI']; $paramConnector = (strpos($reqUrl, "?"))? "&" : "?"; echo " <script type='text/javascript'> window.location = '" . $reqUrl . $paramConnector . "jsEnabled=true' </script> <noscript> <!-- Redirect to page and tell us that JS is not enabled --> <meta HTTP-EQUIV='REFRESH' content='0; " . $reqUrl . $paramConnector . "jsEnabled=false'> </noscript> "; //Break out and try again to check js exit; } } } ?> 
+4
Mar 21 '13 at 1:04 on
source share

You can try using 2 method:

  • setting cookies with JS and detecting them from PHP
  • creating a form with a hidden field and an empty value; and then assigns it some value using JS, if the field receives a value - JS is ON, otherwise turn it off. But the form had to be submitted first before PHP could request the value of the hidden fields.

if you want to determine whether to allow JS to enable the setting before loading the page you can try (I don't know if it works):

 <?php if (isset($_POST['jstest'])) { $nojs = FALSE; } else { // create a hidden form and submit it with javascript echo '<form name="jsform" id="jsform" method="post" style="display:none">'; echo '<input name="jstest" type="text" value="true" />'; echo '<script language="javascript">'; echo 'document.jsform.submit();'; echo '</script>'; echo '</form>'; // the variable below would be set only if the form wasn't submitted, hence JS is disabled $nojs = TRUE; } if ($nojs){ //JS is OFF, do the PHP stuff } ?> 

there is a good tutorial on this issue at http://www.inspirationbit.com/php-js-detection-of-javascript-browser-settings/

+3
Dec 15 '10 at 20:53
source share
 <noscript> <?php if(basename($_SERVER['REQUEST_URI']) != "disable.html"){ ?> <meta http-equiv="Refresh" content="0;disable.html"> <?php } ?> </noscript> 

Put the above code in your header file after the header tag and set the appropriate value for it as [disable.html].

+3
Feb 26 '14 at 11:03
source share
 <html> <head> <?php if(!isset($_REQUEST['JS'])){?> <noscript> <meta http-equiv="refresh" content="0; url='<?php echo basename($_SERVER['PHP_SELF']);?>?JS='"/> </noscript><?php } ?> </head> <body> <?php if(isset($_REQUEST['JS'])) echo 'JavaScript is Disabled'; else echo 'JavaScript is Enabled'; ?> </body> </html> 
+3
Mar 21 '16 at 21:49
source share

before trying to disable javascript browser ...

after that

Try this code:

 <html> <head> <noscript><meta http-equiv="refresh"content="0; url=script-disabled.html"> </noscript> <h1>congrats ! Your Browser Have Java Script Enabled </h1> </head> </html> 

Write something in script -disabled.html

his job

+3
Mar 24 '17 at 5:43 on
source share

PHP cannot be used to determine if javascript is included or not. Instead, use <noscript> to display an alternate message / do something.

+2
Dec 15 '10 at 20:30
source share

To get rid of bots with JS disabled:

 <?php session_start(); @$_SESSION['pagecount']++; ?> <html> <head> <?php if (!isset($_COOKIE['JSEnabled']) || strlen($_COOKIE['JSEnabled'])!=32 ) { $js_cookie=md5(md5(@$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']); echo '<script language="javascript">'; echo 'document.cookie="JSEnabled=' . $js_cookie . '"'; echo '</script>'; echo '<meta http-equiv="refresh" content="0;url=http://example.com"/>'; } ?> <?php $js=$_COOKIE['JSEnabled']; if ($js!=md5(md5(@$_SESSION['pagecount']-1) . $_SERVER['REMOTE_ADDR'])) { $js_cookie=md5(md5(@$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']); echo '<script language="javascript">'; echo 'document.cookie="JSEnabled=' . $js_cookie . '"'; echo '</script>'; echo "</head><body>Sorry, this website needs javascript and cookies enabled.</body></html>"; die(); } else { $js_cookie=md5(md5(@$_SESSION['pagecount']) . $_SERVER['REMOTE_ADDR']); echo '<script language="javascript">'; echo 'document.cookie="JSEnabled=' . $js_cookie . '"'; echo '</script>'; } ?> 

No one can use, for example, curl -H "Cookie: JSEnabled = XXXXXXXXXXXXXXXXXXX" because they do not know your hash calculation algorithm.

+2
Jun 27 '15 at 11:22
source share

This is how I check if javascript and cookies are enabled or not http://asdlog.com/Check_if_cookies_and_javascript_are_enabled

I copy / paste it here

 <? if($_SESSION['JSexe']){ //3rd check js if($_COOKIE['JS']) setcookie('JS','JS',time()-1);//check on every page load else header('Location: js.html'); } //2nd so far it been server-side scripting. Client-side scripting must be executed once to set second cookie. //Without JSexe, user with cookies and js enabled would be sent to js.html the first page load. elseif($_COOKIE['PHP']) $_SESSION['JSexe'] = true; else{ //1st check cookies if($_GET['cookie']) header('Location: cookies.html'); else{ setcookie('PHP','PHP'); header('Location: '.$_SERVER['REQUEST_URI'].'?cookie=1'); } } ?> <head> <script type="text/javascript">document.cookie = 'JS=JS'</script> </head> 
+1
Aug 09 '12 at 17:40
source share

Recently, I have had the following dilemma:

I am using a PHP function that generates a QR image associated with the current URL, which is very useful for mobile devices. The function works fine, but having my site on shared hosting, there are some restrictions on the use of CPU and RAM. This feature is heavy, and it consumes a lot of processor time and RAM, so the hosting guys asked me to reduce the use.

After some attempts, I finally got to the idea that I can save CPU and RAM from bots in search engines. It is difficult to recognize the bot by browser ID, but all the bots do not have JS, and what are the main criteria that I used to determine if it is a real browser or is it a bot. To explain how important it is to prevent the execution of code that will not work for search engines (QR, in my case, does not affect search engines), I can say that only the Google bot, for example, is about 16,000 crawls per day on my site.

So, I did a very simple thing that really helped:

 <script language="javascript"><!-- document.write('<?php echo drawQR($_SERVER["REQUEST_URI"]);?>'); //--></script> 

This code uses JS to write a line of PHP code, so this line will only be written with JS enabled.

From couse, you can use the "noscript" tag if you want to show something when JS is disabled, but this method shows how to execute some PHP only with JS enabled.

Hope this helps.

+1
Sep 20 '12 at 17:01
source share

Create a cookie using JavaScript and read it using PHP.

+1
Sep 11 '14 at 0:03
source share

Please, despite the fact that all people say that you cannot test the technology of client scenarios. If the target technology has http functions, you can ALWAYS do it, just write down the verification step. That means, literally, the way to test javascript is to run javascript. If javascript is disabled on the browser side, it is not possible to check whether the client supports Javascript (for example, Dillo with its default configuration or others)

UPDATED: I developed this script because I am testing some of the examples here and it seems that everyone is doing copypasting without any tests. The code is also located in Gist https://gist.github.com/erm3nda/4af114b520c7208f8f3f ( updated )

 //function to check for session after|before PHP version 5.4.0 function start_session() { if(version_compare(phpversion(), "5.4.0") != -1){ if (session_status() == PHP_SESSION_NONE) { session_start(); } } else { if(session_id() == '') { session_start(); } } } // starting the function start_session(); // create a script to run on the AJAX GET request from :P Javascript enabled browser echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.get(document.URL.substring(0, document.URL.length-1) + "?sessionstart=1"); console.log(document.URL.substring(0, document.URL.length-1) + "?sessionstart=1")} </script>; // Ajax GET request handle if ($_REQUEST['sessionstart'] == 1){ $_SESSION['js'] = 1; // save into session variable } else { session_destroy(); // force reset the test. otherwise session } // If the session variable has not saved by the AJAX call, loads again. if (!isset($_SESSION['js'])){ header("Refresh: 1"); // thats only for the first load echo "Javascript is not enabled <br>"; // Return false } else { echo "Javascript is enabled <br>"; // Return true } 

No more files are needed for this solution, just iterate if you launch a browser that supports JavaScript. The value is passed back to PHP using GET with a simple variable, but can anyone fake the output by doing cURL on url +? Sessionstart = 1, unless you add more logic to it.

+1
Mar 19 '15 at 2:55
source share

With this basic ajax, you can split the data that the client sees based on javascript or not.

index.php

  <!DOCTYPE html> <html> <body> <script> function jsCheck() { var xhttp; if (window.XMLHttpRequest) { // code for modern browsers xhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 && xhttp.status == 200) { document.getElementById("demo").innerHTML = xhttp.responseText; } }; xhttp.open("GET", "jscheckCon.php", true); xhttp.send(); } jsCheck(); </script> <div id="demo"> no javascript </div> </body> </html> 

jscheckCon.php

 <?php echo 'we have javascript!';//you can do that you like to do with js! ?> 
+1
Nov 26 '15 at 20:28
source share

Turn your jscript PHP main page off and add <script> to redirect to a jscript-enabled app in <head> . If the user is really using your first page, suppose jscript is disabled.

0
Dec 15 2018-10-1520:
source share

Another option: If you do not need to check if JS is enabled on the first visitor presentation (main page), you can set a cookie using js. On the next page you can check with php if the cookie exists ...

0
Apr 18 2018-12-18T00:
source share

You can use logic logic (default / switch) - this is an example, I printed a variable in php:

PHP:

 $js = 'No'; print 'Javascript Enabled: &lt;span id="jsEnabled"&gt;'.$js.'&lt;/span&gt;'; 

JS: (in my document ready)

 jQuery('#jsEnabled').text('Yes'); or $('#jsEnabled').text('Yes'); 
0
Aug 6 2018-12-12T00:
source share

You can set a cookie using Javascript and then reload the page using Javascript. Then, using PHP, you should check if the cookie is set if it is enabled Javascript!

0
Oct 21 '12 at 10:57
source share

Its 2013. Just try the script to display non-js templates inside the body > noscript tag and then inside your CSS save your main container js site display: none; After that, just put something like <script>$('#container').show();</script> immediately after closing the main # container div and before the noscript tag. (unless of course you use jquery).

Performing this method will automatically show HTML for browsers that do not support js, and then browsers that support js will only see the js site.

If you are worried about over-inflating the page size with too much markup, then you can do the same, but instead leave the <div id="content"></div> empty and then with the js code instead of just show div, use ajax call to get content for it.

On the side of the note, I would probably include additional css files for the non-js site in the noscript tag to save on bandwidth.

0
May 09 '13 at 19:16
source share

Since PHP is the server side, you cannot know in PHP whether Javascript is enabled if you are not using sessions (or any other way to store data on requests) and first send the code to which the client responds.

If you put the following at the beginning of your PHP file, the client is redirected to the same URL with "js = 0" or "js = 1" added to the query string, depending on whether Javascript is enabled or not. After receiving a redirected request, the script writes the result to the session variable, and then redirects back to the original URL, i.e. Without added "js = 0" or "js = 1". Having received this second redirect, the script is executed as usual, now with a session variable set in accordance with the capabilities of Javascript clients.

If you are not interested in what the query string looks like in the user address bar, you can skip the second redirect and just set the session variable. Although these redirects occur, the user is shown a short informative message (you can also skip if you are not interested).

 <?php session_start(); if (!isset($_SESSION['js']) && !isset($_GET['js'])) { $url=$_SERVER['SCRIPT_URI']; $qry='?'.($q=$_SERVER['QUERY_STRING']).($q?'&':'').'js'; die('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>js check</title>'. '<script type="text/javascript">window.location.href="'.$url.$qry.'=1";</script>'. '<noscript><meta http-equiv="refresh" content="0; url='.$url.$qry.'=0" /></noscript>'. '</head><body>Hold on while we check whether you have Javascript enabled.</body></html>'); } elseif (isset($_GET['js'])) { $_SESSION['js']=$_GET['js']; $qry = preg_replace('%&?js=(0|1)$%', '', $_SERVER['QUERY_STRING']); $url = $_SERVER['SCRIPT_URI'].($qry?'?':'').$qry; die('<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>js check</title>'. '<meta http-equiv="refresh" content="0; url='.$url.$qry.'" />'. '</head><body>Hold on while we check whether you have Javascript enabled.</body></html>'); } if ($_SESSION['js']) { //Javascript is enabled } else { //Javascript is disabled } ?> 
0
Jan 09 '14 at 5:04
source share

if you check when the page loads for the first time, this may start php:

 <noscript> <?php //your php code here ?> </noscript> 
0
May 01 '19 at 20:06
source share

Yes.

Make sure you have the latest jQuery.js

 //javascript $(function(){ $('#jsEnabled2').html('Yes it is') }) //php $js - 'No'; $jscheck = 'Javascript Enabled: '; $jscheck .= '<span id="jsEnabled">'.$js.'</span>'; print $jscheck; 
-four
Sep 23
source share



All Articles