CURL extension

Tomorrow i will explain more and make it under extensions an article about CURL extension, i go to sleep now :)

EDIT: now its perfect

GET EXAMPLE


$data = Yii::app()->CURL->run('http://www.google.com/ig/calculator?q='.$amount.$from.'=?'.$to);

print_r($data);

GET EXAMPLE


$data = Yii::app()->CURL->run('http://maps.google.com/maps/geo?q='.$place.'&output=json&key=ABQIAAAAR3YzPp1SL-w7k-Nhadw6oRRSU9EEwCG8ydw3m56rm2GtI8BohRSHN1qNuRyOrnYS_BNY1_2RnyuYTA');

POST EXAMPLE


$data = Yii::app()->CURL->run('http://www.atropa.com.hr/index.php?',FALSE,




	array(

	'option'=>'com_content','view'=>'article','id'=>58,'Itemid'=>2

	)

);


print_r($data);




<?php

/*


* Yii extension CURL


* This is a base class for procesing CURL REQUEST

*

* @author Igor Ivanović

* @version 0.1      

* @modifid date: 16-12-2010

* @filesource CURL.php

*

*/


class Curl extends CApplicationComponent{

        


        protected $url;

        protected $ch;

        

	public $options = array();

	public $info = array();

    	public $error_code = 0;

    	public $error_string = '';

        

        

        

	protected $validOptions = array(

        'timeout'=>array('type'=>'integer'),    

	'login'=>array('type'=>'array'),

	'proxy'=>array('type'=>'array'),

	'proxylogin'=>array('type'=>'array'),

	'setOptions'=>array('type'=>'array'),

	);

        

        

	/**

	 * Initialize the extension

	 * check to see if CURL is enabled and the format used is a valid one

	 */

	public function init(){

		if( !function_exists('curl_init') )

		throw new CException( Yii::t('Curl', 'You must have CURL enabled in order to use this extension.') );

                

	}


         /**

        * Setter

        * @set the option

        */

        protected function setOption($key,$value){

        curl_setopt($this->ch,$key, $value);

        }

	

        

	/**

	* Formats Url if http:// dont exist

	* set http://

	*/

        public function setUrl($url){

	if(!preg_match('!^\w+://! i', $url)) {

	$url = 'http://'.$url;

	}

        $this->url = $url;

        }





	 /*

	* Set Url Cookie

	*/

        public function setCookies($values){

        if (!is_array($values))

        throw new CException(Yii::t('Curl', 'options must be an array'));

        else

        $params = $this->cleanPost($values);

        $this->setOption(CURLOPT_COOKIE, $params);

        }


	/*

	@LOGIN REQUEST

	sets login option

	If is not setted , return false

	*/

        public function setHttpLogin($username = '', $password = '') {

        $this->setOption(CURLOPT_USERPWD, $username.':'.$password);

        }

        /*

	@PROXY SETINGS

	sets proxy settings withouth username


	*/


        public function setProxy($url,$port = 80){

	$this->setOption(CURLOPT_HTTPPROXYTUNNEL, TRUE);

        $this->setOption(CURLOPT_PROXY, $url.':'.$port);

	}


	/*

	@PROXY LOGIN SETINGS

	sets proxy login settings calls onley if is proxy setted


	*/

	public function setProxyLogin($username = '', $password = '') {

        $this->setOption(CURLOPT_PROXYUSERPWD, $username.':'.$password);

        }

	/*

	@VALID OPTION CHECKER

	*/

	protected static function checkOptions($value, $validOptions)

        {

        if (!empty($validOptions)) {

            foreach ($value as $key=>$val) {


                if (!array_key_exists($key, $validOptions)) {

                    throw new CException(Yii::t('Curl', '{k} is not a valid option', array('{k}'=>$key)));

                }

                $type = gettype($val);

                if ((!is_array($validOptions[$key]['type']) && ($type != $validOptions[$key]['type'])) || (is_array($validOptions[$key]['type']) && !in_array($type, $validOptions[$key]['type']))) {

                        throw new CException(Yii::t('Curl', '{k} must be of type {t}',

                        array('{k}'=>$key,'{t}'=>$validOptions[$key]['type'])));

                }


                if (($type == 'array') && array_key_exists('elements', $validOptions[$key])) {

                        self::checkOptions($val, $validOptions[$key]['elements']);

                    }

                }

            }

        }

        

