PHP setcookie () function usage

Source: Internet
Author: User
Tags setcookie

Setcookie () syntax

Setcookie (PHP 3, PHP 4, PHP 5)

Setcookie -- send a cookie

Note: bool setcookie (string name [, string value [, int expire [, string path [, string domain [, bool secure])

Example

Write cookie

The code is as follows: Copy code

<? Php
$ Value = 'something from somewhere ';

Setcookie ("TestCookie", $ value );
Setcookie ("TestCookie", $ value, time () + 3600);/* expire in 1 hour */
Setcookie ("TestCookie", $ value, time () + 3600 ,"/~ Rasmus/"," example.com ", 1 );
?>

Read cookie

The code is as follows: Copy code

<? Php
// Print an individual cookie
Echo $ _ COOKIE ["TestCookie"];
Echo $ HTTP_COOKIE_VARS ["TestCookie"];

// Another way to debug/test is to view all cookies
Print_r ($ _ COOKIE );
?>


Delete cookie

The code is as follows: Copy code

<? Php
// Set the expiration date to one hour ago
Setcookie ("TestCookie", "", time ()-3600 );
Setcookie ("TestCookie", "", time ()-3600 ,"/~ Rasmus/"," example.com ", 1 );
?>


Because of the specific cookie and HTTP methods, you must send all cookies before you output any text. Otherwise, PHP will give a warning and the cookie will not be sent. Therefore, this is correct:

The code is as follows: Copy code

<? Php

Setcookie ('name', 'Jeff ');

Echo "Hello Everyone !";

?>

The following is an error:

The code is as follows: Copy code

<? Php

Echo "Hello Everyone !";

Setcookie ('name', 'Jeff ');

?>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.