eristoddle
1/31/2014 - 7:12 PM

PHP curl with cookies and no text files needed

PHP curl with cookies and no text files needed

<?php
function fetch($url, $cookies = null, $returnCookie = false) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if($cookies){
        curl_setopt($ch, CURLOPT_COOKIE, implode(';',$cookies));
    }
    curl_setopt($ch, CURLOPT_HEADER, 1);
    $result = curl_exec($ch);
    list($header, $body) = explode("\r\n\r\n", $result, 2);
    $end = strpos($header, 'Content-Type');
    $start = strpos($header, 'Set-Cookie');
    $parts = explode('Set-Cookie:', substr($header, $start, $end - $start));
    $cookies = array();
    foreach ($parts as $co) {
        $cd = explode(';', $co);
        if (!empty($cd[0]))
            $cookies[] = $cd[0];
    }
    curl_close($ch);
    if ($returnCookie){
        return $cookies;
    }
    return json_decode($body);
}