PHP user logon status operation class code based on session and cookie, sessioncookie

Source: Internet
Author: User

PHP user logon status operation class code based on session and cookie, sessioncookie

1. User Login status operation class UserLogin

<?phpfinal class UserLogin {public function __construct() {}public static function getUserInfo() {if (isset($_COOKIE["user_id"])&&$_COOKIE["user_id"]&&(trim($_COOKIE["user_id"])!="")) {if (isset($_SESSION["USER_INFO"]))return $_SESSION["USER_INFO"];$dao = new UserDao();$user = $dao->find($_COOKIE["user_id"]);if ($user) {$_SESSION["USER_INFO"] = $user;setcookie("docloud_sid", session_id(), time() + 36000);setcookie("user_id", $_COOKIE["user_id"], time() + 36000);if (array_key_exists("selected_prj_id", $_COOKIE))setcookie("selected_prj_id", $_COOKIE["selected_prj_id"], time() + 36000);if (array_key_exists("selected_class_id", $_COOKIE))setcookie("selected_class_id", $_COOKIE["selected_class_id"], time() + 36000);if (array_key_exists("selected_image_id", $_COOKIE))setcookie("selected_image_id", $_COOKIE["selected_image_id"], time() + 36000);if (array_key_exists("test_image_ids", $_COOKIE))setcookie("test_image_ids", $_COOKIE["test_image_ids"], time() + 36000);if (array_key_exists("upload_image_ids", $_COOKIE))setcookie("upload_image_ids", $_COOKIE["upload_image_ids"], time() + 36000);return $user;}}self::clearCookie();return null;}public static function setUserInfo($userInfo) {$_SESSION["USER_INFO"] = $userInfo;setcookie("docloud_sid", session_id(), time() + 36000);setcookie("user_id", $userInfo->getId(), time() + 36000);}public static function isLogin() {if (self::getUserInfo()) {return true;}return false;}public static function delUserInfo() {self::clearCookie();session_destroy();}private static function clearCookie() {setcookie("docloud_sid", "", time() - 36000);setcookie("user_id", "", time() - 36000);setcookie("selected_prj_id", "", time() - 36000);setcookie("selected_class_id", "", time() - 36000);setcookie("selected_image_id", "", time() - 36000);setcookie("test_image_ids", "", time() - 36000);setcookie("upload_image_ids", "", time() - 36000);}}?>

2. the user enters the user name and password for relevant determination.

<? Phprequire_once 'init. php '; // if logged in, logoutif (UserLogin: isLogin () & $ _ COOKIE ["user_id"] = 1) {UserLogin: delUserInfo ();} else if (UserLogin: isLogin () {Utils: redirect ('Welcome ') ;}$ username = null; $ password = null; $ msg = ""; if (isset ($ _ POST ['username']) & isset ($ _ POST ['Password']) {$ username = addslashes (trim (stripslashes ($ _ POST ['username']); $ password = addslashes (trim (stripslashes ($ _ P OST ['Password']); // validate $ errors = LoginValidator: validate ($ username, $ password); if (empty ($ errors )) {// save $ dao = new UserDao (); $ user = $ dao-> findByName ($ username); $ last_login_ip = Utils: getIpAddress (); $ user-> setLastLoginIp ($ last_login_ip); $ now = new DateTime (); $ user-> setLastLoginTime ($ now); $ dao-> save ($ user); UserLogin:: setUserInfo ($ user); Flash: addFlash ('logon successful! '); Utils: redirect ('Welcome');} foreach ($ errors as $ e) {$ msg. = $ e-> getMessage (). "<br>" ;}}?>

The Code tells you about PHP operations based on session and cookie User Logon status.

Next, let's add some knowledge about the differences between Cookies and sessions.

1. cookie is a text string handle sent to the client's browser and saved on the client's hard disk. It can be used to maintain persistent data between sessions of a WEB site.

2. session refers to the period from when a visitor arrives at a specific homepage to when the visitor leaves. The Session actually uses cookies for information processing. After the user first requests the Session, the server creates a Cookie in the user's browser. When the Session ends, in fact, this Cookie expires.

Note: The Cookie name created for this user is aspsessionid. The only purpose of this Cookie is to provide different identity authentication for each user.

3. Cookies and sessions share the following characteristics: Both cookies and sessions are session methods used to track browser user identities.

4. The difference between cookie and session is that cookie data is stored on the client and session data is stored on the server.
To put it simply, when you log on to a website,

· If the web server uses a session, all data is stored on the server. Each time the client requests the server, it sends the sessionid of the current session, the server determines the user data flag based on the current sessionid to determine whether the user is logged on or has certain permissions. Because the data is stored on the server, you cannot forge it. However, if you can obtain the sessionid of a logon user, using a special browser to forge the user's request is successful. Sessionid is randomly allocated when the server and client are connected. Generally, there are no duplicates. However, if there are a large number of concurrent requests, there is no possibility of repetition.

· If the browser uses cookies, all the data is stored in the browser. For example, after you log on to the server and set the cookie user name, when you request the server again, the browser sends a user name to the server. These variables are marked with special characters. The server will be interpreted as a cookie variable, so as long as the browser is not closed, the cookie variable will always be valid, so it can ensure that it remains offline for a long time. If you can intercept a user's cookie variable and then forge a data packet to send it, the server still thinks that you are legal. Therefore, cookie attacks are more likely. If the validity period is set, the cookie is saved on the client's hard disk. When you access the website again, the browser checks whether there is any cookie, read the cookie and send it to the server. If you save a forum cookie on your machine, it will be valid for one year. If someone intrude into your machine, copy your cookie and put it under the directory of his browser, then he logs on to the website as you. Therefore, cookies can be forged. Of course, you need an idea to copy the file directly.

The cookie file is in the cookie Directory, which is not recognized by the browser and has an index. the dat file stores the creation time of the cookie file and whether the file has been modified. Therefore, you must first have the cookie file for the website and cheat the browser from the guaranteed time.

5. both of them can be used to store private things, and both have validity periods. The difference is that the session is placed on the server. Whether the session expires depends on the setting of the service period, and the cookie exists on the client, in the past, whether or not the cookie was generated can be configured.

(1) cookie data is stored in the client's browser, and session data is stored on the server.

(2) Cookies are not very secure. Others can analyze the local cookies and perform cookie spoofing.

(3) The session will be stored on the server for a certain period of time. When the number of accesses increases, it will occupy the performance of your server. If you primarily consider reducing the server performance, you should use cookies

(4) the limit for a single cookie on the client is 3 K, that is, the COOKIE stored on the client on a site cannot be 3 K.

(5) store important information such as login information as SESSION; store other information in cookies if necessary.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.