Creating cookies in php

Cookies in PHP

Cookies are used to store the information of a web page in a remote browser, so that when the same user comes back to that page, that information can be retrieved from the browser itself.

In this tutorial, we will discuss how to use Cookies in PHP. We have several examples in this tutorial which will help you to understand the concept and use of a cookie.

Uses of cookie

Cookies are often used to perform following tasks:

  • Session management: Cookies are widely used to manage user sessions. For example, when you use an online shopping cart, you keep adding items in the cart and finally when you checkout, all of those items are added to the list of items you have purchased. This can be achieved using cookies.
  • User identification: Once a user visits a webpage, using cookies, that user can be remembered. And later on, depending upon the search/visit pattern of the user, content which the user likely to be visited are served. A good example of this is ‘Retargetting’. A concept used in online marketing, where depending upon the user’s choice of content, advertisements of the relevant product, which the user may buy, are served.
  • Tracking / Analytics: Cookies are used to track the user. Which, in turn, is used to analyze and serve various kind of data of great value, like location, technologies (e.g. browser, OS) form where the user visited, how long (s)he stayed on various pages etc.
Читайте также:  Java hashmap source code

How to create a cookie in PHP

PHP has a setcookie() function to send a cookie. We will discuss this function in detail now.

 setcookie(name, value, expire, path, domain, secure, httponly) 

setcookie() has several parameters. Following table discusses those.

Parameter Description Which type of data
name Name of the cookie. String
value Value of the cookie, stored in clients computer. String
expire Unix timestamp, i.e. number of seconds since January 1st, 1970 (called as Unix Epoch). Integer
path Server path in which the cookie will be available. String
domain To which domain the cookie is available. String
secure If set true, the cookie is available over a secure connection only. Boolean
httponly If set true, the cookie is available over HTTP protocol only. Scripting languages like JavaScript won’t be able to access the cookie. Boolean

setcookie() returns boolean.

Following example shows how to create a cookie in PHP. Code first and then some explanation.

So, what does the code above does? The first parameter sets the name of the cookie as ‘w3resource’, the second parameter sets the value as ‘w3resource tutorials’, the third parameter states that the cookie will be expired after 3600 seconds (note the way it has been declared, we use time() and then add the number of seconds we wish the cookie must be expired after), the fourth parameter sets path on the server ‘/home/your_name’ where your_name may be an username, so it directs the home directory of a user, the fifth and sixth parameter is set to 1, i.e. true, so the cookie is available over secure connections only and it is available on HTTP protocol only.

echo $_COOKIE[«w3resource»]; simply prints the cookie value. This way you can retrieve a cookie value.

How to create a cookie without urlencoding the cookie value

The setcookie() sends a cookie by urlencoding the cookie value. If you want to send a cookie without urlencoding the cookie value, you have to use setrawcookie() .

This function has all the parameters which setcookie() has, and the return value is also boolean.

PHP $_COOKIE autoglobal

If a cookie is successfully sent to you from the client, it is available in $_COOKIE, which is automatically global in PHP, if the variables_order directive in php.ini is set to C.

The following code shows how to use $_COOKIE.

If you wish to retreive all the cookies, you may use the following command

headers already sent problem because of cookies

PHP Cookies are part of the HTTP header. Therefore, in a PHP script, if it is not set before any another output is sent to the browser, you will get a warning like «. headers already sent. «.

To get rid of the problem, you may use «Output buffering functions». Following code shows how to add an output buffering function.

How to delete a cookie

To delete a cookie value, you may set the expiry time of the cookie in the past. In the following code snippet, cookie expiry time is set one hour before.

Javascript cookies vs php cookies

This may confuse you if you are just starting out with web programming. But in practice, Cookies are defined by RFC 2965. It is a standard which can be used any programming language. It has nothing to do with PHP vs JavaScript. In PHP, as we have seen in the first example of this tutorial, that cookies can be set such a way that it can’t be accessed by client side JavaScript, but that is a programming feature only.

Cookies vs Sessions

Both cookies and sessions are used for storing persistent data. But there are differences for sure.

Sessions are stored on server side. Cookies are on the client side.

Sessions are closed when the user closes his browser. For cookies, you can set time that when it will be expired.

Sessions are safe that cookies. Because, since stored on client’s computer, there are ways to modify or manipulate cookies.

Hopefully, this tutorial about PHP cookies is useful for you. Let us know if you have questions or suggestions.

Previous: PHP File Upload
Next: XForms

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

What is the difference between public, private, and protected?

  • public scope to make that property/method available from anywhere, other classes and instances of the object.
  • private scope when you want your property/method to be visible in its own class only.
  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

PHP Cookies

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.

Create Cookies With PHP

A cookie is created with the setcookie() function.

Syntax

Only the name parameter is required. All other parameters are optional.

The following example creates a cookie named «user» with the value «John Doe». The cookie will expire after 30 days (86400 * 30). The «/» means that the cookie is available in entire website (otherwise, select the directory you prefer).

We then retrieve the value of the cookie «user» (using the global variable $_COOKIE). We also use the isset() function to find out if the cookie is set:

Example

$cookie_name = «user»;
$cookie_value = «John Doe»;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), «/»); // 86400 = 1 day
?>

if(!isset($_COOKIE[$cookie_name])) echo «Cookie named ‘» . $cookie_name . «‘ is not set!»;
> else echo «Cookie ‘» . $cookie_name . «‘ is set!
«;
echo «Value is: » . $_COOKIE[$cookie_name];
>
?>

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

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

To modify a cookie, just set (again) the cookie using the setcookie() function:

Example

$cookie_name = «user»;
$cookie_value = «Alex Porter»;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), «/»);
?>

if(!isset($_COOKIE[$cookie_name])) echo «Cookie named ‘» . $cookie_name . «‘ is not set!»;
> else echo «Cookie ‘» . $cookie_name . «‘ is set!
«;
echo «Value is: » . $_COOKIE[$cookie_name];
>
?>

To delete a cookie, use the setcookie() function with an expiration date in the past:

Example

echo «Cookie ‘user’ is deleted.»;
?>

Check if Cookies are Enabled

The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:

Example

if(count($_COOKIE) > 0) echo «Cookies are enabled.»;
> else echo «Cookies are disabled.»;
>
?>

Complete PHP Network Reference

For a complete reference of Network functions, go to our complete PHP Network Reference.

Источник

Cookies

PHP transparently supports HTTP cookies. Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This is the same limitation that header() has. You can use the output buffering functions to delay the script output until you have decided whether or not to set any cookies or send any headers.

Any cookies sent to server from the client will automatically be included into a $_COOKIE auto-global array if variables_order contains «C». If you wish to assign multiple values to a single cookie, just add [] to the cookie name.

For more details, including notes on browser bugs, see the setcookie() and setrawcookie() function.

User Contributed Notes 1 note

// Example
// Setting a cookie
setcookie ( «usertoken» , «noice» , time ()+ 20 * 24 * 60 * 60 );
// 20 days = 20*24*60*60 seconds

setcookie ( «usertoken» , «» , time ()- 3600 )
?>

  • Features
    • HTTP authentication with PHP
    • Cookies
    • Sessions
    • Dealing with XForms
    • Handling file uploads
    • Using remote files
    • Connection handling
    • Persistent Database Connections
    • Command line usage
    • Garbage Collection
    • DTrace Dynamic Tracing

    Источник

Оцените статью