Php set cookie with header

PHP Cookies

Summary: in this tutorial, you’ll learn about cookies and how to use the PHP setcookie() function to manage cookies effectively.

Introduction to cookies

The web works based on the HTTP protocol. The HTTP protocol is stateless.

When the web browser requests a page from a web server, the webserver responds with the page content. Later, the same web browser requests the same page again, and the webserver has no information that the request is from the same web browser.

Cookies solve this stateless challenge.

A cookie is a piece of data that a web server sends to the web browser. The web browser may store it and send it back in the subsequent requests to the same web server. The web server knows that two requests come from the same web browser by using the same cookie.

Cookies are also known as web cookies, HTTP cookies, or browser cookies. We’ll use the cookies to make it short.

The following flow chart illustrates how cookies work:

PHP cookie

  • First, the web browser sends a request to the web server. The web server doesn’t have any information about the web browser. The web server creates a cookie with a name return and a value 1 and attaches the cookie to the HTTP response header. To create a cookie, you’ll use the setcookie() function.
  • Second, the web browser stores the cookie.
  • Third, the web browser sends the second request with the stored cookie in the header of the HTTP request to the web server. On the web server, PHP can access the cookie via the $_COOKIE superglobal variable and do something accordingly.
  • Finally, the web server responds with the content of the request. Typically, it responds to the web browser with the content based on the value of the cookie.

A web browser can store a cookie with a maximum size of 4KB. However, it’s different between web browsers.

A cookie has an expiration date. Typically, web browsers store cookies for a specific duration. And the web server can specify the expired time for a cookie.

A cookie also stores the web address (URL) that indicates the URL which created the cookie. And the web browser can send back the cookie that was originally set by the same web address. In other words, a website won’t be able to read a cookie set by other websites.

Most modern web browsers allow users to choose to accept cookies. Therefore, you should not wholly rely on cookies for storing critical data.

Why using cookies

In general, websites use cookies to enhance user experiences. For example, you would have to log in to a website again after you leave it without cookies.

Typically, you’ll use cookies for the following purposes:

  • Session management: cookies allow a website to remember users and their login information or anything else that the web server should remember.
  • Personalization: cookies can store user’s preferences, themes, and other settings.
  • Tracking: cookies store user behavior. For example, on an Ecomerce website, you can use cookies to record the products that users previously viewed. Later, you can use this information to recommend the related products that users might be interested in.
Читайте также:  What is an argument list in java

PHP makes it easy to work with cookies using the setcookie() function. The setcookie() function allows you to send an HTTP header to create a cookie on the web browser.

 setcookie ( string $name , string $value = "" , int $expires = 0 , string $path = "" , string $domain = "" , bool $secure = false , bool $httponly = false ): boolCode language: HTML, XML (xml)

The following table illustrates the arguments of the setcookie() function:

Argument Meaning
$name The name of the cookie
$value The value of the cookie. It can be any scalar value such as string or integer.
$expires The time (in a UNIX timestamp) the cookie expires. If $expires is not set or set to 0, the cookie will expire when the web browser closes.
$path The path on the webserver on which the cookie will be available. For example, if the path is ‘/’, the cookie will be available within the domain.
$domain The domain to which the cookie will be available.
$secure if $secure is set to true , the cookie should be transmitted over a secured HTTP (HTTPS) connection from the web browser.
$httponly if $httponly is true, the cookie can be accessed only via the HTTP protocol, not JavaScript.

As of PHP 7.3.0, you can use the same setcookie() function with an alternative signature:

setcookie ( string $name , string $value = "" , array $options = [] ) : boolCode language: PHP (php)

The $options argument is an array that has one or more keys, such as expires , path , domain , secure , httponly and samesite . The samesite can take a value of None , Lax , or Strict . If you use any other key, the setcookie() function will raise a warning.

The setcookie() function returns true if it successfully executes. Notice that it doesn’t indicate whether the web browser accepts the cookie or not. The setcookie() function returns false if it fails.

The $_COOKIE an associative array that stores the HTTP cookies. To access a cookie by a name, you use the following syntax:

$_COOKIE['cookie_name']Code language: PHP (php)

If the cookie name contains dots ( . ) and spaces ( ‘ ‘ ), you need to replace them with underscores ( _ ).

To check if a cookie is set, you use the isset() function:

 if(isset($_COOKIE['cookie_name'])) Code language: HTML, XML (xml)

The $_COOKIE is a superglobal variable, so it can be accessed from anywhere in the script.

Before reading a cookie value, you should always check if it has been set by using the isset() function:

 if (isset($_COOKIE['cookie_name'])) < // process the cookie value >Code language: HTML, XML (xml)

To check if a cookie equals a value, you use the following code:

 if (isset($_COOKIE['cookie_name']) && $_COOKIE['cookie_name'] == 'value') < // . >Code language: HTML, XML (xml)

If you don’t use a cookie, you can force the browser to delete it. PHP doesn’t provide a function that directly deletes a cookie. However, you can delete a cookie using the setcookie() function by setting the expiration date to the past.

The following code deletes a cookie with the cookie_name in the subsequent page request:

unset($_COOKIE['cookie_name']); setcookie('cookie_name', null, time()-3600); Code language: PHP (php)

The following example shows how to use a cookie to display a greeting message to a new or returning visitor.

 define('ONE_WEEK', 7 * 86400); $returning_visitor = false; if (!isset($_COOKIE['return'])) < setcookie('return', '1', time() + ONE_WEEK); > else < $returning_visitor = true; > echo $returning_visitor ? 'Welcome back!' : 'Welcome to my website!'; Code language: HTML, XML (xml)

First, define a constant that stores one week in second:

define('ONE_WEEK', 7 * 86400); Code language: JavaScript (javascript)

Second, set the returning_visitor to false:

$returning_visitor = false;Code language: PHP (php)

Third, check the cookie with the name return. If the cookie is not set, create it with the value one and the expiration date one week. Otherwise, set the $returning_visitor variable to true.

if (!isset($_COOKIE['return'])) < setcookie('return', '1', time() + ONE_WEEK); > else < $returning_visitor = true; >Code language: PHP (php)

Finally, display the greeting message based on the value of the $returning_visitor variable.

When you request the page for the first time, you’ll see the following message:

And if you open the web developer tool, you’ll see the cookie as shown in the following picture:

Since the web browser already stores the cookie with the name return and value 1 , if you refresh the page, you’ll see a different message:

This cookie will last for seven days set by the webserver. Of course, from the web browser, you can manually delete the cookie.

Summary

  • A cookie is a piece of data that the web server sends to a web browser to check if two requests come from the same web browser.
  • Use the PHP setcookie() function to set a cookie that is sent along with HTTP header from the web server to the web browser.
  • Use the superglobal variable $_COOKIE to access the cookies in PHP.

Источник

HTML Cookies From PHP

If you’re looking for a basic introduction that explains what Cookies are, this is not it, try HTML Cookie Introduction. If you’re looking for a tutorial on how to deal with Cookies with javascript, see my tutorial HTML Cookies From Javascript. This short tutorial tells you what’s possible from PHP, and how to accomplish that. It will not explain Cookies, the Set-Cookie header, or tell you what the attributes of a Cookie mean. See HTML Cookie Introduction for that.

How do you look at the Cookies sent from the browser?

You can get a raw look at the Cookies, by looking at the Cookie header that was sent.

They’ll look just like they did in the Cookie header, so you’ll see something like

The cookies that come to you from the browser are ones that you set before. The browser sends them along with a request for the page your PHP code runs in only if the Domain, Path, and Secure attributes match the URL of your page.

Conveniently PHP Puts Cookies In An Associative Array

Instead of dealing with the raw Cookies, we can deal with an array provided for us by PHP. It’s called the $_COOKIE array.

cookie1=$_COOKIE[‘cookie1’]; // value1 cookie2=$_COOKIE[‘user’]; // joe cookie3=$_COOKIE[‘rock’]; // roll

If you weren’t sure if the Cookie was already set, then you’d check first,

A server sets a Cookie by sending a Set-Cookie header to the browser. When you are writing code in PHP that sends Cookies, that’s your job. Get a Set-Cookie header sent.

You have to do it before anything else is sent, because as soon as any part of a page is sent, the headers go just before them. After that, it’s too late. The headers already went.

I’m going to show you two ways to send Cookies from PHP. First you can set any headers you want, including a Set-Cookie header. You can just build the header and send it off. Second, PHP has a set of functions just for dealing with Cookies. I’ll show you those second, so you’ll understand better what they are doing, but the thing to remember, is that the only way to set a Cookie is by sending a Set-Cookie header.

Setting the header directly

PHP has a header() method to set a header. Sending a Cookie from PHP can be as simple as

to set a Cookie named user with the value joe

As detailed in HTML Cookie Introduction (and specified in RFC 6265 — HTTP State Management Mechanism, [If you don’t know what an RFC is, see RFCs and a Script to get them]), the date used with a Set-Cookie header is in Greenwich Mean Time (now called UTC). That means that if you send a Set-Cookie header with an Expires attribute, it needs to be in GMT. To set a cookie to expire in a day, you could do this:

// 24 hr * 60 min/hr * 60 sec/min = 86400 sec $thedate=gmdate(‘D, d M Y H:i:s \G\M\T’,$time()+24*60*60);

time() returns the time in seconds since the Unix Epoch (January 1 1970 00:00:00 GMT). We add to that the number of seconds in a day, to get the time for a day from now. We pass that to gmdate along with a format string that gives exactly the format specified in RFC 6265. You can replace the format string with the predefined constant DATE_COOKIE, but oddly, although it produces a date string that can be parsed according to the rules in RFC 6265, it is not exactly the one that the specification says you should use, substituting dashes for spaces between the day, month and year. Both work, but I like to specify the format string as above, so it agrees with the RFC.

That means that from PHP you can do something like

Makes a cookie named acookie with no value

A cookie named acookie with no value but HttpOnly set to true

A cookie named acookie with value 3 that expires a week into the future

To expire a Cookie, you set the Cookie with the time in the past so that it has already expired. The Cookie should have the same name as it was set with, and in addition should have the same domain, path, and secure attributes as were used to set it. To deal with time drift between machines, it’s safest to use a time a week into the past, but if the times are synchronized, a time one second in the past will delete a Cookie. As an example:

The cookies for this page as seen on the server

Remember, this sets cookies on your machine. The domain will always be the same as the page so that you can set them, and see them. They will always be set to expire when the session is over unless you click the Date in past to delete? button to delete them. The Path is always ‘/’. Secure is never set.

Источник

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