步骤5 保护RESTful API
为了保护RESTful API,可以在application/config/rest.php中设置安全保护级别,如下所示:
![]()
$config['rest_auth'] = 'basic';
其中保护级别有如下设置:
None:任何人都可以访问这个API
BASIC:这个设置中,只提供基本的验证方式,适合在内部网络使用
Digest:使用用户名和密码进行验证,比如:$config['rest_valid_logins'] = array('admin' => '1234');
第二部分 调用RESTful服务
接下来,我们讲解如何调用RESTful服务,因为RESTful服务是通过HTTP协议进行发布服务,因此有多种方法进行调用。
1) 通过file_get_contents()调用
可以通过PHP中最简单的file_get_contents()去调用RESTful,比如:
![]()
$user = json_decode(file_get_contents('http://example.com/index.php/api/user/id/1/format/json'));
![]()
echo $user;
要注意的是,要是访问一个受密码保护的RESTful的话,需要用如下形式访问:
![]()
$user = json_decode(
![]()
file_get_contents('http://admin:1234@example.com/index.php/api/user/id/1/format/json')
![]()
);
![]()
echo $user->name;
2)使用cUrl访问RESTful
使用php中的cUrl去访问RESTful服务时最方便稳定的,下面的代码指导如何使用cUrl去设置HTTP协议头,去更新一个指定用户的信息,如下代码所示:
![]()
function native_curl($new_name, $new_email)
![]()
{
![]()
$username = 'admin';
![]()
$password = '1234';
![]()
![]()
// Alternative JSON version
![]()
// $url = 'http://twitter.com/statuses/update.json';
![]()
// Set up and execute the curl process
![]()
$curl_handle = curl_init();
![]()
curl_setopt($curl_handle, CURLOPT_URL, 'http://localhost/restserver/index.php/example_api/user/id/1/format/json');
![]()
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
![]()
curl_setopt($curl_handle, CURLOPT_POST, 1);
![]()
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, array(
![]()
'name' => $new_name,
![]()
'email' => $new_email
![]()
));
![]()
![]()
//本行可选,如果你的RESTful API是开放的,则请删除该行
![]()
curl_setopt($curl_handle, CURLOPT_USERPWD, $username . ':' . $password);
![]()
![]()
$buffer = curl_exec($curl_handle);
![]()
curl_close($curl_handle);
![]()
![]()
$result = json_decode($buffer);
![]()
![]()
if(isset($result->status) && $result->status == 'success')
![]()
{
![]()
echo 'User has been updated.';
![]()
}
![]()
![]()
else
![]()
{
![]()
echo 'Something has gone wrong';
![]()
}
![]()
}
用过PHP的cUrl的朋友应该知道,这里其实是使用cUrl对我们已经发布的RESTful地址进行访问,并提交相关要更新的参数。但是,强大的CodeIgniter为我们封装了更强大的cUrl类库cUrl library(http://codeigniter.com/wiki/Curl_library/),上面的代码可以简化如下:
![]()
function ci_curl($new_name, $new_email)
![]()
{
![]()
$username = 'admin';
![]()
$password = '1234';
![]()
$this->load->library('curl');
![]()
$this->curl->create('http://localhost/restserver/index.php/example_api/user/id/1/format/json');
![]()
//本行可选,如果你的RESTful API是开放的,则请删除该行 $this->curl->http_login($username, $password);
![]()
$this->curl->post(array(
![]()
'name' => $new_name,
![]()
'email' => $new_email
![]()
));
![]()
$result = json_decode($this->curl->execute());
![]()
if(isset($result->status) && $result->status == 'success')
![]()
{
![]()
echo 'User has been updated.';
![]()
}
![]()
else
![]()
{
![]()
echo 'Something has gone wrong';
![]()
}
![]()
}
http://tech.chinaunix.net/a2011/0420/1180/000001180783_3.shtml