8 cosas asombrosas que puedes hacer con PHP y cURL

cURL y su extensión de PHP libcURL, son herramientas muy útiles y potentes para tareas, como pueden ser, la simulación de un navegador web, enviar formularios o acceder a un servicio web. En este artículo, os voy a mostrar ciertas cosas sorprendentes que se pueden realizar utilizando PHP y cURL.

Comprobar si un sitio web específico está disponible

¿Quieres saber si un sitio web específico está disponible? cURL está aquí para ayudar. Este script puede utilizarse en un cronjob para monitorizar tus sitios web. No olvides actualizar el script con la URL que desees chequear en la línea 3. Una vez hecho esto, pégalo, o bien en tu proyecto o bien en el archivo que va a ejecutar el cron, y te permitirá conocer la disponibilidad de tus sitios webs.

if (isDomainAvailible('http://www.programacion.net'))
       {
               echo "Up and running!";
       }
       else
       {
               echo "Woops, nothing found there.";
       }

       //returns true, if domain is availible, false if not
       function isDomainAvailible($domain)
       {
               //check, if a valid url is provided
               if(!filter_var($domain, FILTER_VALIDATE_URL))
               {
                       return false;
               }

               //initialize curl
               $curlInit = curl_init($domain);
               curl_setopt($curlInit,CURLOPT_CONNECTTIMEOUT,10);
               curl_setopt($curlInit,CURLOPT_HEADER,true);
               curl_setopt($curlInit,CURLOPT_NOBODY,true);
               curl_setopt($curlInit,CURLOPT_RETURNTRANSFER,true);

               //get answer
               $response = curl_exec($curlInit);

               curl_close($curlInit);

               if ($response) return true;

               return false;
       }

Sustituto de file_get_contents()

La función file_get_contents() es muy útil pero, desafortunadamente, está desactivada por defecto en muchos hostings. Utilizando cURL puedes escribir una función de reemplazo que funciona exáctamente igual que file_get_contents()

function file_get_contents_curl($url) {
	$ch = curl_init();
	
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
	curl_setopt($ch, CURLOPT_URL, $url);
	
	$data = curl_exec($ch);
	curl_close($ch);
	
	return $data;
}

Obtener el último estado de Twitter

Mediante el uso de PHP y cURL, es bastante sencillo obtener el estado de un usuario específico de Twitter. Una vez que lo tienes, ¿qué tal si lo muestras en el pie de página como hacen multitud de webs?

function get_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    curl_close($c);
    preg_match('/(.*)</text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '\0', $status);
    return($status);
}

La función es super sencilla de utilizar:

echo get_status('noprog');

Comprobar la amistad entre dos usuarios de Twitter

Si quieres saber si un usuario específico te sigue, puedes utilizar la API de Twitter. Este snippet te devolverá un true si dos usuarios, especificados en la línea 18 y 19, son amigos. De lo contrario devolverá un false.

function make_request($url) {
	$ch = curl_init();
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	$result = curl_exec($ch);
	curl_close($ch);
	return $result;
}

/* gets the match */
function get_match($regex,$content) {
	preg_match($regex,$content,$matches);
	return $matches[1];
}

/* persons to test */
$person1 = 'noprog';
$person2 = 'rotundolopez';

/* send request to twitter */
$url = 'https://api.twitter.com/1/friendships/exist';
$format = 'xml';

/* check */
$persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2);
$result = get_match('/(.*)</friends>/isU',$persons12);
echo $result; // returns "true" or "false"

Descargar imágenes de una web externa utilizando cURL

Aquí tienes un conjunto de funciones que te pueden ser muy útiles: Proporciona a este script la URL de una página web, y guardará todas las imágenes de esa página en tu servidor.

function getImages($html) {
    $matches = array();
    $regex = '~http://somedomain.com/images/(.*?).jpg~i';
    preg_match_all($regex, $html, $matches);
    foreach ($matches[1] as $img) {
        saveImg($img);
    }
}

function saveImg($name) {
    $url = 'http://somedomain.com/images/'.$name.'.jpg';
    $data = get_data($url);
    file_put_contents('photos/'.$name.'.jpg', $data);
}

$i = 1;
$l = 101;

while ($i < $l) {
    $html = get_data('http://somedomain.com/id/'.$i.'/');
    getImages($html);
    $i += 1;
}

Convertir divisas utilizando cURL y Google

Convertir divisas no es una tarea complicada, pero como sabéis las monedas fluctúan todo el tiempo, es por eso que, definitivamente, necesitamos un servicio como Google para obtener sus valores más recientes. La función currency() tiene 3 parámetros: from (divisa origen), to (divisa destino) y amount (el valor).

function currency($from_Currency,$to_Currency,$amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);
    $url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    curl_close($ch);
    $data = explode('"', $rawdata);
    $data = explode(' ', $data['3']);
    $var = $data['0'];
    return round($var,2);
}

Obtener el tamaño de ficheros externos utilizando cURL

¿Quieres ser capaz de calcular el tamaño de un fichero específico? La siguiente función te puede ayudar. Tiene 3 parámetros: la url del fichero, y, en el caso de que el archivo esté protegido con contraseña, un nombre de usuario y una contraseña.

function remote_filesize($url, $user = "", $pw = ""){
    ob_start();
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
 
    if(!empty($user) && !empty($pw))
    {
        $headers = array('Authorization: Basic ' .  base64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
 
    $ok = curl_exec($ch);
    curl_close($ch);
    $head = ob_get_contents();
    ob_end_clean();
 
    $regex = '/Content-Length:s([0-9].+?)s/';
    $count = preg_match($regex, $head, $matches);
 
    return isset($matches[1]) ? $matches[1] : "unknown";
}

Subida FTP con cURL

PHP cuenta con una librería para tratar con los FTP, pero también se puede utilizar cURL para subir archivos a un servidor por FTP. Aquí tienes un ejemplo sobre cómo hacerlo:

// open a file pointer
$file = fopen("/path/to/file", "r");

// the url contains most of the info needed
$url = "ftp://username:[email protected]:21/path/to/new/file";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// upload related options
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file"));

// set for ASCII mode (e.g. text files)
curl_setopt($ch, CURLOPT_FTPASCII, 1);

$output = curl_exec($ch);
curl_close($ch);

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP