ThinkPHP5开发Api接口简单实例

这个实例实现这样一个功能: 
前端提交学生学号(sno)给Api Api接口返回此学生的基本信息

API接口端

<?php 
namespace app\index\controller;
use think\Controller;
use app\index\model\Student;

class User
{

    public function index() {
        return $this->fetch();
    }


    // 客户端提交学生学号(sno)给api    api返回此学生的基本信息

    public function api($sno='0001') {

        // 查询 并把数据赋值给 $data
        $data = Student::getBysno($sno);
        // 返回数据
        return json($data);
    }

}

(请求端) HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>TP5通过API查询数据</title>
</head>
<body>
    <form action="http://localhost/index.php/index/user/capi/" method="post">
        <input type="text" name="sno">
        <input type="submit" value="提交查询">
    </form>
</body>
</html>

(请求端) C层控制器

<?php 
namespace app\index\controller;
use think\Controller;
class User extends Controller {

    public function index() {
        return $this->fetch();
    }


    public function capi() {

        // http协议请求
        $url = 'http://localhost/index.php/index/index/api/';
        // input('sno') 是前端的from传过来的name值
        $ch = curl_init($url.'?sno='.input('sno'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行 并把执行后的数据赋值给 $data
        $data = curl_exec($ch);
        // 关闭
        curl_close($ch);
        // 返回数据
        return $data;
    }

}

一、服务端部分

[php]  view plain  copy
  1. <?php  
  2.   
  3. require 'conn.php';  
  4. header('Content-Type:text/html;charset=utf-8');  
  5.   
  6. $action = $_GET['action'];  
  7. switch ($action) {  
  8.   
  9.     //注册会员  
  10.     case"adduserinfo";  
  11.         $username = lib_replace_end_tag(trim($_GET['username']));  
  12.         $password2 = lib_replace_end_tag(trim($_GET['userpassword']));  
  13.         $password = md5("$password2" . ALL_PS);  
  14.         $email = lib_replace_end_tag(trim($_GET['email']));  
  15.   
  16.         if ($username == '' || $password2 == '' || $password == '') {  
  17.             $res = urlencode("参数有误");  
  18.             exit(json_encode($res)); //有空信息  
  19.         }  
  20.   
  21.         $sql = "select username from `member` where username='$username'";  
  22.         $query = mysql_query($sql$conn);  
  23.         $count = mysql_num_rows($query);  
  24.   
  25.         if ($count > 0) {  
  26.             exit(json_encode(1)); //返回1表示注册失败  
  27.         } else {  
  28.   
  29.             $addsql = "insert into `member` (username,password,email) values ('$username','$password','$email')";  
  30.             mysql_query($addsql);  
  31.             exit(json_encode(0)); //返回0表示注册成功  
  32.         }  
  33.         break;  
  34.   
  35.   
  36.     //查询用户信息  
  37.     case"selectuserinfo";  
  38.         $username = lib_replace_end_tag($_GET['username']);  
  39.         $sql = "select id,username,nickname,mobile from `member` where username='$username'";  
  40.         $query = mysql_query($sql$conn);  
  41.         $row = mysql_fetch_array($query);  
  42.         foreach ($row as $key => $v) {  
  43.             $res[$key] = urlencode($v);  
  44.         }  
  45.         exit(json_encode($res));  
  46.         break;  
  47.   
  48.   
  49.     //会员登录  
  50.     case"userlogin";  
  51.         $username = lib_replace_end_tag($_GET['username']);  
  52.         $password2 = lib_replace_end_tag(trim($_GET['userpassword']));  
  53.         $password = md5("$password2" . ALL_PS);  
  54.         $sqluser = "select id,username,password from `member` where username='" . $username . "' and password='" . $password . "'";  
  55.         $queryuser = mysql_query($sqluser);  
  56.         $rowuser = mysql_fetch_array($queryuser);  
  57.         if ($rowuser && is_array($rowuser) && !empty($rowuser)) {  
  58.             if ($rowuser['username'] == $username && $rowuser['password'] == $password) {  
  59.                 if ($rowuser['password'] == $password) {  
  60.                     $res = urlencode("登录成功");  
  61.                     exit(json_encode($res));  
  62.                 } else {  
  63.                     $res = urlencode("密码错误");  
  64.                     exit(json_encode($res));  
  65.                 }  
  66.             } else {  
  67.                 $res = urlencode("用户名不存在");  
  68.                 exit(json_encode($res));  
  69.             }  
  70.         } else {  
  71.             $res = urlencode("用户名密码错误");  
  72.             exit(json_encode($res));  
  73.         }  
  74.         /* 
  75.          * 0:表示登录成功,1:表示密码错误,2:用户名不存在,3:用户名密码错误 
  76.          */  
  77.         break;  
  78.   
  79.     default:  
  80.         exit(json_encode(error));  
  81. }  
  82. ?>  

二、客户端部分

[php]  view plain  copy
  1. <?php  
  2.   
  3. header('Content-Type:text/html;charset=utf-8'); //避免输出乱码  
  4.   
  5. function httpPost($url$parms) {  
  6.     $url = $url . $parms;  
  7.     if (($ch = curl_init($url)) == false) {  
  8.         throw new Exception(sprintf("curl_init error for url %s."$url));  
  9.     }  
  10.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  11.     curl_setopt($ch, CURLOPT_HEADER, 0);  
  12.     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600);  
  13.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
  14.     if (is_array($parms)) {  
  15.         curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data;'));  
  16.     }  
  17.     $postResult = @curl_exec($ch);  
  18.     $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
  19.     if ($postResult === false || $http_code != 200 || curl_errno($ch)) {  
  20.         $error = curl_error($ch);  
  21.         curl_close($ch);  
  22.         throw new Exception("HTTP POST FAILED:$error");  
  23.     } else {  
  24.         // $postResult=str_replace("\xEF\xBB\xBF", '', $postResult);  
  25.         switch (curl_getinfo($ch, CURLINFO_CONTENT_TYPE)) {  
  26.             case 'application/json':  
  27.                 $postResult = json_decode($postResult);  
  28.                 break;  
  29.         }  
  30.         curl_close($ch);  
  31.         return $postResult;  
  32.     }  
  33. }  
  34.   
  35. $postUrl = "http://pujia.test.com/api/server.php";  
  36.   
  37. $p=$_GET['p'];  
  38. if ($p =="selectuserinfo") {  
  39.   
  40.     $username = $_GET['username'];  
  41.     $parms = "?action=selectuserinfo&username=" . $username . "";  
  42.   
  43. elseif ($p =="adduserinfo") {  
  44.   
  45.     $username = $_GET['username'];  
  46.     $userpassword = $_GET['userpassword'];  
  47.     $parms = "?action=adduserinfo&username=" . $username . "&userpassword=" . $userpassword . "";  
  48.   
  49. elseif ($p =="userlogin") {  
  50.     $username = $_GET['username'];  
  51.     $userpassword = $_GET['userpassword'];  
  52.     $parms = "?action=userlogin&username=" . $username . "&userpassword=" . $userpassword . "";  
  53.   
  54. }  
  55. $res = httpPost($postUrl$parms); //$parms  
  56. $res = json_decode($res);  
  57. print_r(urldecode(json_encode($res)));  
  58. ?>  
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值