Empty Woocommerce Cart before adding new item

If you happen to only wants to allow 1 item in your cart and remove all other cart item before adding one, this article might be your saver. Apparently there are a few article that uses a hook call 'woocommerce_add_to_cart' where it 'should' remove the item before adding it. But it doesn't work for newer version of woocommerce. However, there is another hook call 'woocommerce_add_to_cart_validation'. Therefore, if you would like to remove an item before adding a new item into your cart in Woocommerce, you should do something like this.

// before addto cart, only allow 1 item in a cart
add_filter( 'woocommerce_add_to_cart_validation', 'woo_custom_add_to_cart_before' );

function woo_custom_add_to_cart_before( $cart_item_data ) {

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return true;
}

This will remove everything during validation before adding the item into wWocommerce cart. Try it!

Multiple Upload Using Single Upload File With jQuery

This is a trick to perform multiple upload using a single upload bar instead of multiple upload bars created by stickman. If you are looking for multiple upload using iframe or asynchronous method, you can visit this simplest way tutorial that explains how iframe method can be done and whether ajax method is available. I first came across stickman article was when i was doing research for multiple upload without having the file uploaded into the server. His idea was brilliant. However, i hardly have the need for such function until recently when my project submit form required multiple upload using a single upload bar again. Stickman method was pure JavaScript which is great and efficient but i needed something from jQuery. Here, i will try to simplify his method into jQuery form.

Concept of Single Multiple Upload File

In order to achieve single multiple upload file, we will have to understand that multiple upload is still possible even without asynchronous upload, that is, we will need multiple upload bar displaying on the screen and having user to click on each upload bar to upload multiple item at once. In stickman concept, its almost the same. The only differences is that he uses one upload bar and insert a new one on top of the existing upload bar AFTER a user has finished selected the item to be uploaded. Therefore it seems like there is only one upload bar. (the process is too fast for our eyes to follow. Thus, we all get trick when this happen) But in reality, all these upload bars were only hidden from user but not from codes. Once, the submit button is pressed, all the visible and non-visible upload bars are being uploaded to the server! This way we get our cheap multiple upload using a single upload bar method.

jQuery Single Multiple Upload File

I won't be displaying stickman code in this article as you can download directly from his website. We can now proceed with the coding after we have understand how stickman method works.

HTML code

All we need on the HTML section are these:

<div>
	<input type="file" name="files[]">
	<div id="upload_list"></div>
</div>

jQuery code

jQuery code is fairly simple. Let's don't complicate stuff. All we need to do is this.

jQuery(document).ready(function($){
var replaceMe = function(){
	var obj = $(this);
	$(obj).css({'position':'absolute','left':'-9999px','display':'none'}).parent().prepend('<input type="file" name="'+obj.attr('name')+'"/>')
	$('#upload_list').append('<div>'+obj.val()+'<input type="button" value="cancel"/><div>');
	$("input[type='file']").change(replaceMe);
	$("input[type='button']").click(function(){
		$(this).parent().remove();
		$(obj).remove();
	});
}
$("input[type='file']").change(replaceMe);
});

The above takes care of the basic. If you wish to restrict the number of upload, you can place a restriction variable.

jQuery(document).ready(function($){
var max = 2;
var replaceMe = function(){
	var obj = $(this);
	if($("input[type='file']").length > max)
	{
		alert('fail');
		obj.val("");
		return false;
	}
	$(obj).css({'position':'absolute','left':'-9999px','display':'none'}).parent().prepend('<input type="file" name="'+obj.attr('name')+'"/>')
	$('#upload_list').append('<div>'+obj.val()+'<input type="button" value="cancel"/><div>');
	$("input[type='file']").change(replaceMe);
	$("input[type='button']").click(function(){
		$(this).parent().remove();
		$(obj).remove();
		return false; //safari fixes
	});
}
$("input[type='file']").change(replaceMe);
});

Where max is the counter that restricts the number of uploads. Since jQuery takes care of most of the complicated things. The code eventually became smaller. For some reason bind doesn't works for the event change. Thus, i will have to attach the event again. From pure JavaScript of 156 line into a few line of codes, jQuery definitely makes developers life much more easier (doesn't means the code produce by jQuery is much more efficient though.).

The Demo

The demo can be found here.

Conclusion

The above jQuery code has simplify the version found on stickman site. Although the display doesn't looks as attractive but my objective has been achieved. Sometimes, JavaScript can be harder to read compared to a jQuery one. However, JavaScript version still has a better efficiency as compared to a jQuery one.

Tutorial: disable _blank attribute from opening new window

Today is an interesting day. I was working on my project and found that i have a hard time looking for a way to disable my target attribute, _blank, which will open a new window and display the item there.  Surprisingly, i found tons of how to create pop out box and many discussion regarding setting up a window.open instruction. But no one care to explain how to stop or disable it! Hence, i decide to write it out myself.

Pop out box

We all know how to enable a pop out box. We can do that either by window.open or using target attribute _blank to pass the work to another window. We can also do that for form submission but bringing out another box is not very professional unless you are showing certain information. Hence, most of us will go with ajax or iframe way of synchronize submission. Nonetheless, pop out box is a necessity in our web environment. While opening a new window box is easy but how about disabling it?

Disable _blank attribute

Disabling a pop out box or anything that will pop out is pretty simple. If you try to recall how you disable those anchor link, you might have an idea how you are going to disable all other types of link. Most pop out box is being initialize by a click. Hence, the event that we are interested with is onclick event handler. However, different people will have different ways of disabling an anchor link such as

<a href="JavaScript: void();">link</a>

or

<a href="#">link</a>

But we are interested in

<a href="JavaScript: return false;">link</a>

In order to disable pop out, it is the same as how we used to disable link. Hence, if you have a link such as this,

<a href="http://somewhere.com" target="_blank">link</a>

it will bring you to somewhere.com on a new pop out box. And if you want to prevent that, you will do this.

<a href="http://somewhere.com" target="_blank" onclick='return false;'>link</a>

That's it! To prevent window.open, we just remove that sentence! haha..

17 JavaScript Form Validation Snippets

Last week i wrote 25 form validation for PHP. I find useful to have more layer of defend as JavaScript might malfunction or disable and cause your validation to fail but the form is still being passed on to our server. Nonetheless, JavaScript validation does provide certain level of restriction and protection for any web application. Especially when web is evolving quickly in this period of time. We are required to validate any data from our user to prevent any harm that can cause damage to our application and businesses. These JavaScript form validation snippets are needed in every form validation and repeating searching for them is unnecessary and slow down development processes. Therefore, you might want to bookmark these snippets for your future needs

Email Validation

Email validation is the most basic validation that any web application would have.

