methods['users_get']['limit'] = 500; // 500 requests per hour per user/key $this->methods['users_post']['limit'] = 100; // 100 requests per hour per user/key $this->methods['users_delete']['limit'] = 50; // 50 requests per hour per user/key } public function users_get() { // var_dump($this->input->server('REQUEST_METHOD')); // var_dump($this->get('id')); // 参数带id // var_dump($this->get('blah')); // http://www.cirest.com:8889/api/example/users/id/2/di/3 可以传多个参数 // // //通过query获取 url 传参 测试失败? // var_dump($this->query('id')); // var_dump($this->query('blah')); // var_dump($this->query()); // Users from a data store e.g. database $users = [ ['id' => 1, 'name' => 'John', 'email' => 'john@example.com', 'fact' => 'Loves coding'], ['id' => 2, 'name' => 'Jim', 'email' => 'jim@example.com', 'fact' => 'Developed on CodeIgniter'], ['id' => 3, 'name' => 'Jane', 'email' => 'jane@example.com', 'fact' => 'Lives in the USA', ['hobbies' => ['guitar', 'cycling']]], ]; $id = $this->get('id'); // If the id parameter doesn't exist return all the users if ($id === NULL) { // Check if the users data store contains users (in case the database result returns NULL) if ($users) { // Set the response and exit $this->response($users, RestController::HTTP_OK); // OK (200) being the HTTP response code } else { // Set the response and exit $this->response([ 'status' => FALSE, 'message' => 'No users were found' ], RestController::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } // Find and return a single record for a particular user. $id = (int) $id; // Validate the id. if ($id <= 0) { // Invalid id, set the response and exit. $this->response(NULL, RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // Get the user from the array, using the id as key for retrieval. // Usually a model is to be used for this. $user = NULL; if (!empty($users)) { foreach ($users as $key => $value) { if (isset($value['id']) && $value['id'] === $id) { $user = $value; } } } if (!empty($user)) { $this->set_response($user, RestController::HTTP_OK); // OK (200) being the HTTP response code } else { $this->set_response([ 'status' => FALSE, 'message' => 'User could not be found' ], RestController::HTTP_NOT_FOUND); // NOT_FOUND (404) being the HTTP response code } } public function users_post() { // $this->some_model->update_user( ... ); $message = [ 'id' => 100, // Automatically generated by the model 'name' => $this->post('name'), 'email' => $this->post('email'), 'message' => 'Added a resource' ]; $this->set_response($message, RestController::HTTP_CREATED); // CREATED (201) being the HTTP response code } public function users_delete() { // $this->>delete获取不到参数 // 可以使用 url 传参数方式获取 使用 $this->get('id')来接收 // DELETE http://www.cirest.com:8889/api/example/users/2 使用中路由重写了 成/users/id/2 // DELETE http://www.cirest.com:8889/api/example/users/id/2 var_dump($this->get('id')); // 参数带id var_dump($this->get('blah')); // http://www.cirest.com:8889/api/example/users/id/2/blah/3 可以传多个参数 $id = (int) $this->get('id'); var_dump($id); // Validate the id. if ($id <= 0) { // Set the response and exit $this->response(NULL, RestController::HTTP_BAD_REQUEST); // BAD_REQUEST (400) being the HTTP response code } // $this->some_model->delete_something($id); $message = [ 'id' => $id, 'message' => 'Deleted the resource' ]; $this->set_response($message, RestController::HTTP_NO_CONTENT); // NO_CONTENT (204) being the HTTP response code } // 签发Token public function issue_get() { $key = '344'; //key $time = time(); //当前时间 $token = [ 'iss' => 'http://www.helloweba.net', //签发者 可选 'aud' => 'http://www.helloweba.net', //接收该JWT的一方,可选 'iat' => $time, //签发时间 'nbf' => $time, //(Not Before):某个时间点后才能访问,比如设置time+30,表示当前时间30秒后才能使用 'exp' => $time + 7200, //过期时间,这里设置2个小时 'data' => [ //自定义信息,不要定义敏感信息 'userid' => 1, 'username' => '李小龙' ] ]; $jsonList = [ 'access_token' => JWT::encode($token, $key), ]; $this->set_response($jsonList, RestController::HTTP_CREATED); } public function verification_post() { $key = '344'; //key要和签发的时候一样 $jwt = $this->post('access_token'); //签发的Token try { JWT::$leeway = 60;//当前时间减去60,把时间留点余地 $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256方式,这里要和签发的时候对应 $arr = (array)$decoded; print_r($arr); } catch (\Firebase\JWT\SignatureInvalidException $e) { //签名不正确 echo $e->getMessage(); } catch (\Firebase\JWT\BeforeValidException $e) { // 签名在某个时间点之后才能用 echo $e->getMessage(); } catch (\Firebase\JWT\ExpiredException $e) { // token过期 echo $e->getMessage(); } catch (Exception $e) { //其他错误 echo $e->getMessage(); } //Firebase定义了多个 throw new,我们可以捕获多个catch来定义问题,catch加入自己的业务,比如token过期可以用当前Token刷新一个新Token } // 七牛 上传图片测试 public function qiniu_get() { $cfg = [ 'access' => 'K5w2Fe4XowpU6kuklgLlAhGkXWt111WVssI1R0ff', 'secret' => 'i9QhgiUvdO5AgpPnQkPXO6n9wA9jILLeaskqP0Iz', 'bucket' => 'pocoyo_bucket', 'domain' => 'http://pub8vjaao.bkt.clouddn.com' ]; $auth = new Auth($cfg['access'], $cfg['secret']); // 创建一个过期时间为1小时的临时上传令牌 $token = $auth->uploadToken($cfg['bucket'], null, 3600); // 中文名需要转换编码? $filePath = iconv('UTF-8', 'GBK', APPPATH . 'controllers\api\QQ图片20160922141622.png'); $uploadMgr = new UploadManager(); list($ret, $err) = $uploadMgr->putFile($token, null, $filePath); if($err !== null) { $this->err = $err; var_dump($err); } else { echo $cfg['domain'] . '/' . $ret['key']; } } // Chevereto 图床免费版本地址:https://github.com/Chevereto/Chevereto-Free // https://chevereto.com/docs/api-v1 // 上传图片测试 public function chevereto_post() { // 1. 上传本地文件时应使用 $fields post base64_encode方法 // Always use POST when uploading local files. Url encoding may alter the base64 source // due to encoded characters or just by URL request length limit due to GET request. // base64编码 会导致过长 url request // var_dump($_FILES); 参考 uploadimg 可以做一些前置校验处理 // 前置判断 if (empty($_FILES) === false) $key = '5486424e4dfb6b87453dd4bb25c0dcb0'; $url = 'http://172.17.1.110/chevereto/api/1/upload'; // What do we send to chevereto api? $fields = array( 'key' => urlencode($key), // The image encoded in base64 'source' => base64_encode(file_get_contents($_FILES["file"]['tmp_name'])), // format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁 'format' => urlencode('json') ); //open connection $ch = curl_init(); //set the url, number of POST vars, POST data curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, sizeof($fields)); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 240); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect: ')); //execute post $result = curl_exec($ch); //释放curl句柄 curl_close($ch); echo $result; //close connection // 2. 上传远程图片地址可使用 _get source=urlencode{source} 方法即可 // $key = '6a55c7f9fa13813c2da613dc7b5b920b'; // // 设定远程图片地址 // $source = 'https://img3.doubanio.com/view/group_topic/large/public/p67032015.jpg'; // // format: txt / json txt 只返回图片地址或错误信息 eg.Duplicated upload 较为简洁 // $url = 'http://172.17.1.110:8888/api/1/upload/?key={key}&source={source}&format=txt'; // $url = str_replace(array('{key}','{source}'),array($key,urlencode($source)),$url); // // //初始化 // $ch = curl_init(); // //设置选项,包括URL // curl_setopt($ch, CURLOPT_URL, $url); // curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // curl_setopt($ch, CURLOPT_HEADER, 0); // //执行并获取HTML文档内容 // $output = curl_exec($ch); // //释放curl句柄 // curl_close($ch); // echo $output; // 失败 // { // "status_txt": "Bad Request", // "error": { // "context": "Exception", // "code": 102, // "message": "Duplicated upload" // }, // "status_code": 400 // } // 成功 // { // "status_txt": "OK", // "image": { // "image": { // "size": "89163", // "url": "http://172.17.1.110:8888/images/2019/07/09/p67032015.jpg", // "extension": "jpg", // "mime": "image/jpeg", // "name": "p67032015", // "filename": "p67032015.jpg" // }, // }, // "success": { // "code": 200, // "message": "image uploaded" // }, // "status_code": 200 // } } }