1. 程式人生 > >php寫接口

php寫接口

lec span cal etop color row this 客戶 訪問

<?php
$mysqli = new mysqli(‘localhost‘, ‘root‘, ‘‘,‘jiekou‘);
mysqli_query($mysqli,"set names utf8");
if ($mysqli->connect_error) {
    die(‘Connect Error (‘ . $mysqli->connect_errno . ‘) ‘
            . $mysqli->connect_error);
}
$output = array();

$user_by= $_POST[‘user_by‘];
$uid = $_POST
["uid"]; if (empty($user_by)) { $output = array(‘data‘=>NULL, ‘info‘=>‘this is null!‘, ‘stats‘=>1); exit(json_encode($output)); } if ($user_by == ‘get_userinfo‘) {//調用獲取用戶信息的接口 //查詢數據庫 $sql="select * from user WHERE user_id=$uid"; $result =$mysqli->query($sql);
$userInfo = $result -> fetch_row(); if($userInfo){//如果數據存在輸出數據 $output = array( ‘data‘ => array( ‘userInfo‘ => $userInfo, ), ‘stats‘=>0 ); }else{ $output = array( ‘data‘ => array
( ‘userInfo‘ => $userInfo, ), ‘stats‘=>1 ); } exit(json_encode($output));//把結果反饋給客戶端 } $mysqli->close(); ?>
<?php
$url = ‘http://localhost/jiekou/api.php‘;
$sl_data=array(
    ‘uid‘=>1,
    ‘user_by‘=>‘get_userinfo‘
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);//要訪問的地址
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);//執行結果是否被返回,0是返回,1是不返回
curl_setopt($ch, CURLOPT_POST, 1);// 發送一個常規的POST請求
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($sl_data));
$output = curl_exec($ch);//執行並獲取數據
echo $output;
curl_close($ch);

?>

php寫接口