Home >Backend Development >PHP Problem >How to request interface with token in php
PHP Token(Token)
Token means "token", which is a string of characters generated by the server. An identifier for the client to make the request.
In view of the above characteristics, communication between the mobile terminal and the server requires 2 keys, that is, 2 tokens. (Recommended learning: PHP video tutorial)
The first token is for the interface (api_token);
The second token is for the user (user_token);
Let’s talk about the first token (api_token) first
Its responsibility is to maintain the concealment and effectiveness of interface access and ensure that the interface can only be used by one’s own family. How?
The reference idea is as follows:
Generate a random string based on the common attributes owned by the server and the client. The client generates this string, and the server also generates it according to the same algorithm. A string used to verify the client's string.
The current interface is basically MVC mode, and the URL is basically restful style. The general format of the URL is as follows:
http://blog.snsgou.com/模块名/控制器名/方法名?参数名1=参数值1&参数名2=参数值2&参数名3=参数值3
The interface token generation rules are as follows:
api_token = md5 ('模块名' + '控制器名' + '方法名' + '2013-12-18' + '加密密钥') = 770fed4ca2aabd20ae9a5dd774711de2
1. '2013-12-18' is the time of the day
2. 'Encryption key' is private Encryption key. After the mobile phone needs to register an "Interface User" account on the server, the system will assign an account and password. The data table design reference is as follows:
Field Name Field Type Comment
client_id varchar(20) Client ID
client_secret varchar(20) Client (encryption) key
Server interface verification, PHP implementation process is as follows:
<?php // 1、获取 GET参数 值 $module = $_GET['mod']; $controller = $_GET['ctl'] $action = $_GET['act']; $client_id = $_GET['client_id']; $api_token = $_GET['api_token‘]; // 2、根据客户端传过来的 client_id ,查询数据库,获取对应的 client_secret $client_secret = getClientSecretById($client_id); // 3、服务端重新生成一份 api_token $api_token_server = md5($module . $controller . $action . date('Y-m-d', time()) . $client_secret); // 4、客户端传过来的 api_token 与服务端生成的 api_token 进行校对,如果不相等,则表示验证失败 if ($api_token != $api_token_server) { exit('access deny'); // 拒绝访问 } // 5、验证通过,返回数据给客户端 ?>
The above is the detailed content of How to request interface with token in php. For more information, please follow other related articles on the PHP Chinese website!