Table of Contents
Msimatch - Log In
Home php教程 php手册 php cookie使用方法学习笔记分享

php cookie使用方法学习笔记分享

Jun 06, 2016 pm 08:26 PM
cookie php

在php中cookie与其它程序中没什么两样,cookie都是用来存储信息到客户端,常用用于安全性要求不高的一些应用中,如用户登录记住密码之类的,下面我来给大家介绍

PHP setcookie() 函数向客户端发送一个 HTTP cookie。cookie 是由服务器发送到浏览器的变量。cookie 通常是服务器嵌入到用户计算机中的小文本文件。每当计算机通过浏览器请求一个页面,就会发送这个 cookie。cookie 的名称指定为相同名称的变量。例如,如果被发送的 cookie 名为 "name",会自动创建名为 $user 的变量,包含 cookie 的值。

必须在任何其他输出发送前对 cookie 进行赋值。如果成功,则该函数返回 true,否则返回 false。

1 setcookie(name, value, expire, path, domain, secure)
•name 必需。规定 cookie 的名称。
•value 必需。规定 cookie 的值。
•expire 可选。规定 cookie 的有效期。
•path 可选。规定 cookie 的服务器路径。
•domain 可选。规定 cookie 的域名。
•secure 可选。规定是否通过安全的 HTTPS 连接来传输 cookie。
可以通过 $HTTP_COOKIE_VARS["user"] 或 $_COOKIE["user"] 来访问名为 "user" 的 cookie 的值。在发送 cookie 时,cookie 的值会自动进行 URL 编码。接收时会进行 URL 解码。如果你不需要这样,,可以使用 setrawcookie() 代替。

例,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() 代替。


例,cookie来保存用户登录信息


1、数据库连接配置页面:connectvars.php

复制代码 代码如下:


//数据库的位置
define('DB_HOST', 'localhost');
//用户名
define('DB_USER', 'root');
//口令
define('DB_PASSWORD', '19900101');
//数据库名
define('DB_NAME','test') ;
?>

2、登录页面:logIn.php

复制代码 代码如下:


//插入连接数据库的相关信息
require_once 'connectvars.php';

$error_msg = "";
//判断用户是否已经设置cookie,如果未设置$_COOKIE['user_id']时,执行以下代码
if(!isset($_COOKIE['user_id'])){
    if(isset($_POST['submit'])){//判断用户是否提交登录表单,如果是则执行如下代码
        $dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
        $user_username = mysqli_real_escape_string($dbc,trim($_POST['username']));
        $user_password = mysqli_real_escape_string($dbc,trim($_POST['password']));

        if(!empty($user_username)&&!empty($user_password)){
            //MySql中的SHA()函数用于对字符串进行单向加密
            $query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND "."password = SHA('$user_password')";
            //用用户名和密码进行查询
            $data = mysqli_query($dbc,$query);
            //若查到的记录正好为一条,则设置COOKIE,同时进行页面重定向
            if(mysqli_num_rows($data)==1){
                $row = mysqli_fetch_array($data);
                setcookie('user_id',$row['user_id']);
                setcookie('username',$row['username']);
                $home_url = 'loged.php';
                header('Location: '.$home_url);
            }else{//若查到的记录不对,则设置错误信息
                $error_msg = 'Sorry, you must enter a valid username and password to log in.';
            }
        }else{
            $error_msg = 'Sorry, you must enter a valid username and password to log in.';
        }
    }
}else{//如果用户已经登录,则直接跳转到已经登录页面
    $home_url = 'loged.php';
    header('Location: '.$home_url);
}
?>

   


        Mismatch - Log In
       
   
   
       

Msimatch - Log In


       
                if(empty($_COOKIE['user_id'])){
            echo '

'.$error_msg.'

';
        ?>
       
       

           

                Log In

               
               
                                value="" />
               

               
               
           

   
           

           
       

                }
        ?>
   

3、登入页面:loged.php

复制代码 代码如下:

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks 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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles