English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP setcookie() function usage and example

PHP HTTP Reference Manual

The setcookie() function sends Cookie

Syntax

bool setcookie ( string $name [, string $value="" [, int $expire=0 [, string $path="" [, string $domain="" [, bool $secure=false [,bool $httponly=false]]]]]] )

Definition and Usage

It is used to set COOKIES.

 The setcookie() function sends the Cookie once it is defined, along with the remaining HTTP headers to the client. Like other HTTP headers, the Cookie must be sent before any output is generated by the script (due to protocol restrictions). Please call this function before generating any output (including <html> and <head> or spaces).
Once the Cookie is set, it can be read using $_COOKIE when the page is opened next time. The Cookie value also exists in $_REQUEST.

Return value

 If output has been produced before calling this function, setcookie() will fail and return FALSE. If setcookie() runs successfully, it returns TRUE. Of course, this does not mean that the user has accepted the Cookie.

Parameter

NumberParameters and Description
1

name

cookie name

2

value

Cookie value. This value is stored on the user's computer, do not store sensitive information. For example, if the name is 'cookiename', its value can be obtained through $_COOKIE['cookiename'].

3

errno

It contains information about the cookie input.

4

expire

Cookie's expiration time. This is a Unix timestamp, which is the number of seconds since the Unix epoch (Greenwich Mean Time 1970 year 1 month 1 seconds from the Unix epoch (Greenwich Mean Time+60*60*24*30 is to set the Cookie 30 days after expiration. If set to zero, or omitted, the Cookie will expire at the end of the session (i.e., when the browser is closed).

5

path

Cookie's Valid Path. Set it to '/'When the domain parameter is set to '/foo/'Cookie is only valid for the domain in the domain parameter /foo/ Directory and its subdirectories are valid (for example /foo/bar/). The default value is the current directory at the time the Cookie is set.

6

domain

Cookie's Valid Domain/Subdomain. Setting it to a subdomain (for example, 'www.example.com') makes the Cookie valid for this subdomain and its third-level subdomains (for example, w2.www.example.com). To make the Cookie valid for the entire domain (including all its subdomains), just set it to the domain (in this example, 'example.com').

Online Example

Try the following example

<?php
   $input = 'It contains the name of the cookie';
   
   setcookie("TestCookie", $input);
   setcookie("TestCookie", $input, time())+3600); 
   setcookie("TestCookie", $input, time())+3600, "/~rasmus/", "oldtoolbag.com", 1);
?>

PHP HTTP Reference Manual