How to Get JavaScript if It Is Disabled in PHP
PHP-based Web applications enable a rich, customized user experience through on-demand content and a variety of methods of user interaction. However, many of the methods of user interaction require JavaScript to function. A subset of your users may have disabled JavaScript for security reasons. PHP executes server-side, but through a simple trick, can detect whether a user has JavaScript enabled.
Instructions
-
Using Cookies
-
1
Create an "index.php" page that the user will land on when she first visits your site. This "index.php" page can redirect the user to different version of the site depending on whether JavaScript is enabled, or simply prompt the user to enable JavaScript to continue.
-
2
Set a user cookie with Javascript in the header section of "index.php" and reload the page.
<script type="text/javascript>
function setJSCookie(name,value,expires_in_days){
if(expires_in_days){
var this_Date = new Date();
var expire_date = "; expires="+this_Date.toGMTString();
this_Date.setTime(this_Date.getTime()+(days*24*60*60*1000));
} else {
var expire_date = "";
}
document.cookie = name+"="+value+expire_date+"; path=/";
}
setJSCookie("my_site_w_JS_enabled","Y",1);
</script>
<meta http-equiv="refresh" content="2;url=index.php?c=1"> -
-
3
Check in "index.php" whether the cookie is detected after reload.
<?php
if(!isset($_COOKIE['my_site_w_JS_enabled'] && $_GET['c'] == 1){
//page reloaded and cookie is not set, do something
}
?>
-
1
- Photo Credit Hemera Technologies/Photos.com/Getty Images