search
HomeBackend DevelopmentPHP TutorialDetailed explanation of how to call interfaces and write interface code in php

For example: http://localhost/openUser.php?act=get_user_list&type=json
Here openUser.php is equivalent to an interface, where get_user_list is an API (Get user list), Pay attention to the data type returned being in JSON format.
You only need to execute this link in your PHP code and it will return.
Direct use of GET method

$file_contents = file_get_content('http://localhost/openUser.php?act=get_user_list&type=json')

POST method must use the following (PHP curl support needs to be enabled).

$url = 'http://localhost/openUser.php?act=get_user_list&type=json';
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, $url );
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt ( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
curl_setopt ( $ch, CURLOPT_POST, 1 ); //启用POST提交
$file_contents = curl_exec ( $ch );
curl_close ( $ch );

Writing interfaces in PHP

1. First, briefly answer two questions:
1. Can PHP develop clients?
Answer: No, because PHP is a scripting language and is responsible for completing the S part of the B/S architecture or C/S architecture, that is, the development of the server. (Don’t worry about GTK and WinBinder)
2. Why choose PHP as your first choice for server development?
Answer: Cross-platform (can run under UNIX, LINUX, WINDOWS, Mac OS), low consumption (PHP consumes very few system resources), high operating efficiency (relatively speaking), and the perfect partner of MySQL. It is Free and open source,...

2. How to use PHP to develop API (Application Programming Interface, Application Programming Interface)?

People who have done API should understand that actually developing API is simpler than developing WEB, but the logic may be more complex, because API is actually data output without rendering the page, so there is no MVC ( API only has M and C),
1. Just like WEB development, you first need some relevant parameters. These parameters will be passed by the client, maybe GET or POST. This needs to be agreed upon by the development team. , or develop unified specifications.
2. With parameters, complete data processing according to application requirements, such as: task progress update, APP in-app purchase, data submission at the end of a game, etc.
3. After the data logic is processed, return to the client Related data that need to be used, such as: mission status, in-app purchase results, player information, etc.
How to return the data to the client?
Direct output form, such as: JSON, XML, TEXT, etc.
4. After the client obtains the data you returned, it interacts with the user locally
A simple API example written temporarily:

<?php
$output = array();
$a = @$_GET[&#39;a&#39;] ? $_GET[&#39;a&#39;] : &#39;&#39;;
$uid = @$_GET[&#39;uid&#39;] ? $_GET[&#39;uid&#39;] : 0;
if (empty($a)) {
    $output = array(&#39;data&#39;=>NULL, &#39;info&#39;=>&#39;坑爹啊!&#39;, &#39;code&#39;=>-201);
    exit(json_encode($output));
}
//走接口
if ($a == &#39;get_users&#39;) {
    //检查用户
    if ($uid == 0) {
        $output = array(&#39;data&#39;=>NULL, &#39;info&#39;=>&#39;The uid is null!&#39;, &#39;code&#39;=>-401);
        exit(json_encode($output));
    }
    //假设 $mysql 是数据库
    $mysql = array(
        10001 => array(
            &#39;uid&#39;=>10001,
            &#39;vip&#39;=>5,
            &#39;nickname&#39; => &#39;Shine X&#39;,
            &#39;email&#39;=>&#39;979137@qq.com&#39;,
            &#39;qq&#39;=>979137,
            &#39;gold&#39;=>1500,
            &#39;powerplay&#39;=> array(&#39;2xp&#39;=>12,&#39;gem&#39;=>12,&#39;bingo&#39;=>5,&#39;keys&#39;=>5,&#39;chest&#39;=>8),
            &#39;gems&#39;=> array(&#39;red&#39;=>13,&#39;green&#39;=>3,&#39;blue&#39;=>8,&#39;yellow&#39;=>17),
            &#39;ctime&#39;=>1376523234,
            &#39;lastLogin&#39;=>1377123144,
            &#39;level&#39;=>19,
            &#39;exp&#39;=>16758,
        ),
        10002 => array(
            &#39;uid&#39;=>10002,
            &#39;vip&#39;=>50,
            &#39;nickname&#39; => &#39;elva&#39;,
            &#39;email&#39;=>&#39;elva@ezhi.net&#39;,
            &#39;qq&#39;=>NULL,
            &#39;gold&#39;=>14320,
            &#39;powerplay&#39;=> array(&#39;2xp&#39;=>1,&#39;gem&#39;=>120,&#39;bingo&#39;=>51,&#39;keys&#39;=>5,&#39;chest&#39;=>8),
            &#39;gems&#39;=> array(&#39;red&#39;=>13,&#39;green&#39;=>3,&#39;blue&#39;=>8,&#39;yellow&#39;=>17),
            &#39;ctime&#39;=>1376523234,
            &#39;lastLogin&#39;=>1377123144,
            &#39;level&#39;=>112,
            &#39;exp&#39;=>167588,
        ),
        10003 => array(
            &#39;uid&#39; => 10003,
            &#39;vip&#39; => 5,
            &#39;nickname&#39; => &#39;Lily&#39;,
            &#39;email&#39; => &#39;Lily@ezhi.net&#39;,
            &#39;qq&#39; => NULL,
            &#39;gold&#39; => 1541,
            &#39;powerplay&#39;=> array(&#39;2xp&#39;=>2,&#39;gem&#39;=>112,&#39;bingo&#39;=>4,&#39;keys&#39;=>7,&#39;chest&#39;=>8),
            &#39;gems&#39; => array(&#39;red&#39;=>13,&#39;green&#39;=>3,&#39;blue&#39;=>9,&#39;yellow&#39;=>7),
            &#39;ctime&#39; => 1376523234,
            &#39;lastLogin&#39;=> 1377123144,
            &#39;level&#39; => 10,
            &#39;exp&#39; => 1758,
        ),
    );
    
    $uidArr = array(10001,10002,10003);
    if (in_array($uid, $uidArr, true)) {
        $output = array(&#39;data&#39; => NULL, &#39;info&#39;=>&#39;The user does not exist!&#39;, &#39;code&#39; => -402);
        exit(json_encode($output));
    }
    //查询数据库
    $userInfo = $mysql[$uid];
    
    //输出数据
    $output = array(
        &#39;data&#39; => array(
            &#39;userInfo&#39; => $userInfo,
            &#39;isLogin&#39; => true,//是否首次登陆
            &#39;unread&#39; => 4,//未读消息数量
            &#39;untask&#39; => 3,//未完成任务
        ), 
        &#39;info&#39; => &#39;Here is the message which, commonly used in popup window&#39;, //消息提示,客户端常会用此作为给弹窗信息。
        &#39;code&#39; => 200, //成功与失败的代码,一般都是正数或者负数
    );
    exit(json_encode($output));
} elseif ($a == &#39;get_games_result&#39;) {
    //...
    die(&#39;您正在调 get_games_result 接口!&#39;);
} elseif ($a == &#39;upload_avatars&#39;) {
    //....
    die(&#39;您正在调 upload_avatars 接口!&#39;);
}

Copy code

Click test (for the client, this address is also called directly):

http://www.ezhi.net/api/test/index.php
http://www.ezhi.net/api/test/index.php?a=get_users
http://www.ezhi.net/api/test/index.php?a=get_users&uid=10001
http://www.ezhi.net/api/test/index.php?a=get_users&uid=10002
http://www.ezhi.net/api/test/index.php?a=get_users&uid=10003

三、实际项目中,我们在开发 API 应该注意的几个事项(仅供参考):
1、单文件实现多接口的形式有很多种,例如:if..elseif.. 或 switch 或 动态方法 (也就是TP的这种访问函数体的形式)
2、对于数据的输出最好用json,json具有相当强大的跨平台性,市场上各大主流编程语言都支持json解析,json正在逐步取代xml,成为网络数据的通用格式
3、接口安全,一定要增加接口验证。例如,客户端和服务端针对不同接口统一做好加密方式,服务端在对于每次接口需要都要进行验证。以保证防止接口被恶意刷新或黑客恶意调用,尤其是大型商业应用。
4、对于线上的 API 必须保证所有接口正常且关闭所有的错误信息 => error_reporting(0),在输出JSON 时,不能有任何其它输出,否则,客户端将解析数据失败,直接 Crash!
5、开发 API 和 WEB 有一定的区别,如果是 WEB 的话,可能代码出错了,不会导致特别严重的错误,也许只是导致数据写入和查询失败,也许导致 WEB 的某个部分错位或乱码。但如果是 API,直接 Crash!
6、做接口开发,不建议使用框架开发,原因概括起来有两点(其实我有点冒风险的,本人也是 TPer 一枚,毕竟这是TP的官网):
  1)客户端一般对服务端的响应速度有极高要求,因此,使用最原生态的 PHP 完成接口开发,是最高效的,假如用到了框架,还需要加载各种不需要多余的文件,就好比夏天穿了件冬天的衣服。试想,你在玩手机的时候,使用一个应用随便一个操作,等半天才有动静,你受的了吗?

  2)就是上面第4点提到的,框架对于WEB开发,是件很幸福的事,但对于 API 而言,你实在不敢想象它会给你出什么岔子!最后你将痛苦不堪~~因为很多框架都是为 WEB 诞生的(我也很期待有一天能看到专门为开发 API 而生的框架或者扩展)

  这个也有人纠结,接口效率与稳定性,还得看编码的人,有的人可能写的还不如框架跑的快,也有人觉得用框架没什么问题,这里只是建议,关键看自己的实际情况,同时建议代码上线前压测一下

  说到这,不得不说扯一下,腾讯微博淘宝等开放平台。其实那些开放平台,所谓的开放,就是给你提供一个这样的接口,你根据他们提供的技术文档,按他们制定的格式和要求,调它们提供的接口文件(一般都是返回JSON或者XML),你就可以获取到他们的相关信息,例如:QQ用户基本信息、淘宝店铺、商品消息等等。然后在根据这些消息,在你的应用里完成交互。

  其实,ajax 也是调用 API 的接口

The above is the detailed content of Detailed explanation of how to call interfaces and write interface code 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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

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)
1 months 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
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version