search
HomeBackend DevelopmentPHP TutorialDetailed explanation of PHP server-side API and interface development

This time I will bring you a detailed explanation of PHP server-side API and interface development. What are the precautions for PHP server-side API and interface development? The following is a practical case, let's take a look.

I believe everyone has done PHP request API interface to obtain data, such as Taobao API, WeChat public platform, weather query, express query, etc. Some need to refer to the interface document to construct a sign (signature) according to the signature algorithm, or set token, and then send a POST request through curl with parameters to obtain the return data, usually in json or xml format.

But now the situation is reversed. We need to develop the PHP server-side API interface, that is, when others request us, we verify the legitimacy of the request and return the query data.

This situation is actually used in mobile app development. Mobile APP applications often need to request the PHP interface to obtain data, but this request generally does not need to be verified. Different URLs are requested according to different functions, usually Pass parameters in get mode to obtain data directly.

This article briefly talks about the server-side method of verifying the legitimacy of the request and the method of receiving parameters.

Simple get requestFor example: http://www.demo.com/api/get_cat?id=2, requesting this URL will return some data, No matter who uses what programming language the request can get the data.

Then this is obviously not possible when the legality needs to be verified. Therefore, a secret key is needed. At this time, POST is often used to request the url.

For example, there is a signature sign in the passed parameters, and the value is 98888. Of course, there are many ways to generate the sign and it cannot be so simple. I just write it casually here. Then the sign received by the server is 98888. If we agree on 98888 It is legal. At this time, you can verify that this is a legal request by judging whether the sign is 98888.

But this is too simple, it will be cracked all at once, and setting this sign will be meaningless. Therefore, there must be a rule for generating sign. When requesting, the sign parameter is generated according to this rule. When the server receives it, it also generates sign according to this rule. If the generated signs are consistent, it indicates that this is a legal request. Each request will be accompanied by a sign for verification.

There is another kind of verification called token. The token is verified when making the first request. There is no need to verify again within a certain period of time. This requires two steps. The first step is to request the interface for obtaining the token and get the token. The second step is to request the function of the specific interface, and you need to bring the token to pass the parameters. Since the server first stores the token when requesting the token for the first time and then returns it, subsequent requests can verify whether the passed token exists.

Many interface developments use both methods to ensure privacy and security.

Another point is that PHP's CURL module is often used to send POST requests. For example, the other party sends a POST request through curl, curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string), where $post_string is a good way to pass a PHP array. Or is it in json format?

If the PHP array is passed, I will get the parameters directly via $_POST['xx']. If the json format is passed, I seem to have to use file_get_contents('php: //input', 'r') gets the passed json data, and then parses the json to get the parameters.

When should I use the second option?

This has been asked online before, let’s see how everyone answers:

For PHP, JSON and arrays Sometimes the difference is really just a line of code. If I write it, I may just use the first one.

I think if you want your code to be more concise, you can use the second one. I remember that Weixin's php sdk seems to be similar to the second one (of course it is in xml format)

And if the other party If you use Object-oriented directly serialized json, using json will make his code more concise.

The first method, is to transmit the form form POST protocol, PHP will convert the PHP array into the HTTP form format, which is universal across languages, but this This is not a mainstream API protocol, but more like a simulated submission form.

Most API protocols will use JSON POST. The second method is to put JSON data in the HTTP Body. Also cross-language, but more user-friendly as an API. The first method is to directly PHP curl. If the data content is not processed well and content like @/xxx/xxx is passed in the array value, curl will transfer the local file on the server. Please pay attention to precautions.

x-www-form-urlencoded is an RFC standard, there is nothing incompatible, it is not only cross-language, but also across time and space. JSON was developed in recent years. It is not a standard, it is just for convenience.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of PHP callback functions and anonymous functions


phpstudy2018 access directory service permissions


ThinkPHP implements WeChat payment (jsapi payment) process tutorial detailed explanation_php example

The above is the detailed content of Detailed explanation of PHP server-side API and interface development. 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
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Atom editor mac version download

Atom editor mac version download

The most popular open source editor