我必须使用cURL将信息发送到外部网站。我在Laravel应用程序上设置了Guzzle。我已经设置了基础知识,但根据网站的文档,有一个用户名和密码所需的操作。如何将“操作”与登录和访问所需的凭据一起传递?
该网站声明:
curl [-k] –dump-header <header_file> -F “action=login” -F “username=<username>” -F “password=<password>” https://<website_URL>
我的控制器:
$client = new \GuzzleHttp\Client();
$response = $client->get('http://website.com/page/login/', array(
'auth' => array('username', 'password')
));
$xml = $response;
echo $xml;
网站将加载echo
,但它只会启动登录屏幕。我需要这些凭据绕过登录屏幕(成功登录)才能获得cURL所需的部分信息。
答案 0 :(得分:10)
curl -F
提交POST请求而不是GET请求。因此,您需要相应地修改代码,例如
$client = new \GuzzleHttp\Client();
$response = $client->post('http://website.com/page/login/', [
'body' => [
'username' => $username,
'password' => $password,
'action' => 'login'
],
'cookies' => true
]
);
$xml = $response;
echo $xml;
请参阅http://guzzle.readthedocs.org/en/latest/quickstart.html#post-requests,http://curl.haxx.se/docs/manpage.html#-F
编辑:
只需向请求添加['cookies' => true]
即可使用与此GuzzleHttp\Client()
关联的身份验证Cookie。 http://guzzle.readthedocs.org/en/latest/clients.html#cookies
$response2 = $client->get('http://website.com/otherpage/', ['cookies' => true]);
答案 1 :(得分:6)
我无法获得@ JeremiahWinsley对更新版Guzzle工作的答案,所以我已经更新了他们的代码,以便在Guzzle 5.x中工作。
需要进行三项重大更改
form_params
代替body
来防止错误&#34;传入&#34;正文&#34;请求选项作为发送POST请求的数组已被弃用。&#34; CookieJar
对象->getBody()->getContents()
获取body of the request 以下是更新后的代码:
$client = new \GuzzleHttp\Client();
$cookieJar = new \GuzzleHttp\Cookie\CookieJar();
$response = $client->post('http://website.com/page/login/', [
'form_params' => [
'username' => $username,
'password' => $password,
'action' => 'login'
],
'cookies' => $cookieJar
]
);
$xml = $response->getBody()->getContents();
echo $xml;
要在将来的请求中继续使用Cookie,请将cookieJar
传递给请求:
$response2 = $client->get('http://website.com/otherpage/', ['cookies' => $cookieJar]);
答案 2 :(得分:3)
我在获取@JeremiahWinsley和@Samsquanch的答案以开发新版本的Guzzle时遇到困难。因此,我已经更新了代码,使其可以从Guzzle 6.x开始使用。
枪口6.x。文件:http://docs.guzzlephp.org/en/stable/index.html
这是更新的代码:
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
try {
$client = new Client();
$cookieJar = new CookieJar();
$response = $client->request('POST', 'http://website.com/page/login/', [
'form_params' => [
'username' => 'test@example.com',
'password' => '123456'
],
'cookies' => $cookieJar
]);
$response2 = $client->request('GET', 'http://website.com/otherpage/', [
'cookies' => $cookieJar
]);
if ($response2->getStatusCode() == 200) {
return $response2->getBody()->getContents();
} else {
return "Oops!";
}
} catch (\Exception $exception) {
return 'Caught exception: ', $exception->getMessage();
}