Compago knowledge

  • Increase font size
  • Default font size
  • Decrease font size
Home Manuali Programmazione Usare curl per inviare dati tramite il metodo POST

Usare curl per inviare dati tramite il metodo POST

E-mail Stampa PDF

Di seguito riporto un piccolo script in PHP che serve a inviare dati con il metodo POST.

  class curl {
    var $ch ;
    function curl(){
        $this->ch = curl_init( );
        // you might want the headers for http codes
        curl_setopt( $this->ch, CURLOPT_HEADER, true );
        // set if the web server claims a typical browser as a client
        curl_setopt( $this->ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        // set if you need to follow redirect action
        curl_setopt( $this->ch, CURLOPT_FOLLOWLOCATION, true );
        // set if you need to store the output in a variable
        curl_setopt( $this->ch, CURLOPT_RETURNTRANSFER, true );
        // set if you need cookies
        curl_setopt( $this->ch, CURLOPT_COOKIEJAR, 'cookie.txt'); //output cookies
        curl_setopt( $this->ch, CURLOPT_COOKIEFILE, 'cookie.txt');//input cookies   
    function makeRequest($method, $url, $vars){
        // if the $vars are in an array then turn them into a usable string
        if( is_array( $vars ) ):
            $vars = implode( '&amp;', $vars );
        // setup the url to post / get from / to
        curl_setopt( $this->ch, CURLOPT_URL, $url );
        // the actual post bit
        if ( strtolower( $method ) == 'post' ) :
            curl_setopt( $this->ch, CURLOPT_POST, true );
            curl_setopt( $this->ch, CURLOPT_POSTFIELDS, $vars );
        // return data
        return curl_exec( $this->ch );
  $curl = new curl( );
  // test with single data to send
  echo $curl->makeRequest('post','','data=mydatahere' );
  // test with a data array to send
  echo $curl->makeRequest('post','',array('data1=test1','data1=test2'); );

La richiesta con il metodo post viene inviata tramite il comando "curl", occorre quindi che nel webserver siano installate le librerie necessarie.

some others usefull options for HTTPS requests are:

curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);

so you can avoid the SSL cert check.

Ultimo aggiornamento ( Martedì 10 Maggio 2011 12:50 )