Home Backend Development PHP Tutorial Differences and examples of usage between php5 Cookie and Session

Differences and examples of usage between php5 Cookie and Session

Jul 25, 2016 am 08:59 AM

  1. SetCookie("Cookie", "cookievalue",time()+3600, "/forum", ".jbxue.com", 1);
Copy code

1), receive and process Cookies PHP has very good support for receiving and processing cookies. It is completely automatic and has the same principle as FORM variables. It is very simple. For example, if you set a Cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a variable like an ordinary variable named $myCookie. The value of this variable is the value of the Cookie. The same applies to arrays. Another way is to reference PHP's global variable $HTTP_COOKIE_VARS array. Examples are as follows: (assuming these have been set in previous pages and are still valid)

  1. echo $MyCookie;
  2. echo $CookieArray[0];
  3. echo $_COOKIE["MyCookie"];
  4. echo $HTTP_COOKIE_VARS["MyCookie"];
  5. ?>
Copy the code

2) and delete cookies To delete an existing cookie, there are two ways:

  1. 1.SetCookie("Cookie", "");
  2. 2.SetCookie("Cookie", "value" , ​​time()-1 / time() );
Copy code

3) Restrictions on the use of cookies 1. It must be set before the content of the HTML file is output; 2. Different browsers handle cookies inconsistently, and sometimes incorrect results may occur. 3. The restriction is on the client side. The maximum number of cookies that can be created by a browser is 30, and each cookie cannot exceed 4KB. The total number of cookies that can be set by each WEB site cannot exceed 20.

3. Session configuration and application

  1. session_start(); //Initialize session. Need to be in the file header
  2. $_SESSION[name]=value; //Configure Seeeion
  3. echo $_SESSION[name]; //Use session
  4. isset($_SESSION[name]); //Judge
  5. unset($_SESSION[name]); //Delete
  6. session_destroy(); //Consume all sessions
  7. ?>
Copy code

Note: session_register(), session_unregister, session_is_registered are no longer used under php5.

1. Examples of cookie usage

  1. if($_GET['out'])

  2. { //Used to log out cookies
  3. setcookie('id',"");
  4. setcookie('pass ',"");
  5. echo "<script>location.href='login.php'</script>"; //Because cookies do not take effect in time, they will only take effect when you refresh them again, so after logging out Let the page refresh automatically.
  6. }

  7. if($_POST['name']&&$_POST['password']) //If the variables username and password exist, set cookies below

  8. { //Used Set cookies
  9. setcookie('id',$_POST['name'],time()+3600);
  10. setcookie('pass',$_POST['password'],time()+3600);
  11. echo "< ;script>location.href='login.php'"; //Let cookies take effect in time

  12. }

  13. if($_COOKIE['id']&&$_COOKIE[ 'pass'])
  14. { //After cookies are set successfully, used to display cookies
  15. echo "Login successful!
    Username: ".$_COOKIE['id']."
    Password: ".$_COOKIE['pass'];
  16. echo "
    ";
  17. echo "Log out cookies"; //Within double quotation marks, if there are more quotation marks, single quotation marks are required.
  18. }
  19. ?>


  20. Password:
< ;br/>

Copy code

2. Session usage example

  1. //session usage example
  2. session_start();//Start session, must be placed in the first sentence, otherwise an error will occur.
  3. if($_GET['out'])
  4. {

  5. unset($_SESSION['id']);

  6. unset($_SESSION['pass']);
  7. }< /p>
  8. if($_POST['name']&&$_POST['password'])

  9. {
  10. //For setting session
  11. $_SESSION['id']=$_POST['name' ];
  12. $_SESSION['pass']=$_POST['password'];
  13. }

  14. if($_SESSION['id']&&$_SESSION['pass'])

  15. {
  16. echo "Login successful!
    User ID: ".$_SESSION['id']."
    User password: ".$_SESSION['pass'];
  17. echo "< ;br />";
  18. echo "Log out session";
  19. }
  20. ?>
Copy code
  1. User ID:


  2. Password:


Copy code


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 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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles