search
HomeBackend DevelopmentPHP TutorialDetailed explanation of app interface token

Detailed explanation of app interface token

Mar 05, 2018 pm 01:05 PM
tokeninterfaceDetailed explanation

1. First of all, let’s talk about what an interface is: Simply put, an interface is a bridge used by the server to return data to other programs or clients

2. The function of the interface: return according to fixed parameters Fixed data, for example, if the client passes a=1, then the server will return a's name, if the client passes a=2, the server will return a's gender, but will not return other data.

3. The role of signature: to ensure the security of interfaces and data

4. The role of token: the same as the PC login session, as the only ticket for user entry

For example: the interface between the app and the server, the interface between different programs between java and php, these interfaces generally transmit data in json format

So in order to ensure the relative security of data transmission between the mobile terminal and the server, the interface needs to be encrypted Transmission

1. Design purpose of token:
Because the APP side does not have the same session mechanism as the PC side, it cannot determine whether the user is logged in and cannot maintain the user status, so a mechanism is needed to achieve this. Session, this is the role of token. The token is the only ticket for the user to log in. As long as the token sent by the APP is consistent with the server, it can prove that you have logged in (just like when you go to a movie, you need to buy a ticket, just hold the ticket) Can enter)

2. Types of token design:
(1) Third-party login type: This token is shaped like WeChat’s access_token. The design principle is based on OAuth2.0. Its characteristics It is refreshed regularly (for example, refreshed every two hours). The purpose is because when the data source gives login permission to a third-party server, it must control its validity period and permissions. Otherwise, the third-party server can obtain users from the data source server indefinitely without the user's consent. Arbitrary data

(2) APP self-use login type: This kind of token is the token used by general APPs. Because it does not go through a third party, but the user directly obtains the data source server data, so the design is more casual, and only needs Just ensure the uniqueness of its token

3. Implementation steps for APP self-use login token:
(1) Add the token field and time_out token expiration time field to the database user table
(2) User login (also required for automatic login during registration) generate a token and the expiration time and store it in the table
(3) Before calling other interfaces, judge whether the token is correct. If it is correct, continue, if it is wrong, let the user log in again

4. APP self-use login token implementation code (company’s self-use framework and logic, mainly depends on the logic, do not copy the code directly):

(1)//下面是用户登陆时把token插入数据库的代码
$logininfo['token'] = appuser::settoken();
$time_out = strtotime("+7 days");
db::setByPk('u_adver', array('token1' => $logininfo['token'], 'time_out' => $time_out), $logininfo['id']);


(2)//下面是生成token方法代码
    public static function settoken()
    {
        $str = md5(uniqid(md5(microtime(true)),true));  //生成一个不会重复的字符串
        $str = sha1($str);  //加密
        return $str;
    }

(3)//下面是每个接口都必须调用的token验证代码,验证具体实现是在(4)
$args['token'] = $_POST['token'];
$tokencheck = appuser::checktokens($args['token'], 'u_adver');
        if ($tokencheck != 90001)
        {
            $res['msg_code'] = $tokencheck;
            v_json($res);
        }


(4)//token验证方法,db::是数据库操作类,这里设置是token如果七天没被调用则需要重新登陆(也就是说用户7天没有操作APP则需要重新登陆),如果某个接口被调用,则会重新刷新过期时间
    public static function checktokens($token, $table)
    {
        $res = db::getOneForFields($table, 'time_out', 'token1 = ?', array($token));
        if (!empty($res))
        {
            if (time() - $res['time_out'] > 0) 
            {
                return 90003;  //token长时间未使用而过期,需重新登陆
            }
            $new_time_out = time() + 604800;//604800是七天
            if (db::setWhere($table, array('time_out' => $new_time_out), 'token1 = ?', array($token)))
            {
                return 90001;  //token验证成功,time_out刷新成功,可以获取接口信息
            }
        }
        return 90002;  //token错误验证失败
    }

Related recommendations:

PHP WeChat Methods for public accounts to verify tokens, reply content, and push messages

PHP development APP interface video tutorial

Share about writing php app interfaces and return json data example

The above is the detailed content of Detailed explanation of app interface token. 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
PHP's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor