In this example source code, I will create a cookie in JavaScript and retrieve the cookie value using PHP. Read on.
JavaScript code to create cookie.
<script type='text/javascript'>
function createCookie(name, value,expiredays)
{
var expiry_date = new Date();
expiry_date.setDate(expiry_date.getDate() + expiredays);
document.cookie=name+ "=" +escape(value)+
((expiredays==null) ? ""
:";expires="+expiry_date.toGMTString());
alert("'" + name + "' cookie created.");
}
</script>
HTML code to call the
createCookie
function.<input type="button" value="Create Cookie using JavaScript"
onclick="createCookie('YourName', 'Joel Badinas')"/>
HTML form for submitting request to the server for the PHP code.
<form method="POST" action="">
<p>
<input type="submit" name="submit" value="Get Cookie using PHP"/>
</p>
</form>
PHP code that will read the cookie.
<?php
if (isset($_POST["submit"]))
{
print "Cookie value is '".$_COOKIE["YourName"]."'";
}
?>
Putting it all together.
<html>
<head>
<title>Practical Web Programming</title>
<script type='text/javascript'>
function createCookie(name, value,expiredays)
{
var expiry_date = new Date();
expiry_date.setDate(expiry_date.getDate() + expiredays);
document.cookie=name+ "=" +escape(value)+
((expiredays==null) ? ""
:";expires="+expiry_date.toGMTString());
alert("'" + name + "' cookie created.");
}
</script>
</style>
</head>
<body>
<p method="POST" action="">
<p>
<input type="button" value="Create Cookie using JavaScript"
onclick="createCookie('YourName', 'Joel Badinas')"/>
<input type="submit" name="submit" value="Get Cookie using PHP"/>
</p>
</form>
<?php
if (isset($_POST["submit"]))
{
print "Cookie value is '".$_COOKIE["YourName"]."'";
}
?>
</body>
</html>
There you have it.