PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

curl_version> <curl_setopt_array
Last updated: Fri, 15 Aug 2008

view this page in

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setoptAsigna un valor a una opción de una sesión CURL

Descripción

bool curl_setopt ( resource $ch , int $option , mixed $value )

La función curl_setopt() asigna valores para opciones de una sesión CURL identificada por el parámetro ch . El parámetro option especifica la opción a la que se desea asignar el valor indicado en el parámetro value .

value debe ser una variable de tipo bool para los siguientes valores del parámetro option :

Opción Valor de value Notas
CURLOPT_AUTOREFERER TRUE para establecer de forma automática el campo Referer: en las peticiones que siguen las redirecciones de tipo Location:. Available since PHP 5.1.0.
CURLOPT_BINARYTRANSFER TRUE para devolver la salida completa cuando se usa CURLOPT_RETURNTRANSFER.
CURLOPT_COOKIESESSION TRUE para marcar esta cookie como una nueva cookie de sesión. Obliga a libcurl a ignorar todas las cookies que va a cargar y que son cookies de sesión de una sesión anterior. Por defecto, libcurl guarda y carga todas las cookies, independientemente de si son de sisió o no. Las cookies de sesión son las cookies que no tienen establecida una fecha de expiración y que se supone que solamente deben aplicarse y existir en esta sesión. Disponible desde PHP 5.1.0.
CURLOPT_CRLF TRUE para convertir los caracteres de nueva línea de Unix a caracteres de nueva línea de tipo CRLF en las transferencias.
CURLOPT_DNS_USE_GLOBAL_CACHE TRUE para utilizar una cache de DNS global. Esta opción no es compatible con entornos multi-hilo y por defecto está activada.
CURLOPT_FAILONERROR TRUE para que la ejecución de la función falle de forma "silenciosa" si el código HTTP devuelto es mayor que 300. El comportamiento por defecto es devolver la página normalmente, ignorando el código.
CURLOPT_FILETIME TRUE para intentar obtener la fecha remota de modificación del documento. Se puede obtener el valor empleando la opción CURLINFO_FILETIME con la función curl_getinfo().
CURLOPT_FOLLOWLOCATION TRUE para seguir las cabeceras "Location: " que puede enviar el servidor junto con el resto de las cabeceras HTTP (se debe tener en cuenta que el comportamiento es recursivo, por lo que PHP seguirá tantos encabezados "Location: " como se envien, a no ser que se establezca la opción CURLOPT_MAXREDIRS).
CURLOPT_FORBID_REUSE TRUE para forzar que la conexión se cierre de forma explícita cuando la transmisión ha finalizado y por tanto que no se reserve para su posterior reutilización.
CURLOPT_FRESH_CONNECT TRUE para forzar el uso de una conexión nueva en vez de reutilizar una conexión cacheada.
CURLOPT_FTP_USE_EPRT TRUE para emplear EPRT (y LPRT) cuando se están realizado descargas de tipo FTP. Se puede indicar FALSE para deshabilitar EPRT y LPRT y utilizar solamente PORT. Se incluyó en la versión de PHP 5.0.0.
CURLOPT_FTP_USE_EPSV TRUE para intentar en primer lugar un comando de tipo EPSV en las transferencias FTP y en segundo lugar un comando de tipo PASV. Se puede indicar FALSE para deshabilitar EPSV.
CURLOPT_FTPAPPEND TRUE para escribir a partir del final del archivo remoto en vez de sobreescribirlo.
CURLOPT_FTPASCII Se trata de un alias de la opción CURLOPT_TRANSFERTEXT, que se recomienda utilizar en vez de esta opción.
CURLOPT_FTPLISTONLY TRUE para obtener el listado de los elementos de un directorio de FTP.
CURLOPT_HEADER TRUE para que el encabezado se incluya en la salida.
CURLOPT_HTTPGET TRUE para volver a establecer el método HTTP al tipo GET. El método por defecto es GET, así que solamente es necesaria esta opción si el método ha sido modificado.
CURLOPT_HTTPPROXYTUNNEL TRUE para encaminar la transferencia a través de un tunel establecido con el servidor proxy HTTP indicado.
CURLOPT_MUTE TRUE para que las funciones CURL se comporten de forma completamente "silenciosa".
CURLOPT_NETRC TRUE para obtener el nombre de usuario y la contraseña necesarios para acceder a un sitio remoto a partir del archivo ~/.netrc.
CURLOPT_NOBODY TRUE para no incluir en la salida el contenido del body.
CURLOPT_NOPROGRESS TRUE para deshabilitar el medidor del progreso de las transferencias de tipo CURL.

Note: PHP por defecto establece esta opción como TRUE, por lo que solamente deberí cambiarse su valor para tareas de depuración.

CURLOPT_NOSIGNAL TRUE para que ninguna de las señales generadas por las funciones CURL se notifiquen la proceso de PHP. En entornos de ejecución de SAPIs multi-hilo está activado por defecto, de forma que las opciones de timeout puedan utilizarse. Se incluyó en la versión de CURL 7.10 y de PHP 5.0.0.
CURLOPT_POST TRUE para ejecutar una petición de tipo HTTP POST. El método empleado por el POST es el de application/x-www-form-urlencoded, que es el habitualmente empleado por los formularios HTML.
CURLOPT_PUT TRUE para ejecutar el método HTTP PUT sobre un archivo. El archivo debe indicarse mediante las opciones CURLOPT_INFILE y CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER TRUE para devolver el resultado como una cadena de texto que contiene el valor devuelto por la función curl_exec(), en vez de mostrar la salida directamente en la ventana del navegador.
CURLOPT_SSL_VERIFYPEER FALSE para evitar que CURL verifique el certificado del otro extremo. Se pueden especificar otros certificados para verificar mediante la opción CURLOPT_CAINFO y también se puede especificar un directorio de certificados mediante la opción CURLOPT_CAPATH. La opción CURLOPT_SSL_VERIFYHOST se debe establecer a TRUE o FALSE si la opción CURLOPT_SSL_VERIFYPEER está deshabilitada (su valor por defecto es 2). TRUE por defecto en la versión CURL 7.10. Conjunto instalado por defecto con la versión CURL 7.10.
CURLOPT_TRANSFERTEXT TRUE para emplear el modo de transmisión ASCII en las transferencias de FTP. Para LDAP, obtiene los datos en formato de texto plano en vez de en formato HTML. En los sistemas Windows, no establece la salida STDOUT a modo binario.
CURLOPT_UNRESTRICTED_AUTH TRUE para enviar el nombre de usuario y la contraseña cuando se siguen las cabeceras de tipo "Location: " (al activar la opción CURLOPT_FOLLOWLOCATION). El nombre de usuario y contraseña se envín aun cambiando el nombre del host en las redirecciones. Se incluyó en la version de PHP 5.0.0.
CURLOPT_UPLOAD TRUE para preparar una subida.
CURLOPT_VERBOSE TRUE para obtener la información completa sobre la salida. La salida se escribe en STDERR o en el fichero especificado mediante la opción CURLOPT_STDERR.

El parámetro value debe ser un entero para los siguientes valores del parámetro option :

Opción Valor de value Notas
CURLOPT_BUFFERSIZE El tamaño del buffer que se va a utilizar en cada operación de lectura. No se garantiza que la petición consiga llenar el buffer. Se incluyó en la versión de CURL 7.10 y de PHP 5.0.0.
CURLOPT_CLOSEPOLICY Puede ser o CURLCLOSEPOLICY_LEAST_RECENTLY_USED o CURLCLOSEPOLICY_OLDEST . Existen otros tres valores para CURLCLOSEPOLICY_, pero CURL no los soporta todaví.
CURLOPT_CONNECTTIMEOUT El número de segundos que se pueden esperar como máximo intentando establecer la conexión. Si se le da un valor de 0 (cero), se espera indefinidamente.
CURLOPT_DNS_CACHE_TIMEOUT El número de segundos que se mantienen las entradas de DNS en memoria. Por defecto toma un valor de 120 segundos (2 minutos).
CURLOPT_FTPSSLAUTH El método de autenticación de FTP (si se utiliza autenticación): CURLFTPAUTH_SSL (intentar primero SSL), CURLFTPAUTH_TLS (intentar primero TLS) o CURLFTPAUTH_DEFAULT (dejar que CURL decida el método). Se incluyó en la versión de CURL 7.12.2 y de PHP 5.1.0.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (por defecto se deja a CURL que decida que versión usar), CURL_HTTP_VERSION_1_0 (fuerza a usar HTTP/1.0), o CURL_HTTP_VERSION_1_1 (fuerza a usar HTTP/1.1).
CURLOPT_HTTPAUTH

El método de autenticación HTTP a utilizar. Las opciones son: CURLAUTH_BASIC , CURLAUTH_DIGEST , CURLAUTH_GSSNEGOTIATE , CURLAUTH_NTLM , CURLAUTH_ANY y CURLAUTH_ANYSAFE .

Se puede utilizar el operador bitwise | (conocido como "or") para combinar más de un método. Si se utiliza una combinación de métodos, CURL sondea al servidor para comprobar qué métodos soporta y así elegir el mejor de los soportados.

CURLAUTH_ANY es un alias de CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE es un alias de CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