        protected function defaults(){

            !isset($this->options['timeout'])  ?  $this->setOption(CURLOPT_TIMEOUT,30) : $this->setOption(CURLOPT_TIMEOUT,$this->options['timeout']);

            isset($this->options['setOptions'][CURLOPT_HEADER]) ? $this->setOption(CURLOPT_HEADER,$this->options['setOptions'][CURLOPT_HEADER]) : $this->setOption(CURLOPT_HEADER,FALSE);

            isset($this->options['setOptions'][CURLOPT_RETURNTRANSFER]) ? $this->setOption(CURLOPT_RETURNTRANSFER,$this->options['setOptions'][CURLOPT_RETURNTRANSFER]) : $this->setOption(CURLOPT_RETURNTRANSFER,TRUE);

	    isset($this->options['setOptions'][CURLOPT_FOLLOWLOCATION]) ? $this->setOption(CURLOPT_FOLLOWLOCATIO,$this->options['setOptions'][CURLOPT_FOLLOWLOCATION]) : $this->setOption(CURLOPT_FOLLOWLOCATION,TRUE);

            isset($this->options['setOptions'][CURLOPT_FAILONERROR]) ? $this->setOption(CURLOPT_FAILONERROR,$this->options['setOptions'][CURLOPT_FAILONERROR]) : $this->setOption(CURLOPT_FAILONERROR,TRUE);  

        }

	

	/*

	@MAIN FUNCTION FOR PROCESSING CURL

	*/

	public function run($url,$GET = TRUE,$POSTSTRING = array()){

                $this->setUrl($url);

                if( !$this->url )

		throw new CException( Yii::t('Curl', 'You must set Url.') );

                $this->ch = curl_init();

		self::checkOptions($this->options,$this->validOptions);

                

                if($GET == TRUE){

                $this->setOption(CURLOPT_URL,$this->url);

                $this->defaults();

                }else{

                $this->setOption(CURLOPT_URL,$this->url);

                $this->defaults();

                $this->setOption(CURLOPT_POST, TRUE);

                $this->setOption(CURLOPT_POSTFIELDS, $this->cleanPost($POSTSTRING));        

                }

                

                if(isset($this->options['setOptions']))

		foreach($this->options['setOptions'] as $k=>$v)

		$this->setOption($k,$v);

                

                isset($this->options['login']) ?  $this->setHttpLogin($this->options['login']['username'],$this->options['login']['password']) :  null;

                isset($this->options['proxy']) ? $this->setProxy($this->options['proxy']['url'],$this->options['proxy']['port']) : null;

                

                if(isset($this->options['proxylogin'])){

		if(!isset($this->options['proxy']))

		throw new CException( Yii::t('Curl', 'If you use "proxylogin", you must define "proxy" with arrays.') );

		else

		$this->setProxyLogin($this->options['login']['username'],$this->options['login']['password']);

		}

                

                $return = curl_exec($this->ch);


		// Request failed

		if($return === FALSE)

		{

		$this->error_code = curl_errno($this->ch);

		$this->error_string = curl_error($this->ch);

		curl_close($this->ch);

		echo "Error code: ".$this->error_code."<br />";

		echo "Error string: ".$this->error_string;

		// Request successful

		} else {

		$this->info = curl_getinfo($this->ch);

	        curl_close($this->ch);

		return $return;

		}

                

                

                

                

      }

                

                


        

        

        

        

      


	/**

	 * Arrays are walked through using the key as a the name.  Arrays

	 * of Arrays are emitted as repeated fields consistent with such things

	 * as checkboxes.

	 * @desc Return data as a post string.

	 * @param mixed by reference data to be written.

	 * @param string [optional] name of the datum.

	 */


	protected function &cleanPost(&$string, $name = NULL)

	  {

		$thePostString = '' ;

		$thePrefix = $name ;


		if (is_array($string))

		{

		  foreach ($string as $k => $v)

		  {

			if ($thePrefix === NULL)

                    {

			  $thePostString .= '&' . self::cleanPost($v, $k) ;

                    }

		else

			{

			  $thePostString .= '&' . self::cleanPost($v, $thePrefix . '[' . $k . ']') ;

			}

                }

                

		}

		else

		{

		  $thePostString .= '&' . urlencode((string)$thePrefix) . '=' . urlencode($string) ;

		}


		$r =& substr($thePostString, 1) ;


		return $r ;

	  }


}//end of method




