Sunday, June 1, 2014

PHP Tutorials -> Cookies

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 for 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 create cookies.
Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax

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

Example

The following example sets a cookie named "uname" - that expires after ten hours.
<?php 
setcookie("uname", $name, time()+36000);
?>
<html>
<body>
<p>
A cookie was set on this page! The cookie will be active when 
the client has sent the cookie back to the server.
</p>
</body>
</html>

How to Retrieve a Cookie Value

When a cookie is set, PHP uses the cookie name as a variable.
To access a cookie you just refer to the cookie name as a variable.
Tip: Use the isset() function to find out if a cookie has been set.

Example

The following example tests if the uname cookie has been set, and prints an appropriate message.
<html>
<body>
<?php
if (isset($_COOKIE["uname"]))
echo "Welcome " . $_COOKIE["uname"] . "!<br />";
else
echo "You are not logged in!<br />";
?>
</body>
</html>

PHP Include Files (SSI)


Server Side Includes

You can insert the content of one file into another file before the server executes it, with the require() function. The require() function is used to create functions, headers, footers, or elements that will be reused on multiple pages.
This can save the developer a considerable amount of time. If all of the pages on your site have a similar header, you can include a single file containing the header into your pages. When the header needs updating, you only update the one page, which is included in all of the pages that use the header.

Example

The following example includes a header that should be used on all pages:
<html>
<body>
<?php require("header.htm"); ?>
<p>
Some text
</p>
<p>
Some text
</p>
</body>
</html>


0 comments:

Post a Comment