[英]Beginner intro to CURL and Rest in PHP
我試圖弄清楚如何使用REST並陷入困境。
這是我正在查看的文檔:
Request: https://www.domain.com/shipping/packages?id=5123
/members/login/auth
Authenticates a user and sets the szsess cookie that must be passed into any subsequent API method.
Parameters
email – User's email address
pswd – User's password
我將用來驗證用戶身份,然后將cookie存儲在可以傳遞給API的變量中的PHP代碼是什么?
這是我到目前為止的內容:
<?php
$request = 'https://www.domain.com/shipping/packages?id=5123';
$session = curl_init($request);
print_r($session);
?>
我對所有的CURL和Rest東西都迷失了。
[rant]如果他們使用Cookie進行身份驗證,則它們不是ReSTful。 [/ rant]
為了處理此API,您需要學習執行以下操作(由於其拙劣的實現):
這兩點很簡單。 屁股有點痛。 為了使我們的生活更輕松,我們將在PHP中定義一個API包裝器來執行調用。
<?php
class APIWrap {
private $jarFile = false;
function __construct($jarFile=null) {
if ($jarFile) {
if (file_exists($jarFile)) $this->jarFile = $jarFile;
else {
touch($this->jarFile);
$this->jarFile = $jarFile;
}
}
else {
$this->jarFile = "/tmp/jar-".md5(time()*rand(1,10000000)).".cookie";
}
}
/* The public methods */
public function call_url($url) {
return $this->_call_url($url);
}
public function logIn($email,$password) {
return $this->_call_curl("https://www.domain.com/members/login/auth",array("email" => $email, "pswd" => $password));
}
/* Our curl channel generator */
protected function _call_curl($url,$post=array()) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
if (count($post)) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
curl_setopt($ch, CURLOPT_COOKIEJAR, $this->jarFile);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return curl_exec($ch);
}
}
隨意設置curlopt呼叫-這些呼叫僅供參考。 重要的是CURLOPT_COOKIEJAR 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.