Lyn*_*ynx 7 php curl laravel guzzle
我必须使用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;
Run Code Online (Sandbox Code Playgroud)
该网站将加载echo,但它只会拉起登录屏幕.我需要这些凭据绕过登录屏幕(成功登录)才能获得cURL所需的部分信息.
Jer*_*ley 12
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;
Run Code Online (Sandbox Code Playgroud)
见http://guzzle.readthedocs.org/en/latest/quickstart.html#post-requests,http://curl.haxx.se/docs/manpage.html#-F
编辑:
只需添加['cookies' => true]请求即可使用与此相关的身份验证cookie GuzzleHttp\Client().http://guzzle.readthedocs.org/en/latest/clients.html#cookies
$response2 = $client->get('http://website.com/otherpage/', ['cookies' => true]);
Run Code Online (Sandbox Code Playgroud)
我无法获得@ JeremiahWinsley对更新版Guzzle工作的答案,所以我已经更新了他们的代码,以便在Guzzle 5.x中工作.
需要进行三项重大改动
form_params而不是body防止错误"传入"正文"请求选项作为数组发送POST请求已被弃用."CookieJar对象->getBody()->getContents()得到请求体这是更新的代码:
$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;
Run Code Online (Sandbox Code Playgroud)
要在将来的请求中继续使用cookie,请传递cookieJar给请求:
$response2 = $client->get('http://website.com/otherpage/', ['cookies' => $cookieJar]);
Run Code Online (Sandbox Code Playgroud)
我在获取@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();
}
Run Code Online (Sandbox Code Playgroud)