Se incluyó en la versión de PHP 5.0.0.
CURLOPT_INFILESIZE El tamaño esperado en bytes del archivo empleado en una operación de subida de un archivo a un sitio remoto.
CURLOPT_LOW_SPEED_LIMIT La velocidad de transmisión, en bytes por segundo, que la transferencia debe obtener de manera continua durante CURLOPT_LOW_SPEED_TIME segundos para que PHP considere la transferencia demasiado lenta y la aborte.
CURLOPT_LOW_SPEED_TIME El número de segundos que la transferencia debe obtener de manera continua una velocidad de transferencia inferior a CURLOPT_LOW_SPEED_LIMIT bytes por segundo para que PHP considere la transferencia demasiado lenta y la aborte.
CURLOPT_MAXCONNECTS El número máximo de conexiones persistentes permitidas. Cuando se alcanza el límite establecido, se utiliza la opción CURLOPT_CLOSEPOLICY para determinar que conexión se cierra.
CURLOPT_MAXREDIRS El número máximo de redirecciones HTTP que se siguen. Se utiliza junto con la opción CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT Un número de puerto alternativo para realizar la conexión.
CURLOPT_PROXYAUTH Los métodos de autenticación HTTP empleados para una conexión proxy. Se emplean las mismas máscaras de bits que las descritas para la opción CURLOPT_HTTPAUTH. Para la autenticación proxy, solo se permiten los valores CURLAUTH_BASIC y CURLAUTH_NTLM . Se incluyó en la versión de CURL 7.10.7 y de PHP 5.1.0.
CURLOPT_PROXYPORT El número de puerto que se utiliza en las conexiones proxy. Este número se puede establecer también mediante la opción CURLOPT_PROXY. Se incluyó en la versión de PHP 5.0.0.
CURLOPT_PROXYTYPE Puede tomar el valor CURLPROXY_HTTP (valor por defecto) o CURLPROXY_SOCKS5 . Se incluyó en la versión de CURL 7.10 y de PHP 5.0.0.
CURLOPT_RESUME_FROM La posición en bytes desde la que se reanuda la transferencia.
CURLOPT_SSL_VERIFYHOST 1 para comprobar la existencia de un nombre común en el certificado SSL del otro extremo. 2 para comprobar la existencia de un nombre común y además comprobar si coincide el nombre del host proporcionado.
CURLOPT_SSLVERSION La versión de SSL a utilizar (puede ser 2 o 3). Por defecto PHP trata de determinarlo por si mismo, aunque en algunos casos puede ser necesario indicarlo manualmente.
CURLOPT_TIMECONDITION Manera en la que se trata la opción CURLOPT_TIMEVALUE. Si se indica el valor CURL_TIMECOND_IFMODSINCE , se devuelve la página solamente si ha sido modificada desde la fecha indicada en la opción CURLOPT_TIMEVALUE. Si no ha sido modificada, se devuelve una cabecera de tipo "304 Not Modified" si la opción CURLOPT_HEADER es TRUE. Si se indica el valor CURL_TIMECOND_ISUNMODSINCE el efecto conseguido es el contrario. El valor por defecto es CURL_TIMECOND_IFMODSINCE . Se incluyó en la versión de PHP 5.1.0.
CURLOPT_TIMEOUT El número máximo de segundos que CURL espera a que se ejecuten las funciones.
CURLOPT_TIMEVALUE La fecha en número de segundos transcurridos desde el 1 de Enero de 1970. La fecha se utiliza con la opción CURLOPT_TIMECONDITION. Por defecto, se utiliza el parámetro CURL_TIMECOND_IFMODSINCE .

value debe ser una cadena de texto para los siguientes valores del parámetro option :

Opción Valor de value Notas
CURLOPT_CAINFO El nombre del archivo que contiene uno o más certificados utilizados para la verificación con el otro extremo. Solamente es útil cuando se utiliza conjuntamente con la opción CURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATH El directorio que contiene los certificados de las CA. Se utiliza junto con la opción CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE El contenido de la cabecera "Set-Cookie: " que se utiliza en la petición HTTP.
CURLOPT_COOKIEFILE El nombre del archivo que contiene los datos de las cookies. El archivo puede tener el formato definido por Netscape o el formato de cabeceras HTTP volcadas directamente a un archivo en texto plano.
CURLOPT_COOKIEJAR El nombre del archivo en el que se guardan todas las cookies internas cuando se cierra la conexión.
CURLOPT_CUSTOMREQUEST Un método personalizado a utilizar en lugar de "GET" o "HEAD" cuando se hace una petición HTTP. Se utiliza cuando se quieren realizar peticiones HTTP no habituales como por ejemplo "DELETE". Los valores válidos son del tipo "GET", "POST", "CONNECT" y similares; esto es, no se debe introducir un valor complejo como por ejemplo "GET /index.html HTTP/1.0\r\n\r\n".

Note: No se deben emplear métodos personalizados si no se está seguro de que el servidor remoto los soporta.

