Home php教程 PHP源码 PHP cookie使用方法与注意事项

PHP cookie使用方法与注意事项

Jun 08, 2016 pm 05:23 PM
cookie nbsp quot setcookie

cookie是一个用于存储信息到客户端浏览器中的我们可以利用cookie来记录用户的一些相关信息,像站长统计代码就基于cookie与ip来实现的,下面我来介绍cookie使用与注意事项。

<script>ec(2);</script>

PHP cookie用法

 代码如下 复制代码

setcookie('mycookie','value');
//函数原型:int setcookie(string name,string value,int expire,string path,string domain,int secure)
echo($mycookie);
echo($HTTP_COOKIE_VARS['mycookie']);
echo($_COOKIE['mycookie']);

删除Cookie

(1)调用只带有name参数的setcookie();
(2)使失效时间为time()或time-1;

 代码如下 复制代码

setcookie('mycookie');或setcookie('mycookie','');或setcookie("mycookie",false);
//setcookie('mycookie','',time()-3600);
echo($HTTP_COOKIE_VARS['mycookie']);
print_r($_COOKIE);

建议删除方法:

 代码如下 复制代码

setcookie('mycookie','',time()-3600);

PHP提供一个很好用的函数mktime()。
你只要按顺序传送给mktime()你希望表示的小时,分钟,秒数,月份,日期,及年份,
mktime()就会返回该日期自1970年1月1日的总秒数。

因此,如果需要模拟 Y2K 问题:

 代码如下 复制代码
$y2k = mktime(0,0,0,1,1,2000);
setcookie('name','value',$y2k);
setcookie('name', 'value', time+3600);
setcookie('name', 'value', $y2k, '~/myhome', '.domain.com');

获取COOKIE过期时间的办法

 代码如下 复制代码

$expire = time() + 86400; // 设置24小时的有效期
setcookie ("var_name", "var_value", $expire); // 设置一个名字为var_name的cookie,并制定了有效期
setcookie ("var_name_expire", $expire, $expire); // 再将过期时间设置进cookie以便你能够知道var_name的过期时间

注:

在发送 cookie 时,cookie 的值会自动进行 URL 编码。接收时会进行 URL 解码。
如果你不需要这样,可以使用 setrawcookie() 代替。

PHP设置、获取与删除COOKIE

 

 代码如下 复制代码

//--------设置COOKIE,1小时后过期------//
setcookie('TestCookie','hello word 秦迷',time()+3600);
//setrawcookie不进行URL编码
header('Content-type: text/html');
 

//查看发送的报头
var_dump(headers_list());#array(2) { [0]=> string(85) "Set-Cookie: TestCookie=hello+word+%C7%D8%C3%D4; expires=Tue, 19-Apr-2011 10:06:14 GMT" [1]=> string(23) "Content-type: text/html" }
echo '
';
echo $_COOKIE['TestCookie'];#hello word 秦迷
//兼容旧版本(淘汰)
if(isset($HTTP_COOKIE_VARS["TestCookie"])){
    echo $HTTP_COOKIE_VARS["TestCookie"];
}
 

echo '
';
//输出所有 cookie
print_r($_COOKIE);#Array ( [key] => value [TestCookie] => hello word 秦迷 )
?>
 


 

 

//-----设置数组COOKIE-------//
setcookie("cookie[one]","oneVal",time()+3600);
setcookie("cookie[two]","twoVal",time()+3600);
 

echo '
';
echo $_COOKIE['cookie']['two'];#twoVal
echo '
';
 

//输出 cookie (在重载页面后)
if (isset($_COOKIE["cookie"]))
{
    foreach ($_COOKIE["cookie"] as $name => $value)
    {
       echo "$name : $value
";
       /**
        * two : twoVal
        * one : oneVal
        */
 

    }
}
 

 

//设置过期,删除COOKIE
//setcookie('TestCookie', '', time() - 3600);
//setcookie('cookie[one]', '', time() - 3600);


方法一:

