登录接口
<?php
class JsonUserAction extends action{
public function login(){
$phone=$_POST['phone'];
//$phone = '153';
if(empty($phone)){
$result=array('err_no' =>1001,'err_msg'=>"unauthorized request"); //非法请求
echo json_encode($result); exit;
}else{
$result=array('err_no' =>0,'err_msg'=>"success"); //成功
echo json_encode($result); exit;
}
}
}
?>
接口测试 (也可以说成调用)
<?php
class ApiTestAction extends action{
public function apitest(){
//get方法调用接口
/*$phone = '153';
$url = 'http://localhost/index.php/JsonUser/login';
//发送选项
$opts = array(
'http'=>array(
'method'=>'POST',
//'timeout'=>15,
)
);
//发送
$context = @stream_context_create($opts);
$result = @file_get_contents($url,false,$context);
$obj = json_decode($result,TRUE); //decod json数据,并转成数组
var_dump($obj);
echo $obj['err_msg'];
if(isset($obj) && $obj['err_no']=0) //得到返回值后,对返回值作相应处理
echo 'OK';
else
echo 'FALSE';*/
$data=array('phone'=>'153', //密码
);
//echo date('y-m-d h:i:s',time());
$data=http_build_query($data);
$opts=array(
'http'=>array(
'method'=>'POST',
'header'=>"Content-type:application/x-www-form-urlencoded\r\n".
"Content-Length:".strlen($data)."\r\n",
'content'=>$data
),
);
$context=stream_context_create($opts);
$html = file_get_contents('http://localhost/index.php/JsonUser/login',false,$context);//http接口地址
echo $html;
$obj = json_decode($html,TRUE); //decod json数据,并转成数组
var_dump($obj);
}
}
?>
============================
例:
//用户登录接口
public function login(){
$phone = $_POST['phone'];
$password = $_POST['password'];
//$phone = '153';
if(empty($phone)){
$result=array('err_no' =>1001,'err_msg'=>"login name is empty"); //用户名为空
echo json_encode($result); exit;
}
if(empty($password)){
$result=array('err_no' =>1002,'err_msg'=>"password id empty"); //密码为空
echo json_encode($result); exit;
}
if(!preg_match("/^1[34578]\d{9}$/", $phone)){
$result=array('err_no' =>1003,'err_msg'=>"login name isnot phone number"); //不是手机号
echo json_encode($result); exit;
}
if(strlen($password)<6 or strlen($password)>16 ){
$result=array('err_no' =>1004,'err_msg'=>"password is wrongful"); //密码长度不在6-16位
echo json_encode($result); exit;
}
//die();
$User = M('user');
$result = $User->where("phone= "."'$phone'".' AND password= '." '$password' ")->find();
if($result){
$result=array('err_no' =>1,'err_msg'=>"success"); //成功
echo json_encode($result); exit;
}else{
$result=array('err_no' =>0,'err_msg'=>"failure"); //失败
echo json_encode($result); exit;
}
}