Previous Page

Push JavaScript Values To PHP

by Thomas J. Allen
Posted on May 25, 2018 at 01:23:50 PM


I was working on a timezone counter to show when the next Sabbath starts based on the visitors location.

My time calculations were all done in PHP to calculate the remaining time till the Sabbath starts. So I was trying to figure out how to grab the visitors TimeZone info without needing to link to a service to determine their location by IP Address. Then it hit me! JavaScript would be the best way to grab this info from the client side browser and set the correct info, but then how would I send this info to PHP?

I tried many different steps to accomplish this, without success. Then it hit me, why not just set a cookie with JavaScript and grab it in PHP! This approach turned out to be a success.

JavaScript To Set Initial Cookie

<script type="text/javascript">

  function setCookie(cname, cvalue, exdays) {
   var d = new Date();
   d.setTime(d.getTime() + (exdays*24*60*60*1000));
   var expires = "expires="+ d.toUTCString();
   document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }

 function getCookie(cname) {
   var name = cname + "=";
   var decodedCookie = decodeURIComponent(document.cookie);
   var ca = decodedCookie.split(';');
   for (var i = 0; i <ca.length; i++) {
          var c = ca[i];
          while (c.charAt(0) == ' ') {
                     c = c.substring(1);
          }
          if (c.indexOf(name) == 0) {
               return c.substring(name.length, c.length);
          }
  }
  return "";
 }

  // Set Cookie With Users Time Zone (Cookie Name, Value, Days To Expire)
  setCookie("timezone", Intl.DateTimeFormat().resolvedOptions().timeZone, "10");

</script>

 

PHP To Grab Cookie Value

<?php

    echo "<br>PHP: " . $_COOKIE["timezone"];

?>

 

My Image


Previous Page
Site By BrainScanMedia.com, Inc. - A Web Solutions Company. Advanced Cart, Parker Colorado Web Design, Parker Colorado Web Design, Parker Colorado Web Hosting, Parker Colorado Web Hosting, Parker Colorado eCommerce, Parker Colorado SEO, Parker Colorado Search Engine Optimization, Parker Colorado Graphic Designer, Parker Colorado Programmer, Parker Colorado Business Card Design, Staten Island New York Web Design, Staten Island New York Web Design, Staten Island New York Web Design, Staten Island New York Web Designer, Staten Island New York Website Design, Staten Island New York Web Hosting, Staten Island New York Web Hosting, Staten Island New York eCommerce, Staten Island New York SEO, Staten Island New York Graphic Designer, Staten Island New York Programmer, Staten Island New York Business Card Design