如何通过Guzzle电话上的登录界面

问题描述 投票:6回答:3

我必须使用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所需的部分信息。

php curl laravel guzzle
3个回答
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-requestshttp://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]);

6
投票

我无法获得@ JeremiahWinsley对更新版Guzzle工作的答案,所以我已经更新了他们的代码,以便在Guzzle 5.x中工作。

需要进行三项重大改动

  • 使用form_params而不是body来防止错误“传入”正文“请求选项作为发送POST请求的数组已被弃用。”
  • 更改cookie以使用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]);

3
投票

我无法获得@ JeremiahWinsley和@ Samsquanch的答案来处理更新版本的Guzzle。所以我已经将代码更新为Guzzle 6.x.

Guzzle 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' => '[email protected]',
                '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();
    }
© www.soinside.com 2019 - 2024. All rights reserved.