Home >Backend Development >PHP Tutorial >PHP setcookie设置Cookie用法(及设置无效的问题)_php技巧

PHP setcookie设置Cookie用法(及设置无效的问题)_php技巧

WBOY
WBOYOriginal
2016-05-17 09:17:311019browse

结果碰到一个问题,setcookie设置了Cookie并没有生效,在浏览器端也没有看到。查了一下,原来是setcookie是通过HTTP请求响应的Header来完成的,需要在请求响应内容输出之前执行(就像其他Header设定一样)。

在php.ini中error_reporting = E_ALL的情况下,输出内容之后再setcookie会弹出以下提示:

复制代码 代码如下:

Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\b.php:2) in … on line …

但因为当时php.ini设置成了error_reporting = E_ALL & ~E_NOTICE,于是没有任何提示,所以开发的时候还是建议设成error_reporting = E_ALL 方便观察到一些异常情况。

附一个setcookie用法实例
a.php
复制代码 代码如下:

setcookie("page", "a.php");
$page = $_COOKIE["page"] ? $_COOKIE["page"] : "unknown";
echo "From " . $page . "

";
?>
This is a.php. Go to b.php

b.php
复制代码 代码如下:

setcookie("page", "b.php");
$page = isset($_COOKIE["page"]) ? $_COOKIE["page"] : "unknown";
echo "From " . $page . "

";
?>
This is b.php. Go to a.php
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