Are you psychic? Just what I need. Thanks. Well done! :)

No im psycho :) , i will explain more when i wake up and make source downloadable in extensions

Now ITS perfect class :) i`ve have some issues so i modified and fix all issues

I`ve added under Curl extension

enjoy :)

Goooood!

Thank you!

You can use as google weather to :)




$data = Yii::app()->CURL->run('http://www.google.com/ig/api?weather='.$place.'&hl=en');

 

$xml = new SimplexmlElement($data);

        foreach($xml->weather as $item) {

 

                foreach($item->current_conditions as $new) {

 

                        //For temperature in fahrenheit replace temp_c by temp_f

                        $current_temperature=$new->temp_c['data'];

                        $current_humidity=$new->humidity['data'];

                }

 

                $current_condition=$item->forecast_conditions[0]->condition['data'];           

                $next_temperature=$item->forecast_conditions[1]->high['data'];

 

                //to convert Fahrenheit into Celcius

                $next_temperature=round(($next_temperature-32)*(5/9));

 

                $next_condition=$item->forecast_conditions[1]->condition['data'];

        }  

 

echo " Current temperature :".$current_temperature."<br />"; 

echo "Current condition : ".$current_condition."<br />";

echo $current_humidity; 

echo "Tomorrows temperature :".$next_temperature."<br />"; 

echo "Tomorrows condition : ".$next_condition."<br />";




Currently developing, Twitter api extension for Curl extension

@Igor

there is no need to post here when you already posted in the extensions forum…

Maybe you could merge this into it, Mdomba? :)

<edit>

Thanks!

</edit>

Indeed… moved and merged…

Maybe a small tip to add to your how-to explanation.

in config/main.php

you have to add in the extension to the componont array.

// application components

‘components’=>array(

    // CURL extension include /protected/extensions/curl


    // http://www.yiiframework.com/extension/curl/


    // &#036;data = Yii::app()-&gt;CURL-&gt;run('URL of webservice'); return data


    'CURL' =&gt;array(


        'class' =&gt; 'application.extensions.curl.Curl',


                 //you can setup timeout,http_login,proxy,proxylogin,cookie, and setOPTIONS


    ),

),

Hi thanks for that extension. However our team was faced with a situation where we needed the"PUT" support also in the extensiion. So we modified your extension a bit and added "PUT" also to it. The details can be found at the below link.

// yii.askfairy.com/2011/12/added-put-support-to-yii-curl-extension.html

Please let me know if you think if there is a bug there which we just might have missed out.

It would be nice if the url parameters would be passed in as an array, e.g. $params, and appended to the string before doing the request.

[size="2"]just tried this extension and got

[/size]

[size="2"]PHP error[/size]

[size=&quot;2&quot;] 		Only variables should be assigned by reference	[/size]





   		[size=&quot;2&quot;]...&#092;protected&#092;extensions&#092;curl&#092;Curl.php(281)[/size]

[size="2"]




		$r =& substr($thePostString, 1) ;


		return $r ;



This is strict php mode, why would one use & substr ??? to save a bit of memory? I changed the code to

[/size][size="2"]




		$r = substr($thePostString, 1) ;

  

		return $r ;



works OK.

[/size]

How do I add cookies to a request? for example can i do something like this:<br />


            Yii::app()->CURL->setCookies(array(

                $xmlresponse->login['cookieprefix'].'_session' => $xmlresponse->login['sessionid']

                    ));

            

            $data = Yii::app()->CURL->run(url,FALSE,

                array( 

                    

                    ));



this gives me a php 500 error

not valid descriptor for curl_setopt()




protected function setOption($key,$value){

        curl_setopt($this->ch,$key, $value);

        }

Nice Job!

I just started a new project that I need to call an external API and it will be very usefull.

But, there is a way to inform the credentials on the fly? I mean, set in on controller?

Because my credetials will depend on the logged user.

Thanks a lot

Hi guys,

I got it usign the belo code




Yii::app()->CURL->options['login'] = array('username' => $username,'password' => $pass);

$return = Yii::app()->CURL->run($url);