Detailed explanation of how to call interfaces and write interface code in php

伊谢尔伦
Release: 2023-03-12 13:08:01
Original
15944 people have browsed it

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')
Copy after login

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 );
Copy after login

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:

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

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
Copy after login

三、实际项目中,我们在开发 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!