乐闻世界logo
搜索文章和话题

How can I set a cookie with expire time?

1个答案

1

1. Setting Cookies in JavaScript

In JavaScript, you can create and read cookies using the document.cookie property. To set a cookie with an expiration time, include the expires attribute, whose value must be a GMT-formatted time string.

javascript
function setCookie(name, value, days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toUTCString(); } document.cookie = name + "=" + (value || "") + expires + "; path=/"; } setCookie('user', 'John Doe', 7); // Sets a cookie named 'user' with value 'John Doe' that expires after 7 days.

2. Setting Cookies in PHP

In PHP, use the setcookie() function to set cookies. This function allows direct specification of the expiration time using a Unix timestamp format, as shown below:

php
$name = "user"; $value = "John Doe"; $expire = time() + (86400 * 30); // Expires after 30 days setcookie($name, $value, $expire, "/"); // Sets the cookie

3. Setting Cookies in Python (Flask Framework)

For Python web frameworks like Flask, set cookies on the response object using the set_cookie() method and specify the max_age parameter (in seconds) to control expiration time.

python
from flask import Flask, make_response app = Flask(__name__) @app.route('/') def index(): resp = make_response("Cookie is set") resp.set_cookie('user', 'John Doe', max_age=60*60*24*7) # Expires after one week return resp

Summary

When setting cookies with expiration time, the key is to correctly represent time and date, and to use these representations appropriately in your chosen programming environment. Different languages and frameworks have specific methods for handling cookies, including expiration time. Through the examples above, it is clear that setting cookies with expiration time is straightforward and simple whether implemented on the client-side or server-side.

2024年6月29日 12:07 回复

你的答案