Jump to: navigation, search

PHP Cookie and Pass values through Cookie

From w3cyberlearnings

Contents

What is cookie in PHP?

  • Cookie uses to pass information to the user browser.
  • Cookie is unsecured because information in the cookie that pass to the user browser can be

changed.

  • Cookie is stored in a specific location within the user computer.
  • Ad that uses cookie to track user browser habits which against the user privacy.
  • User can turn off his or her own cookie.
  • Store information using Cookis is very unreliable because user can delete or alter the cookie
  • Cookie information can not be access in the current page where the cookie has been set.

Where to place the cookie?

  • Cookie must be placed on the top of page.

Cookie syntax

setcookie(name, value, expire, path, domain);

Cookie hour

// for 1 minute
$expire1= time() + 60 ;
// for 3minutes 
$expire2= time() + 60 * 3;
// for 1 hour  
$expire2= time() + 60 * 60;
// for 3 hour
$expire2= time() + 60 * 60 * 3;
// for 1 day (24 hours)
$expire2= time() + 60 * 60 * 24;
// for 2 days 
$expire2= time() + 60 * 60 * 24 * 2;
// for a month
$expire2= time() + 60 * 60 * 24 * 30;
// for 2 months
$expire2= time() + 60 * 60 * 24 * 30 * 2;
// for 1 year
$expire2= time() + 60 * 60 * 24 * 30 * 12;

Cookie syntax example 1

  • This cookie expire within an hour after create.
setcookie('user', 'Bob Maat', time()+3600);

Cookie syntax example 2

  • The same as the example 1.
$expire = time() + 60 * 60 * 24 ;
setcookie('user', 'Bob Maat', $expire);

Cookie syntax example 3

  • Set cookie for a specific path and domain
$expire = time() + 60 * 60 * 24 ;
$path = '/student_list/';
$domain ='w3cyberlearnings.com';
setcookie('user', 'Bob Maat', $expire,$path, $domain);

Example 1

student.php page

  • Set cookie.
  • Place cookie on top of the page.
<?php
setcookie('name', 'Bob Maat', time() + 60);
session_start();

$_SESSION['authorized'] = 1;
?>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>All User</title>
	</head>
	<body>
		<a href="student_list.php">Click Here</a>
	</body>
</html>

student_list.php page

  • Get user cookie information

<?php
session_start();
if ($_SESSION['authorized'] != 1) {
	echo 'Sorry, you do not have permission!';
	exit();
}
?>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<title>List User</title>
	</head>
	<body>
		<?php
		echo 'Student name: ' . $_COOKIE['name'] . '<br/>';
		?>
	</body>
</html>

Navigation
Web
SQL
MISC
References