Sunday 10 June 2012

working with Curl PHP

  <?php
 //login start
        set_time_limit(0);

        //$php_userid = "admin";//$_POST['login'];
        //$php_password = "dD82slk7!";//$_POST['passwd'];


        $cookie_file_path = "cookie.txt"; // Please set your Cookie File path


        $fp = fopen($cookie_file_path,'wb');
        fclose($fp);
        $agent = "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)";
        $reffer = "http://127.0.0.1/example/user/";
        $LOGINURL = "http://127.0.0.1/example/user/";

        $POSTFIELDS = 'name=admin&pass=htpass123&op=Log in&form_id=user_login';       
    

/* Initialize the cURL session*/
     $ch = curl_init();


/* Set the URL of the page or file to download.*/
        curl_setopt($ch, CURLOPT_URL,$LOGINURL);
        curl_setopt($ch, CURLOPT_USERAGENT, $agent);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$POSTFIELDS);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_REFERER, $reffer);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);


/**
* Execute the cURL session
*/
//$contents = curl_exec ($ch) or die(curl_error());


        $result = curl_exec ($ch);

      // echo curl_exec ($ch);
    $response = curl_getinfo($ch);
    //print_r($response);


/**
* Close cURL session
*/

    curl_close ($ch); 
    print_r($result);
            //login ends

Download file or web page using PHP cURL and save it to file

The below PHP code is a slight variation of the above code. It not only downloads the contents of the specified URL but also saves it to a file.

/**
* Initialize the cURL session
*/
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,
'http://news.google.com/news?hl=en&topic=t&output=rss');
/**
* Create a new file
*/
$fp = fopen('rss.xml', 'w');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);
/**
* Execute the cURL session
*/
curl_exec ($ch);
/**
* Close cURL session and file
*/
curl_close ($ch);
fclose($fp);
?>

No comments:

Post a Comment