search
HomeBackend DevelopmentPHP Tutorialphp setcookie(name, value, expires, path, domain, secure) 参数详解_php技巧

setcookie() 定义一个和其余的 HTTP 标头一起发送的 cookie。和其它标头一样,cookie 必须在脚本的任何其它输出之前发送(这是协议限制)。这需要将本函数的调用放到任何输出之前,包括 和 标签以及任何空格。如果在调用 setcookie() 之前有任何输出,本函数将失败并返回 FALSE。如果 setcookie() 函数成功运行,将返回 TRUE。这并不说明用户是否接受了 cookie。
函数定义:
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )
setcookie() 参数详解
参数        说明 举例
name cookie的名字 使用 $_COOKIE['cookiename'] 调用名为 cookiename 的 cookie。
value cookie的值,存放在客户端,不要存放敏感数据 假定 name 是 'cookiename',可以通过$_COOKIE['cookiename'] 取得其值。
expire

Cookie 过期的时间。这是个 Unix 时间戳,即从 Unix 纪元开始的秒数。  

换而言之,通常用 time() 函数再加上秒数来设定 cookie 的失效期。

或者用mktime()来实现。

time()+60*60*24*30 将设定 cookie 30 天后失效。

如果未设定,cookie 将会在会话结束后(一般是浏览器关闭)失效。

path Cookie 在服务器端的有效路径。

如果该参数设为 '/' 的话,cookie 就在整个 domain 内有效,

如果设为 '/foo/',cookie 就只在 domain 下的 /foo/ 目录及其子目录内有效,例如 /foo/bar/

默认值为设定 cookie 的当前目录。

domain 该 cookie 有效的域名。

要使 cookie 能在如 example.com 域名下的所有子域都有效的话,该参数应该设为 '.example.com'

虽然 . 并不必须的,但加上它会兼容更多的浏览器。

如果该参数设为www.example.com 的话,就只在 www 子域内有效。

细节见Cookie 规范中的 tail matching。

secure

指明 cookie 是否仅通过安全的 HTTPS 连接传送。

当设成 TRUE 时,cookie 仅在安全的连接中被设置。默认值为FALSE

0 或 1

例子 1. setcookie() 发送例子
复制代码 代码如下:

$value = 'something from somewhere';
setcookie("TestCookie", $value);
setcookie("TestCookie", $value,time()+3600);  /* expire in 1 hour */
setcookie("TestCookie", $value,time()+3600, "/~rasmus/", ".utoronto.ca", 1); 

注意 cookie 中值的部分在发送的时候会被自动用 urlencode 编码并在接收到的时候被自动解码并把值赋给与自己同名的 cookie 变量。如果不想这样并且在使用 PHP 5 的话,可以用 setrawcookie() 来代替。下面这个简单的例子可以得到刚才所设定的 cookie 的值:
复制代码 代码如下:

// 输出单独的 cookie
echo $_COOKIE["TestCookie"];
echo $HTTP_COOKIE_VARS["TestCookie"];
// 另一个调试的方法就是输出所有的 cookie
print_r($_COOKIE);
?>

要删除 cookie 需要确保它的失效期是在过去,才能触发浏览器的删除机制。下面的例子说明了如何删除刚才设置的 cookie:
例子 2. setcookie() 删除例子
复制代码 代码如下:

// 将过期时间设为一小时前
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1); 

也可以通过在 cookie 名称中使用数组符号来设定数组 cookie,可以设定多个 cookie 作为数组单元,在脚本提取 cookie 时所有的值都放在一个数组种:
例子 3. setcookie() 中使用数组的例子
复制代码 代码如下:

// 设定 cookie
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// 刷新页面后,显示出来
if (isset($_COOKIE['cookie'])) {
    foreach ($_COOKIE['cookie'] as $name => $value) {
        echo "$name : $value
\n";
    }
}
?>

上例将输出:
three : cookiethree
two : cookietwo
one : cookieone

总结:cookie的基本使用不难,这篇文章记录的重点主要是掌握path的路径设置和domain的域名设置。


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)