<script> document.cookie = "js_var_value = " + localStorage.value </script>
<?php
$php_var_val= $_COOKIE['js_var_value'];
echo $php_var_val;
?>
There are many reasons why one might want to assign a Javascript variable to a PHP variable. Some possible reasons include:
-To pass data from Javascript to PHP (for example, to use PHP to process or store data that was entered into a form via Javascript)
-To make use of PHP's built-in functions and libraries from within Javascript
-To take advantage of PHP's faster execution speed when working with large data sets or complex algorithms.
The document.cookie is used to store cookies in javascript and $_COOKIE is a PHP superglobal variable that is used to access cookies. We will use document.cookie to store javascript variable value to a cookie and access it in PHP using $_COOKIE.
<script>
var user_name = "Rohit";
document.cookie = "name = " + user_name;
</script>
<?php
$name= $_COOKIE['name'];
echo $name;
?>
In the above code example:
The first time you log in it doesn't work. If you reload the page everything is fine. This is because php will execute first only then the javascript.