Home >Backend Development >PHP Problem >How to verify token in php

How to verify token in php

(*-*)浩
(*-*)浩Original
2019-09-19 11:27:146279browse

Token is a token. Its biggest feature is randomness and unpredictability. General hackers or software cannot guess it.

How to verify token in phpSo, what is the role of Token? What is the principle?

Token is generally used in two places - to prevent repeated form submissions and anti-csrf attacks (cross-site request forgery).

Generate a request url (Recommended learning: PHP programming from entry to proficiency)

<?php
$key = &#39;key&#39;; //秘钥 ,非常重要,不参与url传输、秘钥泄露将导致token验证失效
$data[&#39;time&#39;] = time();
$data[&#39;data&#39;] = &#39;data&#39;;
$data[&#39;token&#39;]= md5( md5($key) . md5($data[&#39;time&#39;]) );
// 拼接url
$url = &#39;domain.com/api.php?&#39; . http_build_query($data);

Server-side verification token

<?php
$param = $_GET;
// 验证时间戳
if (!isset($param[&#39;time&#39;]) || intval($param[&#39;time&#39;]) <= 1) {
    exit(&#39;时间戳不正确&#39;);
}
// 设置每个token的过期时间为60秒
if (time() - intval($param[&#39;time&#39;]) > 60) {
    exit(&#39;请求超时&#39;);
}
// 验证token

// 服務器端生成token
$key = &#39;key&#39;; //秘钥
$time = time();
$server_token= md5( md5($key) . md5($param[&#39;time&#39;]) );;
if ($server_token !== $param[&#39;token&#39;]) {
    exit(&#39;token错误&#39;);
}

echo &#39;验证通过&#39;;
// 其他业务逻辑
// ...

The above is the detailed content of How to verify token in php. For more information, please follow other related articles on the PHP Chinese website!

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