Check if JavaScript is enabled with PHP
Asked Answered
E

24

52

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

Ergocalciferol answered 15/12, 2010 at 20:27 Comment(4)
Nope. Well. Not on the first visit. On the second+ yes. Use AJAX to set a session var. If it is set on page 2, you have JS. If not, you don't. This could work on a front login page... but if you need it on the first page load, you can't have it.Loment
Even if it's set in a variable session, you can disable it after. So it's unreliable.Derwent
Agree with @DampeS8N. I've made this simple script to check for. https://mcmap.net/q/342047/-check-if-javascript-is-enabled-with-php (an answer below link).Dishrag
Possible duplicate of What is the difference between client-side and server-side programming?Forras
S
50

No, that is not possible, because PHP is a server side language, it does not access the client's browser in any way or form (the client requests from the PHP server).

The client may provide some meta info through HTTP headers, but they don't necessarily tell you whether the user has JavaScript enabled or not and you can't rely on them anyway,

Strafford answered 15/12, 2010 at 20:29 Comment(3)
A good rule of thumb is to create pages and assume javascript is off. Once loaded, use javascript to "write" to your page. This allows for progressive enhancement.Marjoriemarjory
As many others have pointed out it IS possible it just is not simple. I can not understand why THIs is the accepted answer.Miniver
https://mcmap.net/q/342047/-check-if-javascript-is-enabled-with-php a two moves way to make Javascript tell you it is.Dishrag
J
69

perhaps a more simple 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>
Jeffereyjefferies answered 29/2, 2012 at 17:1 Comment(7)
Your solution is clever and efficient, but it does not validate W3C's HTML5 standards: Element style not allowed as child of element noscript in this context. (Suppressing further errors from this subtree.) You can keep this simplicity but still be valid, with <noscript> <div style="display:none"> </noscript> <span>my content</span> <noscript></div></noscript>.Vacuole
This doesn't tell you about the script, just warns the user. This is also a good way to autocheck for javascript. Just need to refresh url to the current phpsessid/session and you'll get the confirmation about is not present. No matter if you do w or w/o the javascript, check for it is just easy.Dishrag
Watch at @Chris Thompson.Dishrag
This is great if you just need to hide a portion of the page if there is no JS, but that's not what the OP was asking. He asked specifically for a way to check for JS from PHP.Vachel
It is valid HTML5 to put a <style> tag inside a <noscript> tag, as long as the <noscript> tag is in the <head>. See w3.org/TR/html5/scripting-1.html#the-noscript-elementPaigepaik
as @Clément said (it does not validate W3C's HTML5 standards) but if you move the code to the head tag, it will be a validate W3C's HTML5 standard and you can use the style in the noscript tag without any problem :)Amen
This doesn't answer the OPs question so unfortunately can't upvote it, however it's a really nice little trick which I hadn't thought of and and I wanted to say thank you for this @JeffereyjefferiesMarlowe
S
50

No, that is not possible, because PHP is a server side language, it does not access the client's browser in any way or form (the client requests from the PHP server).

The client may provide some meta info through HTTP headers, but they don't necessarily tell you whether the user has JavaScript enabled or not and you can't rely on them anyway,

Strafford answered 15/12, 2010 at 20:29 Comment(3)
A good rule of thumb is to create pages and assume javascript is off. Once loaded, use javascript to "write" to your page. This allows for progressive enhancement.Marjoriemarjory
As many others have pointed out it IS possible it just is not simple. I can not understand why THIs is the accepted answer.Miniver
https://mcmap.net/q/342047/-check-if-javascript-is-enabled-with-php a two moves way to make Javascript tell you it is.Dishrag
S
19

Technically no because as the other answers have said, PHP is strictly server-side, but you could do this...

In the PHP page on the server, output (a lot of HTML has been deleted 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 a session variable to indicate the client supports JS

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

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

Serna answered 15/12, 2010 at 20:34 Comment(1)
GOD. This is actually the solution i was thinking for. You ONLY need to check for it. Chris, think about is not the same thing do something using script noscript directive on the client then just KNOW about that and store the data.Dishrag
C
11

//Here is a solution: //it works perfect

<?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: /');
Cortneycorty answered 29/10, 2012 at 21:53 Comment(3)
So this would imply (correct me if I'm wrong) that each time a user sees the front page for the first time, it "forces" a redirection so the page is re-loaded an then you check on the reload, if it's javascript enabled? It sounds like it's bringing in an elephant to kill a mouse. But you're right: it works. It would be maybe safer to add a warning before showing the code.Adieu
Seems copied code from another webpage, but not complete. @ Chris Thompson has the correct and easies way to do that.Dishrag
Much cleaner than mine, same principle.Dishrag
T
7

You can't tell if a browser has JS enabled, but you can tell if the browser supports JS http://php.net/manual/en/function.get-browser.php

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

Having said this, that's probably not of much use. You should reconsider detecting JS from PHP. There should be no need for it if you use progressive enhancement, meaning that JS only adds functionality to what's already on the page.

Trudi answered 15/12, 2010 at 20:45 Comment(7)
Do the end users need to configure their systems to use this?Abukir
I hate being mean, but did you read the link? There are notes about configuring it. I don't suggest using it, by the way, it's not truly reliable for many things.Trudi
Reading the comments from that page actually tells you that it'll tell you whether the browser type in the HTTP headers supports JS, not whether it's enabled.Trudi
@SublymeRick I reworded the answer so it's more obvious that it doesn't solve the problem at hand, but it's still good information to know.Trudi
Progressive enhancement takes on a new meaning when your entire application is written in client-side JavaScript code (Ember or Angular). I'm working on a way to have these sorts of web apps work without JavaScript, and have everything rendered by the server as well as the client-side code.Kilometer
@Kilometer Consider something like developers.google.com/closure/templates/?csw=1 which can render the HTML on the server or the clientTrudi
@JuanMendes thanks, I've found out that this can be done pretty easily with PhantomJS (e.g. github.com/stephanebisson/ngseo)Kilometer
V
5
<noscript>
    <?php if(basename($_SERVER['REQUEST_URI']) != "disable.html"){ ?>
        <meta http-equiv="Refresh" content="0;disable.html">
    <?php } ?>
</noscript>

Place above code in your header file after title tag and set appropriate like[disable.html] for redirection.

Valse answered 26/2, 2014 at 11:3 Comment(0)
R
5

before try you have to disable your browsers javascript...

after then

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

its work

Rubin answered 24/3, 2017 at 5:43 Comment(0)
N
4

You can try with 2 metod:

  • setting cookies with JS and detecting them from PHP
  • creating a form with a hidden field and an empty value; and then assigning some value to it with JS, if the field gets the value – JS is ON, otherwise it’s off. But the form had to be submitted first before PHP can request that hidden field’s value.

if you want detect if JS enable enable setting before the loading of the page you can try this (I don't konw 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 fine tutorial on this issue on address http://www.inspirationbit.com/php-js-detection-of-javascript-browser-settings/

Newmown answered 15/12, 2010 at 20:53 Comment(0)
L
4

Here is a small include I made up that I have on top of my pages to detect if js is enabled. Hope this helps out...

<?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;
      }
   }
}
?>
Lansquenet answered 21/3, 2013 at 1:4 Comment(1)
This works perfect! The only thing is about the URL. Once you get true or false, the state is perpetued, because you are reading the current GET params. So, if i check that, and block javascript the result is faked with the URL params. Running from the entry point is working perfect. Thanks for that example :)Dishrag
S
4
<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>
Suber answered 21/3, 2016 at 21:49 Comment(0)
M
2

PHP can't be used to detect whether javascript is enabled or not. Instead use <noscript> to display an alternate message / do something.

Mamie answered 15/12, 2010 at 20:30 Comment(1)
Browsers don't load separate JavaScript-files if JavaScript is disabled. This is something PHP could detect. Resp.: Htaccess could set a cookie based on the request.Takao
S
2

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=XXXXXXXXXXXXXXXXXX" because they don't know your algo of computing the hash.

Selfreliance answered 27/6, 2015 at 11:22 Comment(0)
T
1

This is the way I check whether 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's 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>
Toe answered 9/8, 2012 at 17:40 Comment(1)
This includes 3rd party right? Seems that but is not advised.Dishrag
V
1

Recently, I had the following dilemma:

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

After some tries, I finally reached the idea that I can save some CPU & RAM usage from search engine bots. It is difficult to recognize a bot by browser identification, but all the bots have no JS enabled and that's the main criteria I used to detect if it is a real browser or it is a bot. To explain how significant it is to prevent executing code which will not give anything more for Search Engines (QR, in my case, does not affect search engines), I can say that just Google bot for example makes about 16000 crawls a day on my site.

So I've made this very simple thing which helped a lot:

<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 be written only when JS is enabled.

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

Hope this helps.

Virginia answered 20/9, 2012 at 17:1 Comment(3)
Does not work. The PHP code is always executed, instead use <noscript>no JS</noscript> to detectFidole
PHP code is always executed - righ, but document.write which actualy adds it to the document structure - not. <noscript> could or couldn't be managed by a bot - depends on the bot ... but javascript normally is disabled in all bots I know.Virginia
You should clarify that drawQR writes out an <img> tag with a SRC pointing at the QR generation script - otherwise, it looks like you generate the QR code and then write out a link to it only if the user has JS enabled.Hemisphere
C
1

Create a cookie using JavaScript and read it using PHP.

Choric answered 11/9, 2014 at 0:3 Comment(1)
Yes, this is basically the raw answer. You can do that using php session functions wich is in fact a cookie managed by PHP. But, do not limit your code to cookies. One thing is check for javascript technology and the other is about cookie permissions. Using javascript GET we can check for more things than a cookie. We can write to a server file instead a cookie, as example.Dishrag
D
1

Please despite all the people telling you cant check for a client-side scripting technology. If the target technology has http functions, you can do ALWAYS, just write out a verify step. That means literally, the way to check javascript is to run javascript. If javascript is disabled on the browser side it's not possible to check if the client is Javascript capable (like Dillo with it's default config or others)

UPDATED: I've develop this script because i test some of the examples here and seems that everybody does copypasting without any sort of tests. Code is also on the 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
}

This solution do not need more files, just a iteration if you run a Javascript capable browser. The value is passed back to PHP using a GET with a simple variable but anyone can fake the output doing cURL to url + ?sessionstart=1 unless you add more logic to it.

Dishrag answered 19/3, 2015 at 2:55 Comment(5)
Unfortunately, this is not working for me. I have tested script in Chrome and FF, and always receive "Javascript is not enabled", despite the fact that it is. Also, line 53 is generating undefined sessionstart index notice. Could you explain a little how we can use this script? Thanks.Salome
Maybe late, sorry. I've tested again using Firefox with those results: vid.me/8a8b. Also tried with Chrome and failed. I'll try to update asap.Dishrag
@Salome late again. There are many options there that works, no need to edit more. Example, an answer below, https://mcmap.net/q/342047/-check-if-javascript-is-enabled-with-phpDishrag
I have fixed it mostly, but in some cases it wasn't working, don't even remember. Then, I simply switched to server-side 2nd round verification. However, dropped it completely given the GDPR and all.Salome
Im sorry but curious about how does affect GDPR to a Javascript check. Is about cookies? Yep, 2nd round is more hidden and doesn't need for sessions.Dishrag
C
1

With this basic ajax you can separate data that the client see 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! 
?>
Chamonix answered 26/11, 2015 at 20:28 Comment(0)
I
0

Make your main php page assume jscript is off, and add a <script> to redirect to the jscript-enabled app in the <head>. If the user actually uses your first page, assume jscript is off.

Isadoraisadore answered 15/12, 2010 at 20:31 Comment(0)
C
0

Other option: If you dont' have to check if JS is enabled at the visitors first view (mainpage) you can set a cookie with js. On the next page you can check with php if the cookie is there...

Complaint answered 18/4, 2012 at 16:33 Comment(0)
B
0

You can use logic the logic (default/switch) - is this example I printed the 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');
Ben answered 6/8, 2012 at 0:24 Comment(0)
A
0

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

Adsorbent answered 21/10, 2012 at 10:57 Comment(0)
F
0

Its 2013. Simply have your script render the non-js templates inside a body > noscript tag, then inside your CSS keep your main js site container div display: none; After that just put something like <script>$('#container').show();</script> immediately after you close you main #container div and before your noscript tag. (if you're using jquery of course).

Doing it this way will show the HTML for the non-js enabled browsers automatically, and then the js enabled browsers will only see the js site.

If you're worried about over-bloating the page size with too much mark up, then you could do the same but instead leave <div id="content"></div> empty, then with the js code instead of just showing the div use an ajax call to fetch the content for it.

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

Fatling answered 9/5, 2013 at 19:16 Comment(0)
L
0

Since PHP is server side you can't know in PHP whether the client has Javascript enabled unless you use sessions (or some other way to store data across requests) and first send some code to which the client responds.

If you put the following at the start of your PHP file the client is redirected to the same URL with either 'js=0' or 'js=1' appended to the query string, depending on whether they have Javascript enabled or not. Upon receiving the redirected request the script records the result in a session variable and then redirects back to the original URL, i.e. without the appended 'js=0' or 'js=1'.Upon receiving this second redirect the script proceeds as normal, now with the session variable set according to the clients Javascript capability.

If you don't care about how your query string looks in the user's address bar you can skip the second redirect and just set the session variable. While these redirects are taking place the user is shown a short informative message (also something you could skip if you don't care about that).

<?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
}
?>
Licha answered 9/1, 2014 at 5:4 Comment(0)
B
-5

Yes.

Ensure 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;
Ben answered 23/9, 2012 at 4:31 Comment(2)
That will tell the USER if JS is enabled, it won't tell the PHP script. And why does it need the latest jQuery, it looks like it should work in practically any version? You don't even need PHP for this. Just put the SPAN diectly in your HTML. Finally, your assignment to $js has a typo.Alcott
I believe the question was to use php to check if it was enable. In this example, a php variable is printed, it will be no unless javascript is enabled; no?Ben

© 2022 - 2024 — McMap. All rights reserved.