PHP: a simple curl library

function do_curl_command($url,$headers,$post_data=false,$auth="")
{
    if(strpos($url,"http")===false)
    {
       write_log("Invalid curl url $url");
       exit;
    }
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);     
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_HEADER, 1);
    if($auth!="")
    {
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD, $auth); //Your credentials goes here
    }

    $http_method="GET";   
    write_log($post_data);
    if(is_array($post_data) ||  $post_data!="" )
    {
        if(is_array($post_data))
            $post_data= http_build_query($post_data);
        else{
            if(json_decode($post_data))
                $headers[]="Content-Type: application/json";
        }

        curl_setopt($ch, CURLOPT_POST, 1); 
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
        $http_method="POST";
    }

    curl_setopt($ch, CURLOPT_VERBOSE, false);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result=curl_exec($ch);
    if( $result === false)
    {
        echo 'Curl error: ' . curl_error($ch);
        exit;
    }
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $headers = substr($result, 0, $header_size);
    $body = substr($result, $header_size);
    curl_close($ch);
    return array("headers"=>$headers,"body"=>$body);
}

function write_log($data)
{
   $ip=$_SERVER["REMOTE_ADDR"];
   $data=date("\r\nY-m-d H:i:s")."[$ip]".$data;
    //echo $data;
  file_put_contents("log.txt",$data,FILE_APPEND);
}

Leave a Reply

Your email address will not be published. Required fields are marked *