CURLOPT_EGBSOCKET Es como CURLOPT_RANDOM_FILE, salvo que se indica un socket al demonio generador de entropía.
CURLOPT_ENCODING Los contenidos de la cabecera "Accept-Encoding: ". De esta forma, se permite la decodificación de la respuesta. Los valores permitidos son los de "identity", "deflate" y "gzip". Si se indica una cadena vací (""), se envía una cabecera que incluye todos los tipos de codificación. Se incluyó en la versión de PHP 5.0.0.
CURLOPT_FTPPORT El valor que se utiliza para obtener la dirección IP que se emplea en la instrucción "POST" de FTP. La instrucción "POST" indica al servidor remoto que se conecte a la dirección IP especificada. La cadena puede ser una dirección IP, el nombre de un host, el nombre de un interfaz de red (en entornos Unix) o el valor '-' para utilizar la dirección IP por defecto del sistema.
CURLOPT_INTERFACE El nombre del interfaz de red de salida a utilizar. Se puede indicar como nombre de interfaz, dirección IP o nombre de host.
CURLOPT_KRB4LEVEL El nivel de seguridad de KRB4 (Kerberos 4). Se permite cualquiera de los siguientes valores (ordenados de menos a m´s fuerte): "clear", "safe", "confidential", "private".. Si la cadena proporcionada no contiene ninguno de esos valores, se utiliza el valor "private". Si se proporciona un valor de NULL, se deshabilita la seguridad KRB4. Actualmente, este tipo de seguridad solamente funciona en las transferencias FTP.
CURLOPT_POSTFIELDS Los datos a enviar en una operación de tipo HTTP "POST".
CURLOPT_PROXY El proxy HTTP a través del que se encaminan las peticiones.
CURLOPT_PROXYUSERPWD El nombre de usuario y contraseña (indicados con el formato "[username]:[password]") que se van a utilizar para realizar la conexión con el proxy.
CURLOPT_RANDOM_FILE El nombre del archivo que se va a emplear para alimentar el generador de números aleatorios empleado por SSL.
CURLOPT_RANGE Rango de datos que se quieren obtener indicados de la forma "X-Y", donde X o Y son opcionales. Las transferencias HTTP soportan varios rangos diferentes simultaneos separados por comas, de la forma "X-Y,N-M".
CURLOPT_REFERER El contenido de la cabecera "Referer: " empleada en la petición HTTP.
CURLOPT_SSL_CIPHER_LIST La lista de algoritmos de tipo cipher a emplear por SSL. Los siguientes valores son válidos: RC4-SHA y TLSv1.
CURLOPT_SSLCERT El nombre del archivo que contiene el certificado almacenado en formato PEM.
CURLOPT_SSLCERTPASSWD La contraseña necesaria para utilizar el certificado CURLOPT_SSLCERT.
CURLOPT_SSLCERTTYPE El formato del certificado. Los formatos soportados son "PEM" (valor por defecto), "DER" y "ENG". se incluyó en la versión de CURL 7.9.3 y de PHP 5.0.0.
CURLOPT_SSLENGINE El identificador del generador criptográfico de la clave privada de SSL especificada en la opción CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT El identificador del generador criptográfico empleado en las operaciones criptográficas simétricas.
CURLOPT_SSLKEY El nombre del archivo que contiene la clave privada de SSL.
CURLOPT_SSLKEYPASSWD La contraseña secreta necesaria para utilizar la clave privada de SSL especificada en la opció CURLOPT_SSLKEY.

Note: Como esta opció requiere del uso de una contraseña que debe almacenarse en un lugar seguro, recuerde mantener el script de PHP en un entorno de ejecución seguro.

CURLOPT_SSLKEYTYPE El tipo de clave privada de SSL especificada en CURLOPT_SSLKEY. Los valores permitidos son "PEM" (valor por defecto), "DER" y "ENG".
CURLOPT_URL La URL que se quiere obtener. También se puede establecer su valor al inicializar una sesión con la función curl_init().
CURLOPT_USERAGENT El contenido de la cabecera "User-Agent: " enviada en las peticiones HTTP.
CURLOPT_USERPWD El nombre de usuario y contraseña (con el formato "[username]:[password]") que se va a utilizar para realizar la conexión.

value debería ser una variable de tipo array para los siguientes valores del parámetro option :

Opción Valor de value Notas
CURLOPT_HTTP200ALIASES Array de respuestas HTTP de tipo 200 que se tratarán como respuestas válidas y no errores. Se incluyó en la versió de CURL 7.10.3 y de PHP 5.0.0.
CURLOPT_HTTPHEADER Array de valores de cabeceras HTTP que se van a enviar.
CURLOPT_POSTQUOTE Array de comandos FTP que se van a ejecutar en el servidor remoto después de que se haya ejecutado la petición FTP.
CURLOPT_QUOTE Array de comandos FTP que se van a ejecutar en el servidor remoto antes de que se haya ejecutado la petición FTP.

value debe ser un recurso de tipo stream (obtenido por ejemplo mediante la función fopen()) para los siguientes valores del parámetro option :

Opción Valor de value Notas
CURLOPT_FILE Archivo al que se van a volcar los datos de la transferencia. Por defecto es STDOUT (por tanto, generalmente la ventana del navegador).
CURLOPT_INFILE Archivo del que la transferencia debe obtener los datos para las peticiones de tipo subida.
CURLOPT_STDERR Recurso alternativo para escribir los errores producidos en lugar de STDERR.
CURLOPT_WRITEHEADER Archivo en el que se escribe la parte de las cabeceras de la transferencia.

value debe ser una cadena de texto con el nombre válido de una función de tipo callback para los siguientes valores del parámetro option :

Opción Valor de value Notas
CURLOPT_HEADERFUNCTION Nombre de la función de callback que requiere de 2 argumentos. El primero es el recurso CURL y el segundo es una cadena que contiene los datos de la cabecera que se deben escribir. Si se utiliza esta función de callback, el programador tiene la responsabilidad de escribir los datos de la cabecera. La función devuelve el número de bytes escritos.
CURLOPT_PASSWDFUNCTION Nombre de la función de callback que requiere de 3 argumentos. El primero es el recurso CURL, el segundo es una cadena de texto que solicita que se introduzca una contraseña y el tercero es la longitud máxima de la contraseña. La función devuelve una cadena de texto que contiene la contraseña.
CURLOPT_READFUNCTION Nombre de la función de callback que requiere de 2 argumentos. El primero es el recurso CURL y el segundo es una cadena con los datos a leer. Si se utiliza esta función, el programador tiene la responsabilidad de leer los datos. La función devuelve el número de bytes leidos y devuelve 0 (cero) si se llega al final del archivo (EOF).
CURLOPT_WRITEFUNCTION Nombre de la función de callback que requiere de 2 argumentos. El primero es el recurso CURL y el segundo es una cadena de texto con los datos a escribir. Si se utiliza esta función, el programador tiene la responsabilidad de escribir los datos. La función debe devolver el número exacto de bytes que se han escrito o se producirá un error.

Example #1 Inicializar una nueva sesión CURL y obtener una página web

<?php
// Se crea un manejador CURL
$ch curl_init();

// Se establece la URL y algunas opciones
curl_setopt($chCURLOPT_URL"http://www.example.com/");
curl_setopt($chCURLOPT_HEADERfalse);

// Se obtiene la URL indicada
curl_exec($ch);

// Se cierra el recurso CURL y se liberan los recursos del sistema
curl_close($ch);
?>



curl_version> <curl_setopt_array
Last updated: Fri, 15 Aug 2008
 
add a note add a note User Contributed Notes
curl_setopt
w dot danford at electronics-software dot com
12-Aug-2008 07:12
Just a small detail I too easily overlooked.
<?php
/*  If you set:  */
curl_setopt ($ch, CURLOPT_POST, 1);
/* then you must have the data: */
curl_setopt ($ch, CURLOPT_POSTFIELDS, $PostData);
?>
I found with only the CURLOPT_POST set (from copy, paste editing of course) cookies were not getting sent with CURLOPT_COOKIE.  Just something subtle to watch out for.
fred at themancan dot com
06-Aug-2008 01:28
What encoding will a given HTTP POST request use?

The answer is easy -- passing an array to CURLOPT_POSTFIELDS results in  multipart/form-data:

<?php
curl_setopt
(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>

Passing a URL-encoded string will result in application/x-www-form-urlencoded:

<?php
curl_setopt
(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>

I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
jID
05-Aug-2008 01:56
if you use
<?php
curl_setopt
($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");
?>
to specify IP adress for request, sometimes you need to get list of all your IP's.

ifconfig command will output something like:

rl0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    options=8<VLAN_MTU>
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
    ether XX:XX:XX:XX:XX:XX
    media: Ethernet autoselect (100baseTX <full-duplex>)
    status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    Opened by PID 564
tun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
    Opened by PID 565
    Opened by PID 565

My solution for FreeBSD 6 and PHP 5 was:
<?php
  ob_start
();
 
$ips=array();
 
$ifconfig=system("ifconfig");
  echo
$ifconfig;
 
$ifconfig=ob_get_contents();
 
ob_end_clean();
 
$ifconfig=explode(chr(10), $ifconfig);
  for (
$i=0; $i<count($ifconfig); $i++) {
   
$t=explode(" ", $ifconfig[$i]);
    if (
$t[0]=="\tinet") {
     
array_push($ips, $t[1]);
    }    
  }
  for (
$i=0; $i<count($ips); $i++) {
    echo
$ips[$i]."\n";
  }
?>

You will get list of IP adresses in $ips array, like:
82.146.XXX.XXX
78.24.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
78.24.XXX.XXX
78.24.XXX.XXX
Anonymous
01-Aug-2008 10:03
Be careful when following Salil Kothadia's suggestion of using http_build_query with CURLOPT_POSTFIELDS.

As pinkgothic at gmail dot com explains on the http_build_query page: "Be careful if you're assuming that arg_separator defaults to '&'." For example, XAMPP changes the default in PHP.ini to '& amp' which may cause hours of frustration when trying to resolve failed form submissions.
ac at an dot y-co dot de
10-Jul-2008 07:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.

<?php
curl_setopt
($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFOgetcwd().'/cert/ca.crt');
curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/cert/mycert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'password');
?>

If your original certificate is in .pfx format, you have to convert it to .pem using following commands
# openssl pkcs12 -in mycert.pfx -out mycert.key
# openssl rsa -in mycert.key -out mycert.pem
# openssl x509 -in mycert.key >> mycert.pem
nick at glype dot com
07-Jul-2008 06:18
Although CURLOPT_CLOSEPOLICY and the applicable choices are valid constants, setting this option with curl_setopt() always returns false. A quick google search suggests the option is deprecated and/or never worked.
heron at xnapid dot com
19-Jun-2008 11:19
Someone posted this under tmpfile (http://us3.php.net/manual/en/function.tmpfile.php#69419), and I thought it was particularly useful:

By the way, this function is really useful for libcurl's CURLOPT_PUT feature if what you're trying to PUT is a string.   For example:

/* Create a cURL handle. */
$ch = curl_init();

/* Prepare the data for HTTP PUT. */
$putString = "Hello, world!";
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);

/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
/* ... (other curl options) ... */

/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($putData);
curl_close($ch);
Salil Kothadia
19-Jun-2008 06:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:

<?php
$ch
= curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
chaim1567 at googlemail dot com
09-Jun-2008 01:07
Be careful setting options while reusing a curl handle. I do not believe curl_exec resets the previous options e.g. the referrer and headers you set two requests ago may remain for the latest request.

I have not fully tested this and am interested in your results.
f00f
13-May-2008 09:17
Please note that the below is not entirely correct. This format will work partially, but does not always produce correct headers. The correct form for the same code is:
<?php
$str 
= array(
"Accept-Language: en-us,en;q=0.5",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300",
"Connection: keep-alive"
);
      
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, $str);
?>

The appropriate newlines/cr's *should* be handled by curl.

This realization has cost me many hours, because Host, User-Agent, Cache-Control, etc appear to be handled correctly with the string form, but Content-Length and Content-Type are duplicated and the second copy is not parsed correctly by the server!
hotrodder at rocketmail dot com
07-May-2008 03:26
I just spent the last 45 minutes banging my head against my keyboard because when using libcurl for a lighttpd server I would get a 400 Bad Request Error.

It turns out, that despite what has been mentioned in other comments, when using the CURLOPT_HTTPHEADER option, you must use \r\n as newline separators for each header NOT \n. For some reason lighttpd will not accept them. Other webservers will however.

Example:
<?php
$str 
= "Accept-Language: en-us,en;q=0.5\r\n";
$str .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$str .= "Keep-Alive: 300\r\n";
$str .= "Connection: keep-alive\r\n";
       
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, array($str));
?>
skylight at list ru
30-Apr-2008 11:31
OMG! I've joust found kinda bug:
YES, you can set an IP for curl to use by using this statement: curl_setopt($curl, CURLOPT_INTERFACE, $ip);
NO, you CAN NOT set another IP for the same curl object. I mean if u do curl_setopt($curl, CURLOPT_INTERFACE, $ip2); - it wont work!

So to change an IP you need to re-create curl object (curl_close, then curl_init).
sgamon at yahoo dot com
10-Apr-2008 02:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

* it adds a header, "Expect: 100-continue". 
* it then sends the request head, waits for a 100 response code, then sends the content

Not all web servers support this though.  Various errors are returned depending on the server.  If this happens to you, suppress the "Expect" header with this command:

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>

See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
john factorial
04-Apr-2008 06:22
Clarification for the CURLOPT_NOBODY option: by excluding the body from your request, you're effectively making a HEAD request. Use the CURLOPT_NOBODY option to return only the headers in the remote response.

Example:

function check_url($url) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, $url);
    curl_setopt($c, CURLOPT_HEADER, 1); // get the header
    curl_setopt($c, CURLOPT_NOBODY, 1); // and *only* get the header
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // get the response as a string from curl_exec(), rather than echoing it
    curl_setopt($c, CURLOPT_FRESH_CONNECT, 1); // don't use a cached version of the url
    if (!curl_exec($c)) { return false; }

    $httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
    return ($httpcode < 400);
}
mavook at gmail dot com
16-Feb-2008 07:26
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
^^ This will post multipart/form-data

Next example don't work:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_POST, 1);
Sets to content-lenght:0 if $postvars an array.
meat_popsiclez at hotmail dot com
29-Dec-2007 06:13
Despite the documentation for CURLOPT_HTTPHEADER, all header fields MUST be in one string, with a eol indicator, inside a single element array, in my experience.

For example, this will fail.
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50"));
?>

This will work.
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n"));
?>

This will only set the first header
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n","Otherheader: stuff\n"));
?>

This however, will set both headers as we want.
<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\nOtherheader: stuff\n"));
?>
contacto at hardcode dot com dot ar
12-Dec-2007 09:34
hey hey hey!
the problem: curl_setopt($ch,FOLLOW_LOCATION,1);
the error: trouble with open_basedir and safe_mode
the solution: a function already developed by someone
the solution n 2: the same function, modifed, works great for me..

function curl_redir_exec($ch,$debug="")
{
    static $curl_loops = 0;
    static $curl_max_loops = 20;

    if ($curl_loops++ >= $curl_max_loops)
    {
        $curl_loops = 0;
        return FALSE;
    }
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $debbbb = $data;
    list($header, $data) = explode("\n\n", $data, 2);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($http_code == 301 || $http_code == 302) {
        $matches = array();
        preg_match('/Location:(.*?)\n/', $header, $matches);
        $url = @parse_url(trim(array_pop($matches)));
        //print_r($url);
        if (!$url)
        {
            //couldn't process the url to redirect to
            $curl_loops = 0;
            return $data;
        }
        $last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
    /*    if (!$url['scheme'])
            $url['scheme'] = $last_url['scheme'];
        if (!$url['host'])
            $url['host'] = $last_url['host'];
        if (!$url['path'])
            $url['path'] = $last_url['path'];*/
        $new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
        curl_setopt($ch, CURLOPT_URL, $new_url);
    //    debug('Redirecting to', $new_url);

        return curl_redir_exec($ch);
    } else {
        $curl_loops=0;
        return $debbbb;
    }
}

just use this function without de FOLLOW_LOCATION and should work. the problem was that when you get to the line where you return the data if http_code was different than 301 oe 302, $data has obsolete information or none. so $debbbb does the job.

hope this helps someone out there

thanks from argentina
andrabr at gmail dot com
20-Aug-2007 11:03
This is very clear in hindsight, but it still cost me several hours:

 curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, 1);

means that you will tunnel THROUGH the proxy, as in "your communications will go as if the proxy is NOT THERE".

Why do you care? - Well, if you are trying to use, say, Paros, to debug HTTP between your cURL and the server, with CURLOPT_HTTPPROXYTUNNEL set to TRUE Paros will not see or log your traffic thus defeating the purpose and driving you nuts.

There are other cases, of course, where this option is extremely useful...
chuck
20-Jul-2007 06:07
The explanation of CURLOPT_NOBODY ("TRUE to exclude the body from the output.") seems unclear to me -- I originally read "output" to mean the return value, i.e. the response.  In fact it means to exclude the body from your *request*.  Not sure whether "output" means the same thing for CURLOPT_HEADER though.
michael sky
06-Jul-2007 12:09
if you are trying to connect to 'https://...' and after that want to work with POST data - that's the way:

$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile"); # SAME cookiefile
curl_setopt($curl, CURLOPT_URL, "url1"); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
$xxx = curl_exec($curl);

curl_setopt($curl, CURLOPT_URL, "url2"); # this is where you are requesting POST-method form results (working with secure connection using cookies after auth)
curl_setopt($curl, CURLOPT_POSTFIELDS, "var1=value&var2=value&var3=value&"); # form params that'll be used to get form results
$xxx = curl_exec($curl);

curl_close ($curl);
echo $xxx;
sleepwalker at rahulsjohari dot com
27-Jun-2007 08:18
Two things that I noted, one of which has been mentioned earlier, if you are connecting to an SSL site (https) and don't have the appropriate certificate, don't forget to set CURLOPT_SSL_VERIFYPEER as "false"... it's set to "true" by default. Scratched my head over 2 hours to figure this one out as I had a machine with an older version installed and everything worked fine without using this option on that one - but failed on other machines with newer versions.

Second very important thing, I've never had my scripts work (tried on various machines, multiple platforms) with a Relative path to a COOKIEJAR or COOKIEFILE. In my experience I HAVE to specify the absolute path and not the relative path.

Small script I wrote to connect to a page, gather all cookies into a jar, connect to another page to login, taking the cookiejar with you for authentication:

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/start.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start();      // Prevent output
curl_exec ($ch);
ob_end_clean();  // End preventing output
curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=".$f1."&field2=".$f2."&SomeFlag=True");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/Login.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
mcbreen at gmail dot com
12-Jun-2007 11:35
If you are getting the following error:

SSL: certificate subject name 'domain-or-ip-1.com' does not match target host name 'domain-or-ip-2.com'

Then you can set the following option to get around it:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
vincent at ludden dot nl
12-Jun-2007 10:55
Please note that the CURLOPT_INTERFACE setting only accepts IP addresses and hostnames of the local machine. It is not meant to send a URL to a specific IP address.
Jon Freilich
12-May-2007 06:52
curl will sometimes return an "Empty reply from server" error if you don't send a User-Agent string.  Use the CURLOPT_USERAGENT option.
rob at infoglobe dot net
24-Apr-2007 06:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)

CURLOPT_FTP_SSL

Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)

CURLFTPSSL_NONE

Don't attempt to use SSL.

CURLFTPSSL_TRY

Try using SSL, proceed as normal otherwise.

CURLFTPSSL_CONTROL

Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.

CURLFTPSSL_ALL

Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
alfredoaguirre dot v at gmail dot com
14-Mar-2007 01:26
Seems that CURLOPT_RETURNTRANSFER Option set to TRUE, returns a "1" when the transaction returns a blank page.

I think is for eliminate the FALSE to can be with a blank page as return
paczor
08-Mar-2007 03:50
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.

function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback')
Killerwhile
03-Mar-2007 03:36
In response to "brett at brettbrewer dot com" and Jamolkhon, the fact you don't take into account is when a redirection (Location: ...) occurs, all the headers are given so the \r\n\r\n can also separate twp consecutive headers.

An even better trick to get the header is to use CURLINFO_HEADER_SIZE :

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

$headers = substr($output, 0, $header_size - 4);
$body = substr($output, $header_size);

Then $headers contains all the headers.
Jamolkhon
15-Dec-2006 08:11
in response to "brett at brettbrewer dot com":
another useful way of getting headers without using regular expression

<?php

class CCurl {
    var
$m_handle;
    var
$m_header;
    var
$m_body;
   
    function
CCurl($sUrl) {
       
$this->m_handle = curl_init();
       
curl_setopt($this->m_handle, CURLOPT_URL, $sUrl);
       
curl_setopt($this->m_handle, CURLOPT_HEADER, 1);
       
curl_setopt($this->m_handle, CURLOPT_RETURNTRANSFER, 1);
        return;
    }
   
    function
getHeader() {
        return
$this->m_header;
    }
   
    function
execute() {
       
$sResponse = curl_exec($this->m_handle);
       
$this->m_body = substr($sResponse, strpos($sResponse, "\r\n\r\n") + 4);
       
$this->m_header = substr($sResponse, 0, -strlen($this->m_body));
        return
$this->m_body;
    }
   
    function
close() {
       
curl_close($this->m_handle);
        return;
    }
}

?>

(you can add something or make some changes to suit your needs)
eion at bigfoot dot com
22-Nov-2006 05:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...

then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5.  This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.

Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.

Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use.  As it is here, it returns the body of the response and not the header.  It also doesn't deal with redirection urls with username and passwords in them.

<?php
   
function curl_redir_exec($ch)
    {
        static
$curl_loops = 0;
        static
$curl_max_loops = 20;
        if (
$curl_loops++ >= $curl_max_loops)
        {
           
$curl_loops = 0;
            return
FALSE;
        }
       
curl_setopt($ch, CURLOPT_HEADER, true);
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       
$data = curl_exec($ch);
        list(
$header, $data) = explode("\n\n", $data, 2);
       
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if (
$http_code == 301 || $http_code == 302)
        {
           
$matches = array();
           
preg_match('/Location:(.*?)\n/', $header, $matches);
           
$url = @parse_url(trim(array_pop($matches)));
            if (!
$url)
            {
               
//couldn't process the url to redirect to
               
$curl_loops = 0;
                return
$data;
            }
           
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
            if (!
$url['scheme'])
               
$url['scheme'] = $last_url['scheme'];
            if (!
$url['host'])
               
$url['host'] = $last_url['host'];
            if (!
$url['path'])
               
$url['path'] = $last_url['path'];
           
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
           
curl_setopt($ch, CURLOPT_URL, $new_url);
           
debug('Redirecting to', $new_url);
            return
curl_redir_exec($ch);
        } else {
           
$curl_loops=0;
            return
$data;
        }
    }
?>
jochem AT hotmail dot com
09-Nov-2006 08:27
I have seen two posts complaining the "CURLOPT_POSTFIELDS" option is not working well.

This was the solution given below:

   $o="";
   foreach ($post_data as $k=>$v)
   {
       $o.= "$k=".utf8_encode($v)."&";
   }
   $post_data=substr($o,0,-1);

The assumption that this is an error is not true, as stated on http://curl.rtin.bz/docs/httpscripting.html:
"  The data you send to the server MUST already be properly encoded, curl will
  not do that for you. For example, if you want the data to contain a space,
  you need to replace that space with %20 etc. Failing to comply with this
  will most likely cause your data to be received wrongly and messed up."

This means you do really have to encode the data yourself the right way.
zarko at svetlozar dot net
01-Oct-2006 01:51
As Yevgen mentioned earlier sometimes we can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE. Below is a header callback function I wrote back in January that lets you maintain cookies between cURL requests. Cookies are added to $ch during all requests even during redirection, so you can use it together with CURLOPT_FOLLOWLOCATION.
Here is the code:

function read_header($ch, $string)
{
    global $location; #keep track of location/redirects
    global $cookiearr; #store cookies here
    global $ch;
       # ^overrides the function param $ch
       # this is okay because we need to
       # update the global $ch with
       # new cookies
   
    $length = strlen($string);
    if(!strncmp($string, "Location:", 9))
    { #keep track of last redirect
      $location = trim(substr($string, 9, -1));
    }
    if(!strncmp($string, "Set-Cookie:", 11))
    { #get the cookie
      $cookiestr = trim(substr($string, 11, -1));
      $cookie = explode(';', $cookiestr);
      $cookie = explode('=', $cookie[0]);
      $cookiename = trim(array_shift($cookie));
      $cookiearr[$cookiename] = trim(implode('=', $cookie));
    }
    $cookie = "";
    if(trim($string) == "")
    {  #execute only at end of header
      foreach ($cookiearr as $key=>$value)
      {
        $cookie .= "$key=$value; ";
      }
      curl_setopt($ch, CURLOPT_COOKIE, $cookie);
    }

    return $length;
}

Using the header function with curl (add this before curl_exec):

#don't forget globals, especially if you are using this in function
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');

This code assumes that you will reuse $ch without initializing it every time (call curl_init only once, in the beginning). If you need to initialize $ch again at any point in your code you can access the currently stored cookies in $cookiearr and include them in the new $ch.

I wrote this function before I had enough experience with regular expressions so you won't find any preg_match calls here. I have used this code for quite a while and without any problems accessing gmail, yahoo, hotmail, aol etc. where I had to go through login and a few pages before getting to what I was looking for.

Svetlozar Petrov (http://svetlozar.net)
php at miggy dot org
23-Aug-2006 07:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: "));

else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
bendavis78 at gmail dot com
14-Jul-2006 12:58
You can use CURLOPT_HEADERFUNCTION  with a callback inside an object.  This makes is it easy to capture the headers for later use.  For example:
<?
class Test
{
   
public $headers;

   
//...

   
public function exec($opts)
    {
       
$this->headers = array();
       
$opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
       
$ch = curl_init();
       
curl_setopt_array($ch, $opts);
        return
curl_exec($ch);
    }

   
private function _setHeader($ch, $header)
    {
       
$this->headers[] = $header;
        return
strlen($header);
    }

   
}

$test = new Test();
$opts = array(
  
//... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>

...something like that

(This works in php v. 5.1.4)
Philippe dot Jausions at 11abacus dot com
30-May-2006 08:31
Clarification on the callback methods:

- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.

The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.

 -Philippe
mr at coder dot tv
14-Apr-2006 04:22
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);   
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE,  $cookies);

Good Luck, Yevgen
giunta dot gaetano at sea-aeroportimilano dot it
27-Mar-2006 12:59
- CURLOPT-HTTPAUTH is defined in php 4.4.2 9and maybe lower), even tough the manual says php 5.0 only...

- it is not clear from the manual what kind of http auth is carried out by default if user specifies username/pwd: it is BASIC auth

ps: note to manual writers: the version info on this page always looks a bit inaccurate, especially regarding the php version where a given option first appeared...
Dustin Hawkins
27-Dec-2005 11:24
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...

In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)

You can then use a command simiar to this to translate your apache certificate into one that curl likes.

$ openssl x509 -in server.crt -out outcert.pem -text

Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.

If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.

If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
skyogre __at__ yandex __dot__ ru
22-Dec-2005 11:13
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.

<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
 
assert( is_array($data) );
 
$vars=null;
  foreach(
$data as $key=>$value) {
    if(
is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
    else
$vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
  }
  return
$vars