function isEmail(elem, helperMsg){
	var regexp  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if(regexp.test(elem.value)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var email = document.getElementById('ham_email');
if(isEmail(email, "Invalid Email Format")){
//proceed..
}

URL Validation

URL validation helps to validate whether a particular string is a valid url format.

function isUrl(elem, helperMsg) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
	if(regexp.test(elem.value.toLowerCase())){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var link = document.getElementById('ham_link');
if(isUrl(link, "Invalid link")){
//proceed..
}

Username Validation

This function help us validate whether a username contain valid character and length. It accept any underscore, alphabets and numbers within 5-25 characters.

function isValidUsername(elem, msg) {
	var regx = /^[A-Za-z0-9_]{5,25}$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

You can add additional symbols or change the length of the validation easily by alter the regular expression.

In order to use this, we pass in an object and an alert value if it fail.

var username = document.getElementById('username');
if(isValidUsername(username, "Invalid character found on username!")){
//proceed...
}

Password Validation

Here is a simple password strength validation that check the following criteria.

  1. Passwords will contain at least 1 upper case letter
  2. Passwords will contain at least 1 lower case letter
  3. Passwords will contain at least 1 number or special character
  4. Passwords will contain at least 8 characters in length
  5. Password maximum length should not be arbitrarily limited
function isStrongPassword(elem, msg) {
	var regx = /(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/;
	if(regx.test(elem.value)){
		return true;
	}else {
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var password = document.getElementById('password');
if(isStrongPassword(password, "Your password fail the basic strength test. \n1. Passwords will contain at least 1 upper case letter\n2. Passwords will contain at least 1 lower case letter\n3. Passwords will contain at least 1 number or special character\n4. Passwords will contain at least 8 characters in length\n5. Password maximum length should not be arbitrarily limited\n")){
//proceed..
}

Numeric Validation

This validate whether a given string contain a valid numeric value which include both negative value and decimal ones.

function isNumeric(elem, helperMsg){
	var numericExpression = /^[-]?\d*\.?\d*$/;
	if(elem.value.toString().match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var price = document.getElementById('price');
if(isNumeric(price, "Invalid value found")){
//proceed...
}

Text Empty Validation

In every form validation, there is always a need to check whether a particular text box is empty.

function isEmpty(elem, helperMsg){
	if(elem.value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var name = document.getElementById('ham_company');
if(!isEmpty(name, "Please give us your name")){
//proceed...
}

Radio Box Validation

We can determine whether a radio box has been selected using this function.

function hasSelected(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

Drop Down Validation

We also check whether a particular drop down box has its value selected with the following function.
In order to use this, we pass in an object and an alert value if it fail.

var radio = document.getElementById('radio');
if(hasSelected(radio, Please select your gender")){
//proceed...
}
function isSelected(elem, helperMsg){
	if(elem.options[elem.selectedIndex].value.toString().length > 0){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

In order to use this, we pass in an object and an alert value if it fail.

var month = document.getElementById('ham_month');
if(isSelected(month, "Please select a month")){
//proceed...
}

Check Box Validation

We can perform check box validation to see whether a particular check box has been selected through this function.

function hasChecked(elem, msg){
	for (i = 0; i < elem.length; i++) //for all check boxes
	{
		if (elem[i].checked == true ) //otherwise elements also looks at radio buttons
		{
			return true;
		}
	}
	alert(helperMsg);
	elem[0].focus();
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var checkbox= document. getElementsByName('checkbox');
if(checkPhone(checkbox, "Please tick one of the check box")){
//proceed...
}

Phone Validation

This function will validate the following criteria phone number.

  • phone:
    339-4248
    339-42-48
    339 42 48
    339 4248
    3394248
    (095) #phone#
    (095)#phone#
    +7 (095) #phone#
    +7 (095)#phone#
    +7(095) #phone#
    +7(095)#phone#
function checkPhone(elem, msg)
{
	var str = elem.value;
	var phone2 = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
	if (str.match(phone2)) {
   		return true;
 	} else {
 		alert(helperMsg);
		elem.focus();
		return false;
 	}
}

In order to use this, we pass in an object and an alert value if it fail.

var phonenumber = document.getElementById('phonenumber');
if(checkPhone(phonenumber, "Invalid Phone Number")){
//proceed...
}

File Extension Validation

This function validate whether a particular upload string contains a valid extension.

function isAllowedFileExtension(elem, helperMsg){
	var alphaExp = /.*\.(gif)|(jpeg)|(jpg)|(png)$/;
	if(elem.value != "")
	{
		if(elem.value.toLowerCase().match(alphaExp)){
			return true;
		}else{
			alert(helperMsg);
			elem.focus();
			return false;
		}
	}
	else
		return true;
	return false;
}

In order to use this, we pass in an object and an alert value if it fail.

var upload = document.getElementById('ham_upload');
if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only")){
//proceed...
}

IP Validation

Sometimes there is a need to validate whether a particular IP address is valid using JavaScript.

function isValidIPAddress(elem, msg) {
   var re = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;
   ipaddr = elem.value.toLowerCase();
   if (re.test(ipaddr)) {
      var parts = ipaddr.split(".");
      if (parseInt(parseFloat(parts[0])) == 0) { return false; }
      for (var i=0; i<parts.length; i++) {
         if (parseInt(parseFloat(parts[i])) > 255) { return false; }
      }
      return true;
   } else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var ip= document.getElementById('ip');
if(isValidIPAddress(ip, "Invalid IP Address")){
//proceed...
}

US Social Security Number Validation

Testing US Social security number can be done with the below function.

function isValidSSN(elem, msg) {
	var value = elem.value.toLowerCase();
	var tmp = false;
    var re = /^([0-6]\d{2}|7[0-6]\d|77[0-2])([ \-]?)(\d{2})\2(\d{4})$/;
    if (!re.test(value)) { tmp = true; }
    var temp = value;
    if (value.indexOf("-") != -1) { temp = (value.split("-")).join(""); }
    if (value.indexOf(" ") != -1) { temp = (value.split(" ")).join(""); }
    if (temp.substring(0, 3) == "000") { tmp = true; }
    if (temp.substring(3, 5) == "00") { tmp = true; }
    if (temp.substring(5, 9) == "0000") { tmp = true; }

	if(tmp){
		alert(helperMsg);
		elem.focus();
		return false;
	}else
    return true;
}

In order to use this, we pass in an object and an alert value if it fail.

var ssn = document.getElementById('ssn');
if(isValidSSN(ssn, "Invalid US Social Security Number")){
//proceed...
}

US Zip Code Validation

We can valid US zip code using the following function.

function isValidZipCode(elem, msg) {
   var re = /^\d{5}([\-]\d{4})?$/;
   var value = elem.value.toLowerCase();
   if(re.test(value)){
		return true;
   }else {
		alert(helperMsg);
		elem.focus();
		return false;
   }
}

In order to use this, we pass in an object and an alert value if it fail.

var zip= document.getElementById('zip');
if(isValidSSN(zip, "Invalid US Zip Code")){
//proceed...
}

Date Validation

This function validate date with a given format.

function isValidDate(dateStr, format) {
   if (format == null) { format = "MDY"; }
   format = format.toUpperCase();
   if (format.length != 3) { format = "MDY"; }
   if ( (format.indexOf("M") == -1) || (format.indexOf("D") == -1) || _
      (format.indexOf("Y") == -1) ) { format = "MDY"; }
   if (format.substring(0, 1) == "Y") { // If the year is first
      var reg1 = /^\d{2}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
      var reg2 = /^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
   } else if (format.substring(1, 2) == "Y") { // If the year is second
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{2}\1\d{1,2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{4}\1\d{1,2}$/
   } else { // The year must be third
      var reg1 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2}$/
      var reg2 = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
   }
   // If it doesn't conform to the right format (with either a 2 digit year or 4 digit year), fail
   if ( (reg1.test(dateStr) == false) && (reg2.test(dateStr) == false) ) { return false; }
   var parts = dateStr.split(RegExp.$1); // Split into 3 parts based on what the divider was
   // Check to see if the 3 parts end up making a valid date
   if (format.substring(0, 1) == "M") { var mm = parts[0]; } else _
      if (format.substring(1, 2) == "M") { var mm = parts[1]; } else { var mm = parts[2]; }
   if (format.substring(0, 1) == "D") { var dd = parts[0]; } else _
      if (format.substring(1, 2) == "D") { var dd = parts[1]; } else { var dd = parts[2]; }
   if (format.substring(0, 1) == "Y") { var yy = parts[0]; } else _
      if (format.substring(1, 2) == "Y") { var yy = parts[1]; } else { var yy = parts[2]; }
   if (parseFloat(yy) <= 50) { yy = (parseFloat(yy) + 2000).toString(); }
   if (parseFloat(yy) <= 99) { yy = (parseFloat(yy) + 1900).toString(); }
   var dt = new Date(parseFloat(yy), parseFloat(mm)-1, parseFloat(dd), 0, 0, 0, 0);
   if (parseFloat(dd) != dt.getDate()) { return false; }
   if (parseFloat(mm)-1 != dt.getMonth()) { return false; }
   return true;
}

You will use the function this way,

if (!isValidDate(myDateString, "DMY")) { alert("The date is not in the correct format."); }

Time Validation

This function validate time such as

  1. 02:25AM
  2. 00:23PM
  3. 23:45PM
  4. 11:23
  5. etc.
function isValidTime(value) {
   var hasMeridian = false;
   var re = /^\d{1,2}[:]\d{2}([:]\d{2})?( [aApP][mM]?)?$/;
   if (!re.test(value)) { return false; }
   if (value.toLowerCase().indexOf("p") != -1) { hasMeridian = true; }
   if (value.toLowerCase().indexOf("a") != -1) { hasMeridian = true; }
   var values = value.split(":");
   if ( (parseFloat(values[0]) < 0) || (parseFloat(values[0]) > 23) ) { return false; }
   if (hasMeridian) {
      if ( (parseFloat(values[0]) < 1) || (parseFloat(values[0]) > 12) ) { return false; }
   }
   if ( (parseFloat(values[1]) < 0) || (parseFloat(values[1]) > 59) ) { return false; }
   if (values.length > 2) {
      if ( (parseFloat(values[2]) < 0) || (parseFloat(values[2]) > 59) ) { return false; }
   }
   return true;
}

Credit Card Validation

This function validate whether a given string format is similar to a credit card type.

function isValidCreditCard(type, ccnum) {
   if (type == "Visa") {
      // Visa: length 16, prefix 4, dashes optional.
      var re = /^4\d{3}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "MC") {
      // Mastercard: length 16, prefix 51-55, dashes optional.
      var re = /^5[1-5]\d{2}-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "Disc") {
      // Discover: length 16, prefix 6011, dashes optional.
      var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
   } else if (type == "AmEx") {
      // American Express: length 15, prefix 34 or 37.
      var re = /^3[4,7]\d{13}$/;
   } else if (type == "Diners") {
      // Diners: length 14, prefix 30, 36, or 38.
      var re = /^3[0,6,8]\d{12}$/;
   }
   if (!re.test(ccnum)) return false;
   // Remove all dashes for the checksum checks to eliminate negative numbers
   ccnum = ccnum.split("-").join("");
   // Checksum ("Mod 10")
   // Add even digits in even length strings or odd digits in odd length strings.
   var checksum = 0;
   for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
      checksum += parseInt(ccnum.charAt(i-1));
   }
   // Analyze odd digits in even length strings or even digits in odd length strings.
   for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
      var digit = parseInt(ccnum.charAt(i-1)) * 2;
      if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
   }
   if ((checksum % 10) == 0) return true; else return false;
}

Summary

Usually i will use these code in such a way to validate my form. I find it neat and tidy.

form.onsubmit = validation;
var validation = function(){
	var name = document.getElementById('ham_company');
	var email = document.getElementById('ham_email');
	var link = document.getElementById('ham_link');
	var description = document.getElementById('ham_desc');
	var banner = document.getElementById('ham_banner');
	var month = document.getElementById('ham_month');
	var url = document.getElementById('ham_url');
	var upload = document.getElementById('ham_upload');
	var quiz = document.getElementById('ham_quiz');
	if(isEmail(email, "Invalid Email Format"))
		if(isUrl(link, "Invalid link"))
			if(OneNotEmpty(url, upload, "Either image url or upload must be perform!"))
				if(isAllowedFileExtension(url, "Please provide an image with Gif, Png or Jpg extension Only"))
					if(isAllowedFileExtension(upload, "Please Upload Gif, Png or Jpg Images Files Only"))
						if(isSelected(month, "Please select a month"))
							if(isSelected(banner, "Please select a banner"))
								if(NotEmpty(quiz, "Please answer the quiz"))
									if(NotEmpty(name, "Please give us your name"))
									{
										return true;
									}

	return false;
}

On the other hand, you can always brings up new form validation snippets to share with me in this article. I will love to know 🙂

Determine Whether JavaScript Is Enabled/Disabled Via PHP

Recently i was working on a project where there is a need to determine whether JavaScript is enabled or was disabled by the user. Depending whether the JavaScript is enable or not, the system will rely on JavaScript operation if it does and PHP operation if it doesn't. The fundamental solution to this is to detect whether JavaScript is enable before the system can determine which approach can be used. However, there is no easy solution to determine whether a client scripting is enable in a server scripting language (PHP) without finish loading the page! Therefore, in this article we will discuss whether there is such possibility to use PHP to determine whether JavaScript is enabled for your web application.

The Problem

The main problem is that a server script language can never be able to determine whether a client script language is available as the server script language will always run first. Furthermore, the client script is always run on the client side and never executed on the server side. Therefore, when the server scripting is running at the server side and send to the client for display, the server scripting language will have no idea what is going on with the client environment. Hence, strictly speaking will be unable to determine JavaScript is enable or disable.

The Solution

Although it sounds impossible for server side to determine whether a client scripting is available such as JavaScript but certain tricks can be perform in order to achieve this. However, it won't be a convenient one. Recall that every web system should have a redirect index.php page to prevent our code from showing in plaintext if anything happen? We can use that page to determine whether javascript is enable by writing a script to either append a value and post over to the next page or a better alternative is to store it into the user cookie. If you store a value and post it to the next page, the validation can only occur within the main page. However, if you utilize cookie to determine whether JavaScript is available, you can always use php to determine whether that cookie value is available. If it is not available (they delete their browser cookie on the way) you can redirect that user to the index.php to revalidate JavaScript is enable. Once it is being verify, you will just show a message to the user after index.php has redirect or run on pure php.

On the index.php script, it will be something like this,

<script type='javascript/text'>
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
createCookie('verify_cookie', 'Y', 1);
</script>
<meta http-equiv="refresh" content="2;url=main.php?c=1">

We have a function that help us to create a cookie if JavaScript available. Once this is done, we redirect the user to main.php where our real page is located with a get value of c=1. This value is needed to avoid recursive request. We can't use PHP header function because it will redirect before JavaScript has the opportunity to run and the code should be placed before the head tag to make this valid. On all other pages we will have something like this before the header.

<?php
	//filter the global variable first.
	if(!isset($_COOKIE['verify_cookie']) && $_GET['c'] == 1){
		echo 'JavaScript is disable';
	}else if(!isset($_COOKIE['verify_cookie'])){
		//perform check to determine whether the cookie expire OR it really was disabled.
		header('location: index.php');
	}else{
		//perform another check on javascript similar to index.php if you afraid that the cookie exist but javascript was disabled.
	}
?>

The above is to verify whether javascript exist in each page and use to run either pure php or combination with JavaScript as these script can be imported using PHP if needed. The solution above can be use as a references and not necessary a solid solution.

Alternative Solution

The alternative solution to this is to use the noscript tag which is very simple and make your life a better place to live in.

<script>
document.getElementsByTagName('body')[0].innerHTML = 'JavaScript is enable.';
<script>
<noscript>
JavaScript is disabled.
<noscript>

Conclusion

Many will turn to noscript tag that can really ease and simplify the way we code. However, for some system which required to determine whether script is enabled for different server script to run. This might help those that are doing such approach as noscript tag will only run after the server has processed its information. On the other hand, you can combine this approach with the no tag approach to better validate your logic.