在PHP里Cookie的使用是有一些限制的。
1、使用setcookie必须在标签之前
2、使用setcookie之前,不可以使用echo输入内容
3、直到网页被加载完后,cookie才会出现
4、setcookie必须放到任何资料输出浏览器前,才送出

由于上面的限制,在使用setcookie()函数时,学会遇到 “Undefined index”、”Cannot modify header information – headers already sent by”…等问题,解决办法是在输出内容之前,产生cookie,可以在程序的最上方加入函数 ob_start();

ob_start :打开输出缓冲区
函数格式:void ob_start(void)
说明:当缓冲区激活时,所有来自PHP程序的非文件头信息均不会发送,而是保存在内部缓冲区。为了输出缓冲区的内容,可以使用ob_end_flush()或flush()输出缓冲区的内容。

方法二:

解决Warning: Cannot modify header information – headers already sent by ……

前几天装了个php的大头贴系统测试,发现报错Warning: Cannot modify header information – headers already sent by ….今天又装openads,还是出现这个问题。怒了。上网找了半天,有人说要在文件开头写上ob_start();,结果失败。后来打开 php.ini 然后把 output_buffering 设为 on 。重起appache,OK。看来这才是解决办法。

特别注意:如果使用utf-8编码,一定要去掉UTF-8中的BOM,这都是因为utf-8编码文件含有的bom原因,而php4,5都是不支持bom的。去掉bom,可以用Notepad++打开转换一下。切记,切记,切记!(这问题害我折腾了半天。)

方法三:

当前设置的Cookie 不是立即生效的,而是要等到下一个页面时才能看到.这是由于在设置的这个页面里
Cookie由服务器传递给客户浏览器,在下一个页面浏览器才能把Cookie从客户的机器里取出传回服务器的原
因。在同一个页面设置Cookie,实际是从后往前,所以如果要在插入一个新的Cookie之前删掉一个,你必须
先写插入的语句,再写删除的语句,否则可能会出现不希望的结果。

删除一个COOKIE时,该COOKIE的值在当前页面仍然是有效的,也就是值还是存在的,在下次请求该页面或其它页面时就不会存在了。也就是说PHP的COOKIE相关操作都是异步的,当前面设置或删除了COOKIE,要等到下次请求时才能正确反应出来。

删除COOKIE时最好不要用setcookie(cookie名)这种方法,这样很容易删除整个COOKIE数组,具体我不细说了,注意就行了,删除COOKIE的最好方法是设有效时间为过去,当浏览器发现COOKIE有效期过后会确发删除COOKIE事件,还有一点要注意的时,设置COOKIE时有几个参数,删除时也要有几个参数,否则容易出错。

Statement of this Website
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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

How to change title bar color on Windows 11? How to change title bar color on Windows 11? Sep 14, 2023 pm 03:33 PM

By default, the title bar color on Windows 11 depends on the dark/light theme you choose. However, you can change it to any color you want. In this guide, we'll discuss step-by-step instructions for three ways to change it and personalize your desktop experience to make it visually appealing. Is it possible to change the title bar color of active and inactive windows? Yes, you can change the title bar color of active windows using the Settings app, or you can change the title bar color of inactive windows using Registry Editor. To learn these steps, go to the next section. How to change title bar color in Windows 11? 1. Using the Settings app press + to open the settings window. WindowsI go to "Personalization" and then

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to turn off private browsing authentication for iPhone in Safari? How to turn off private browsing authentication for iPhone in Safari? Nov 29, 2023 pm 11:21 PM

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

Win10/11 digital activation script MAS version 2.2 re-supports digital activation Win10/11 digital activation script MAS version 2.2 re-supports digital activation Oct 16, 2023 am 08:13 AM

The famous activation script MAS2.2 version supports digital activation again. The method originated from @asdcorp and the team. The MAS author calls it HWID2. Download gatherosstate.exe (not original, modified) from https://github.com/massgravel/Microsoft-Activation-Scripts, run it with parameters, and generate GenuineTicket.xml. First take a look at the original method: gatherosstate.exePfn=xxxxxxx;DownlevelGenuineState=1 and then compare with the latest method: gatheros

See all articles