简体   繁体   中英

Zend_Http_Client cURL authorization example

I need to create authorization script. Cookies must be saved and used later to access the page without authorization. Can anyone give me work example?

First, you have to do an initial request to get the cookies from the server. In the response, you will save the cookies the server sends in the response header Set-Cookie . Where you store them is up to you. I just added them to a session.

    $uri    = 'http://example.com';
    $client = new Zend_Http_Client();
    $client->setUri($uri);
    $client->setAdapter('Zend_Http_Client_Adapter_Curl');
    $adapter = $client->getAdapter();
    $adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, false);

    /** First Request to get required cookies **/
    $response = $client->request();

    /** Get response cookie strings and store them (session, db, file, etc) **/
    $cookies  = (array) $response->getHeader('Set-cookie');
    $session  = new Zend_Session_Namespace();
    $session->storedCookies = $cookies;

Now that you have the cookies stored, on your next request you can add them to the request.

    /** Start new Zend_Http_Client instance **/
    $uri      = 'http://example.com';
    $client   = new Zend_Http_Client();
    $client->setUri($uri);
    $client->setAdapter('Zend_Http_Client_Adapter_Curl');
    $adapter  = $client->getAdapter();
    /** This setCurlOption is optional **/
    $adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, false);


    $session = new Zend_Session_Namespace();
    $cookies = $session->storedCookies;
    /** Add Stored Cookie strings to Zend_Http_Client instance **/ 
    foreach ($cookies as $cookieStr) {
        $client->setCookie(Zend_Http_Cookie::fromString($cookieStr, $uri));
    }

    /** Perform request using stored cookies **/
    $response = $client->request();

If you have questions or need me to elaborate on anything, just let me know.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM