PHP 5.4.36 Released

curl_getinfo

(PHP 4 >= 4.0.4, PHP 5)

curl_getinfoObtiene información relativa a una transferencia específica

Descripción

mixed curl_getinfo ( resource $ch [, int $opt = 0 ] )

Obtiene información sobre la última transferencia.

Parámetros

ch

El recurso cURL devuelto por curl_init().

opt

Podría ser una de las siguientes constantes:

  • CURLINFO_EFFECTIVE_URL - Último URL efectivo
  • CURLINFO_HTTP_CODE - Último código HTTP recibido
  • CURLINFO_FILETIME - Hora del documento remoto obtenido, si devuelve -1, la hora del documento es desconocida
  • CURLINFO_TOTAL_TIME - Duración total en segundos de última transaferencia
  • CURLINFO_NAMELOOKUP_TIME - Tiempo en segundos en resolver el nombre
  • CURLINFO_CONNECT_TIME - Tiempo en segundos que tomó el establecimiento de la conexión
  • CURLINFO_PRETRANSFER_TIME - Tiempo en segundos desde el inicio hasta justo antes de que comience la transferencia del fichero
  • CURLINFO_STARTTRANSFER_TIME - Tiempo en sengudos hasta que el primer byte está a punto de transferirse
  • CURLINFO_REDIRECT_COUNT - Número de redireccionamientos
  • CURLINFO_REDIRECT_TIME - Tiempo en segundos de todos los pasos de redireción antes de que la última transación haya empezado
  • CURLINFO_SIZE_UPLOAD - Número total de bytes subidos
  • CURLINFO_SIZE_DOWNLOAD - Número total de bytes descargados
  • CURLINFO_SPEED_DOWNLOAD - Velocidad media de descarga
  • CURLINFO_SPEED_UPLOAD - Velocidad media de subida
  • CURLINFO_HEADER_SIZE - Tamaño total de los encabezados recibidos
  • CURLINFO_HEADER_OUT - El string de la petición enviada. Para que funcione, se ha de añadir la opción CURLINFO_HEADER_OUT al gestor, llamando a curl_setopt()
  • CURLINFO_REQUEST_SIZE - Tamaño total de las peticiones realizadas, actualmente solo para peticiones HTTP
  • CURLINFO_SSL_VERIFYRESULT - Resultado de la verificación del certificado SSL solicitado por la opción CURLOPT_SSL_VERIFYPEER
  • CURLINFO_CONTENT_LENGTH_DOWNLOAD - Logitud del contenido de la descarga, leída desde el campo Content-Length:
  • CURLINFO_CONTENT_LENGTH_UPLOAD - Tamaño especificado de subida
  • CURLINFO_CONTENT_TYPE - Content-Type: del documento solicitado, NULL indica que el servidor no envío un encabezado Content-Type: válido.

Valores devueltos

Si se indica el parámetro, opt, devolverá su valor. De lo contrario, devolverá un array asociativo con los siguientes elementos (que se corresponden a opt), o FALSE en caso de error:

  • "url"
  • "content_type"
  • "http_code"
  • "header_size"
  • "request_size"
  • "filetime"
  • "ssl_verify_result"
  • "redirect_count"
  • "total_time"
  • "namelookup_time"
  • "connect_time"
  • "pretransfer_time"
  • "size_upload"
  • "size_download"
  • "speed_download"
  • "speed_upload"
  • "download_content_length"
  • "upload_content_length"
  • "starttransfer_time"
  • "redirect_time"
  • "certinfo"
  • "request_header" (Solamente está definido si CURLINFO_HEADER_OUT está establecido por una llamada previa a curl_setopt())

Historial de cambios

Versión Descripción
5.1.3 Se introdujo CURLINFO_HEADER_OUT.

Ejemplos

Ejemplo #1 Ejemplo de curl_getinfo()

<?php
// Crear un gestor curl
$ch curl_init('http://www.yahoo.com/');

// Ejecutar
curl_exec($ch);

// Comprobar si ocurrió un error
if(!curl_errno($ch))
{
 
$info curl_getinfo($ch);

 echo 
'Se tardó ' $info['total_time'] . ' segundos en enviar la petición a ' $info['url'];
}

// Cerrar manipulador
curl_close($ch);
?>

Notas

Nota:

La información obtenida por esta función se mantiene si se reutiliza el gestor. Esto significa que, a no ser que una estadística sea sobrescrita internamente por esta función, se devolverá la información previa.

add a note add a note

User Contributed Notes 10 notes

up
15
ssttoo at hotmail dot com
10 years ago
Here are the response codes ready for pasting in an ini-style file. Can be used to provide more descriptive message, corresponding to 'http_code' index of the arrray returned by curl_getinfo().
These are taken from the W3 consortium HTTP/1.1: Status Code Definitions, found at
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

[Informational 1xx]
100="Continue"
101="Switching Protocols"

[Successful 2xx]
200="OK"
201="Created"
202="Accepted"
203="Non-Authoritative Information"
204="No Content"
205="Reset Content"
206="Partial Content"

[Redirection 3xx]
300="Multiple Choices"
301="Moved Permanently"
302="Found"
303="See Other"
304="Not Modified"
305="Use Proxy"
306="(Unused)"
307="Temporary Redirect"

[Client Error 4xx]
400="Bad Request"
401="Unauthorized"
402="Payment Required"
403="Forbidden"
404="Not Found"
405="Method Not Allowed"
406="Not Acceptable"
407="Proxy Authentication Required"
408="Request Timeout"
409="Conflict"
410="Gone"
411="Length Required"
412="Precondition Failed"
413="Request Entity Too Large"
414="Request-URI Too Long"
415="Unsupported Media Type"
416="Requested Range Not Satisfiable"
417="Expectation Failed"

[Server Error 5xx]
500="Internal Server Error"
501="Not Implemented"
502="Bad Gateway"
503="Service Unavailable"
504="Gateway Timeout"
505="HTTP Version Not Supported"

And an example usage:
<?php
$ch
= curl_init(); // create cURL handle (ch)
if (!$ch) {
    die(
"Couldn't initialize a cURL handle");
}
// set some cURL options
$ret = curl_setopt($ch, CURLOPT_URL,            "http://mail.yahoo.com");
$ret = curl_setopt($ch, CURLOPT_HEADER,         1);
$ret = curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$ret = curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
$ret = curl_setopt($ch, CURLOPT_TIMEOUT,        30);

// execute
$ret = curl_exec($ch);

if (empty(
$ret)) {
   
// some kind of an error happened
   
die(curl_error($ch));
   
curl_close($ch); // close cURL handler
} else {
   
$info = curl_getinfo($ch);
   
curl_close($ch); // close cURL handler

   
if (empty($info['http_code'])) {
            die(
"No HTTP code was returned");
    } else {
       
// load the HTTP codes
       
$http_codes = parse_ini_file("path/to/the/ini/file/I/pasted/above");
       
       
// echo results
       
echo "The server responded: <br />";
        echo
$info['http_code'] . " " . $http_codes[$info['http_code']];
    }

}
?>
up
4
bg at enativ dot com
9 months ago
curl_getinfo($ch) will also return 'redirect_url' if there is one (even if CURLOPT_FOLLOWLOCATION set to false).
I don't know why it's not in the doc..
up
4
nemetral
6 years ago
Just a quick note: if you want to use curl_getinfo() with option CURLINFO_HEADER_OUT in order to debug your cURL request, you must add curl_setopt($handle, CURLINFO_HEADER_OUT, true); first while specifying the options.
up
3
Mark Evers
6 years ago
There is a constant missing from that list.  CURLINFO_REDIRECT_COUNT will give you the number of redirects it went through if CURLOPT_FOLLOWLOCATION was set.
up
0
qrworld.net
1 month ago
Here you have a function that I use to get the content of a URL using cURL. This uses curl_getinfo to know if it is a regular URL or maybe a redirection.

I hope it would be useful for you:

function getUrlContent($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode>=200 && $httpcode<300) ? $data : false;
}

The source comes from this website:

http://softontherocks.blogspot.com/2014/11/descargar-el-contenido-de-una-url.html
up
0
vince
4 years ago
CURLINFO_HTTP_CODE does not return a string, as the docs say, but rather an integer.

<?php
    $c
= curl_init('http://www.example.com/');
    if(
curl_getinfo($c, CURLINFO_HTTP_CODE) === '200') echo "CURLINFO_HTTP_CODE returns a string.";
    if(
curl_getinfo($c, CURLINFO_HTTP_CODE) === 200) echo "CURLINFO_HTTP_CODE returns an integer.";
   
curl_close($c);
?>

returns

"CURLINFO_HTTP_CODE returns an integer."
up
0
Anonymous
4 years ago
The main doc neglects to mention that when the CURLINFO_HEADER_OUT option is set the array returned by this function will included a new property, request_header, that is a string of the headers sent in the request.
up
-2
nikita dot bulatenko at gmail dot com
1 year ago
CURLINFO_SSL_VERIFYRESULT error codes:
0: ok the operation was successful.
2 : unable to get issuer certificate
3: unable to get certificate CRL
4: unable to decrypt certificate's signature
5: unable to decrypt CRL's signature
6: unable to decode issuer public key
7: certificate signature failure
8: CRL signature failure
9: certificate is not yet valid
10: certificate has expired
11: CRL is not yet valid
12:CRL has expired
13: format error in certificate's notBefore field
14: format error in certificate's notAfter field
15: format error in CRL's lastUpdate field
16: format error in CRL's nextUpdate field
17: out of memory
18: self signed certificate
19: self signed certificate in certificate chain
20: unable to get local issuer certificate
21:unable to verify the first certificate
22: certificate chain too long
23: certificate revoked
24: invalid CA certificate
25: path length constraint exceeded
26: unsupported certificate purpose
27: certificate not trusted
28: certificate rejected
29: subject issuer mismatch
30: authority and subject key identifier mismatch
31: authority and issuer serial number mismatch
32: key usage does not include certificate signing
50: application verification failure
details at http://www.openssl.org/docs/apps/verify.html#VERIFY_OPERATION
up
-2
luiheidsgoeroe at hotmail dot com
6 years ago
Keep in mind that for CURLOPT_RETURNTRANSFER it has to be set with curl_setopt() before execution:

This doesn't work:
<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>

This works:
<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_exec($ch);
var_dump(curl_getinfo($ch,CURLINFO_HEADER_OUT));
?>
up
-7
Piker
8 months ago
Example 1 should use "if(curl_errno($ch))" not "if(!curl_errno($ch))"
To Top