PHP Cookies

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

How to Create a Cookie?

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

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

Example

In the example below, we will create a cookie named “user” and assign the value “Alex Porter” to it. We also specify that the cookie should expire after one hour:

<?php
setcookie(“user”, “Alex Porter”, time()+3600);
?>
<html>
<body>
</body>
</html>

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named “user” and display it on a page:

<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>
<body>

<?php
if (isset($_COOKIE["user"]))
echo “Welcome ” . $_COOKIE["user"] . “!<br />”;
else
echo “Welcome guest!<br />”;
?>

</body>
</html>

How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie(“user”, “”, time()-3600);
?>

PHP $_GET and $_POST at php form

PHP $_GET

The $_GET variable is used to collect values from a form with method=”get”

Information sent from a form with the GET method is visible to everyone (it will be displayed in the browser’s address bar)

<html>
<body>
<form action=”welcome.php” method=”get“>
Name: <input type=”text” name=”name” />
Age: <input type=”text” name=”age” />
<input type=”submit” />
</form>
</body>
</html>

When we input Johnson at name and 30 at age, then clicks the Submit button, the URL sent could look something like this:

http://yourdomain/welcome.php?name=Johnson&age=30

For output we must create file php : welcome.php with code :

<html>
<body>
Welcome <?php echo $_GET["name"]; ?>.<br />
You are <?php echo $_GET["age"]; ?> years old!
</body>
</html>

Output code <?php echo $_GET["name"]; ?> where name must same with form <input type=”text” name=”name” />

output welcome.php will shown like this

Welcome Johnson.
You are 30 years old!

PHP $_POST

(more…)