Working with CURL in PHP

To make life very simple, I have written the following class “myCURL.class.php”.

<?php

class myCURL {

var $curlSession;

function setCURLOpt($opt, $value){ global $curlSession; curl_setopt($curlSession, $opt, $value);}

function req($method, $url, $vars, $flg=flase) { global $curlSession; $curlSession = curl_init(); $this->setStdOpts(); curl_setopt($curlSession, CURLOPT_URL, $url); if ($method == 'POST') {  curl_setopt($curlSession, CURLOPT_POST, 1);  curl_setopt($curlSession, CURLOPT_POSTFIELDS, $vars); } $data = curl_exec($curlSession); if ($data) {  return $data; } else {  $err = curl_error($curlSession);  echo $err;  return $err; } curl_close($curlSession);}

function setStdOpts(){ global $curlSession; curl_setopt($curlSession, CURLOPT_HTTPHEADER, array( 'Expect:' ) ); curl_setopt($curlSession, CURLOPT_HEADER, 0); curl_setopt($curlSession, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); curl_setopt($curlSession, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlSession, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 2); curl_setopt($curlSession, CURLOPT_COOKIEJAR, '/tmp/cookie.txt'); curl_setopt($curlSession, CURLOPT_COOKIEFILE, '/tmp/cookie.txt');}

function get($url) {   return $this->req('GET', $url, 'NULL');}

function post($url, $vars, $flg=false) { return $this->req('POST', $url, $vars, $flg);}}?>

To get started, just copy the above code and paste it in “myCURL.class.php”. Use the following commands to GET contents of any URL through http or https.

<?phprequire_once("myCURL.class.php");$curl = new myCURL();$contents = $curl->get("http://my-experiments-with-it.blogspot.com/");echo $contents;?>

And you are done.


About this entry