MENU

PHP接口设置60秒失效

December 26, 2020 • 原创文章,后端笔记,学习笔记

例子

<?php
$uid = 'Muxiaoguoa';
$time = time();
$key = md5($uid.$time.'HELLOWORLD');
$apiurl = "api.php?uid={$uid}&key={$key}&time={$time}";
echo file_get_contents($apiurl);
?>

代码

<?php
$api = new Api();
$api->infoAction();

class Api {
    /**
     * @todo 根据UID返回用户信息
     * @param int uid 用户ID
     * @param int time 当前时间戳
     * @param int key 秘钥:md5( $uid + $time + 'HELLOWORLD')
     */
    public function infoAction(){
        $default_key = 'HELLOWORLD';//定义秘钥
        /**GET接收参数*/
        $uid = isset($_GET['uid']) ? $_GET['uid'] : '';
        $key = isset($_GET['key']) ? $_GET['key'] : '';
        $time = isset($_GET['time']) ? $_GET['time'] : '';
        
        /**给返回参数默认值*/
        $code = -1;
        $msg = '';
        $data = [];
        
        /* 判断参数 */
        if(!$uid || !$key || !$time){
            $msg = '参数缺失!';
        }else{
            /* 设置60秒失效 */
            if($time - time() > 60 ){
                $msg = '接口已失效!';
            }else{
                /* 判断密钥是否正确 */
                if($key == md5($uid.$time.$default_key)){
                    $code = 1;
                    $data = $this->getuserinfo($uid);
                }else{
                    $msg = '秘钥错误';
                }
            }
        }
        
        $result = [//返回数据统一处理
                'code' => $code,
                'msg' => $msg,
                'data' => $data
        ];
        
        die(json_encode($result,320));//json返回
    }
    
    /**
     * @todo 模拟数据库数据返回
     * @param unknown $uid
     * @return string[]|number[]
     */
    private function getuserinfo($uid){
        $data = [];
        $userArr = [
                /* uid , 年龄 */
                'zhangsan' => ['name'=>'张三', 'age'=>18],
                'lisi' => ['name'=>'李四', 'age'=>19],
                'wangwu' => ['name'=>'王五', 'age'=>20],
                'Muxiaoguo' => ['name'=>'木小果', 'age'=>666]
        ];
        /* 检查键名 UID 是否存在于数组中 */
        if(array_key_exists($uid, $userArr)){
            $data = $userArr[$uid];
        }else{
            $data = 'UID不存在';
        }
        return $data;
    }
}
?>
Archives QR Code
QR Code for this page
Tipping QR Code

感谢以下平台提供云加速支持