Monday, 8 April 2013

Code is for posting data to multiple sites using multi curl in php

 This code is for posting data to multiple sites using multi curl in php. Useful for looping and posting to multiple site.
<?php
class curl_post{
    function __construct(){
        $this->curl_urls = array();
        $this->ch = array();
        $this->num_url = 0;
        $this->output = array();
        $this->multi_curl = curl_multi_init();
        $this->basic_options = array(
                 //CURLOPT_HEADER => true,
                 CURLOPT_RETURNTRANSFER => 1,
                 //CURLOPT_VERBOSE => 1,
                 CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
                 CURLOPT_SSL_VERIFYPEER => false
                );
    }
   
    function add_url($options){
        ++$this->num_url;
        $this->ch[$this->num_url] = curl_init();
        foreach($this->basic_options as $k => $v){
            $options[$k] = $v;
        }
        curl_setopt_array($this->ch[$this->num_url], $options);
        curl_multi_add_handle($this->multi_curl,$this->ch[$this->num_url]);
    }
   
    function exe_curl(){
        $active = null;
        do {
            curl_multi_exec($this->multi_curl,$active);
        } while($active > 0);
        foreach($this->ch as $ch){
            $this->output[] = curl_multi_getcontent($ch);
        }
    }
   
    function __destruct(){
        foreach($this->ch as $ch){
            curl_multi_remove_handle($this->multi_curl, $ch);
            curl_close($ch);
        }
        curl_multi_close($this->multi_curl);
    }
   
}


Example
/*$curl_obj = new curl_post();

$data = "var1=value1&postvar2=value2&postvar3=value3";

$options = array(CURLOPT_URL => 'url-location1
', CURLOPT_POSTFIELDS => $data);

$curl_obj->add_url($options);

$options = array(CURLOPT_URL => '
url-location2', CURLOPT_POSTFIELDS => "testing=value&test2=value2");

$curl_obj->add_url($options);

$options = array(CURLOPT_URL => '');

$curl_obj->add_url($options);
$curl_obj->exe_curl();

print_r($curl_obj->output);*/

No comments:

Post a Comment