PHP Token (token) design
Reprint link: http://www.jb51.net/article/13756.htm
PHP Token design design goal: avoid repeated submission of data. Check the source to see if it is an external submission matching the action to be performed ( If there are multiple logics implemented on the same page, such as adding, deleting, and modifying operations in a PHP file) The token mentioned here is a hidden form item (type=hidden) written to the FORM when the page is displayed. ). The token cannot be plaintext. If it is plaintext, it would be too dangerous, so a certain encryption method must be used. The ciphertext must be reversible. My algorithm is very idiotic, so I used a ready-made method on the Internet.
How to avoid repeated submissions?
An array must be stored in SESSION. This array stores successfully submitted tokens. During background processing, first determine whether the token is in this array. If it exists, it means that it is a repeated submission.
How to check the origin?
Yes option, when this token is generated, the current session_id is added. If someone else copies your html (token copy), when submitting, theoretically the session_id contained in the token is not equal to the current session_id, and this submission can be judged It is an external submission.
How to match the action to be executed?
When tokenizing, the action name of this token must be written into the token, so that during processing, the action can be decoded and compared.
GEncrypt.inc. php:
<?php class GEncrypt extends GSuperclass { protected static function keyED($txt,$encrypt_key){ $encrypt_key = md5($encrypt_key); $ctr=0; $tmp = ""; for ($i=0;$i<strlen($txt);$i++){ if ($ctr==strlen($encrypt_key)) $ctr=0; $tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1); $ctr++; } return $tmp; } public static function encrypt($txt,$key){ //$encrypt_key = md5(rand(0,32000)); $encrypt_key = md5(((float) date("YmdHis") + rand(10000000000000000,99999999999999999)).rand(100000,999999)); $ctr=0; $tmp = ""; for ($i=0;$i<strlen($txt);$i++){ if ($ctr==strlen($encrypt_key)) $ctr=0; $tmp.= substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1)); $ctr++; } return base64_encode(self::keyED($tmp,$key)); } public static function decrypt($txt,$key){ $txt = self::keyED( base64_decode($txt),$key); $tmp = ""; for ($i=0;$i<strlen($txt);$i++){ $md5 = substr($txt,$i,1); $i++; $tmp.= (substr($txt,$i,1) ^ $md5); } return $tmp; } } ?>
(1) granteToken Parameter: formName, which is the action name, key is the encryption/decryption key.
Returns a string in the form: encryption (formName: session_id)
(2) isToken Parameter: token That is The result generated by granteToken, formName, action name, and whether fromCheck check the origin, if true, also determine whether the session_id in the token is consistent with the current session_id.
(3) dropToken, when an action is successfully executed, call this function and record the token into the session.
GToken.inc.php
<?php /** * 原理:请求分配token的时候,想办法分配一个唯一的token, base64( time + rand + action) * 如果提交,将这个token记录,说明这个token以经使用,可以跟据它来避免重复提交。 * */ class GToken { /** * 得到当前所有的token * * @return array */ public static function getTokens(){ $tokens = $_SESSION[GConfig::SESSION_KEY_TOKEN ]; if (empty($tokens) && !is_array($tokens)) { $tokens = array(); } return $tokens; } /** * 产生一个新的Token * * @param string $formName * @param 加密密钥 $key * @return string */ public static function granteToken($formName,$key = GConfig::ENCRYPT_KEY ){ $token = GEncrypt::encrypt($formName.":".session_id(),$key); return $token; } /** * 删除token,实际是向session 的一个数组里加入一个元素,说明这个token以经使用过,以避免数据重复提交。 * * @param string $token */ public static function dropToken($token){ $tokens = self::getTokens(); $tokens[] = $token; GSession::set(GConfig::SESSION_KEY_TOKEN ,$tokens); } /** * 检查是否为指定的Token * * @param string $token 要检查的token值 * @param string $formName * @param boolean $fromCheck 是否检查来路,如果为true,会判断token中附加的session_id是否和当前session_id一至. * @param string $key 加密密钥 * @return boolean */ public static function isToken($token,$formName,$fromCheck = false,$key = GConfig::ENCRYPT_KEY){ $tokens = self::getTokens(); if (in_array($token,$tokens)) //如果存在,说明是以使用过的token return false; $source = split(":", GEncrypt::decrypt($token,$key)); if($fromCheck) return $source[1] == session_id() && $source[0] == $formName; else return $source[0] == $formName; } } ?>
Retrieve the token from $_POST and use isToken to judge.
If you want to judge Whether it is a matching action to be executed, you can change the formName in isToken and run it. It is fine, but there is no match. This proves that this is successful.
The above introduces the design of PHP Token, including various aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solutions to invalid login token include checking whether the Token has expired, checking whether the Token is correct, checking whether the Token has been tampered with, checking whether the Token matches the user, clearing the cache or cookies, checking the network connection and server status, logging in again or requesting a new Token. Contact technical support or developers, etc. Detailed introduction: 1. Check whether the Token has expired. The login Token usually has a validity period set. Once the validity period exceeds, it will be considered invalid, etc.

The problem was found in the springboot project production session-out timeout. The problem is described below: In the test environment, the session-out was configured by changing the application.yaml. After setting different times to verify that the session-out configuration took effect, the expiration time was directly set to 8 hours for release. Arrived in production environment. However, I received feedback from customers at noon that the project expiration time was set to be short. If no operation is performed for half an hour, the session will expire and require repeated logins. Solve the problem of handling the development environment: the springboot project has built-in Tomcat, so the session-out configured in application.yaml in the project is effective. Production environment: Production environment release is

The problem of invalid login token can be solved by checking the network connection, checking the token validity period, clearing cache and cookies, checking login status, contacting the application developer and strengthening account security. Detailed introduction: 1. Check the network connection, reconnect to the network or change the network environment; 2. Check the token validity period, obtain a new token, or contact the developer of the application; 3. Clear cache and cookies, clear browser cache and Cookie, and then log in to the application again; 4. Check the login status.

What is Identity in SQL? Specific code examples are needed. In SQL, Identity is a special data type used to generate auto-incrementing numbers. It is often used to uniquely identify each row of data in a table. The Identity column is often used in conjunction with the primary key column to ensure that each record has a unique identifier. This article will detail how to use Identity and some practical code examples. The basic way to use Identity is to use Identit when creating a table.

1. Function Overview Keyspace notification allows clients to receive events that modify Rediskey changes in some way by subscribing to channels or patterns. All commands that modify key keys. All keys that received the LPUSHkeyvalue[value…] command. All expired keys in the db database. Events are distributed through Redis's subscription and publishing functions (pub/sub), so all clients that support subscription and publishing functions can directly use the keyspace notification function without any modifications. Because the current subscription and publishing functions of Redis adopt a fireandforget strategy, if your program

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to the problem that the php session disappears after refreshing: 1. Open the session through "session_start();"; 2. Write all public configurations in a php file; 3. The variable name cannot be the same as the array subscript; 4. In Just check the storage path of the session data in phpinfo and check whether the sessio in the file directory is saved successfully.

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains
