Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 322
Crusader Avatar asked Mar 22 '26 10:03

Crusader


1 Answers

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.

like image 163
brady.vitrano Avatar answered Mar 25 '26 00:03

brady.vitrano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!