search
HomeBackend DevelopmentPHP Tutorial PHP中使用cookie跟session

PHP中使用cookie和session

cookie和session不管在java还是php中用的是比较多的,cookie可以看做是客户端技术,session则是服务端技术。像购物车还有网站自动登录都可以用cookie实现,session则比较偏向验证这一块,相比cookie安全性更高,因为session是存储在服务端的,不能随意删除或修改。下面来简单的分享下我的学习心得

1.cookie的使用

如果需要保存cookie可以直接在php页面直接使用setCookie函数来保存cookie使用方法如下

<?php setCookie("username","123456",time()&#43;120);
?>

第一个参数是cookie的键,第二个则是value,第三个表示该cookie什么时候过期单位是秒,time()表示当前时间。这句代码的意思是该cookie在2分钟会过期

更新cookie的方法也是一样。如果是火狐浏览器我们可以看到cookie如下


下面来删除cookie

setCookie($cookiename, '');或者 setCookie($cookiename, NULL);这两种方法都能删除cookie

至于要取得cookie就更简单了,使用$_COOKIE就能取得,批量操作cookie也可以通过这个预定义超全局数组

2.session的使用

(1)启用session

(2)把对象放入session中

 session_start();
  $_SESSION["password"]="123456";

两句话就可以把sessiona保存起来了,就像下面这样

要取出session也是使用$_SESSION取得,删除单个session可以使用unset($_SESSION["password"]),如果是删除全部可以使用session_destroy();


session的真正原理不是那么好理解,要理解的深入也很难,需要深入的话可以使用firebug查看http的请求和响应。当服务器创建好session之后,会给客户端浏览器返回一个

PHPSESID,这个ID就是会话唯一ID.当下次浏览器客户端要取session就会通过这个唯一ID去服务器端取出session信息。如果客户端把cookie禁用了,按照正常的代码,session就不能共享了。这里提供最简单的两种做法

第一种就是URL重写,先判断是否有PHPSESSID如果有则设置session_id(SID的值);

第二种就是修改php.ini里的session.use_trans_sid把值设为1


对于第一种PHP提供了一个常量叫SID可以直接拿来使用,因为这种情况比较极端平时基本上不会遇到。具体的代码就不写了。有需要可以给我写评论,我直接给发过去。

要注意的是php的session也可以存对象,要注意的就是使用前最好把这个对象用require_once引入就好使了


最后针对session的应用,我在网上找了一个特别简单的验证码,代码如下

<?php session_start();
    
    Header("Content-type: image/PNG");
    $im = imagecreate(44,18); 
    $back = ImageColorAllocate($im, 245,245,245); 
    imagefill($im,0,0,$back); 
    $vcodes = "";
    srand((double)microtime()*1000000);
    
    for($i=0;$i<4;$i&#43;&#43;){
    $font = ImageColorAllocate($im, rand(100,255),rand(0,100),rand(100,255)); 
    $authnum=rand(1,9);
    $vcodes.=$authnum;
    imagestring($im, 5, 2&#43;$i*10, 1, $authnum, $font);
    }
    $_SESSION['VCODE'] = $vcodes;

    for($i=0;$i<100;$i&#43;&#43;) 
    {
    $randcolor = ImageColorallocate($im,rand(0,255),rand(0,255),rand(0,255));
    imagesetpixel($im, rand()%70 , rand()%30 , $randcolor); 
    }
    ImagePNG($im);
    ImageDestroy($im);
?>

具体怎么用就不用解释了吧得意

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

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment