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

search for in the

curl_close> <ctype_xdigit
[edit] Last updated: Mon, 01 Nov 2010

view this page in

XVIII. Funciones CURL (Client URL Library)

Introducción

PHP soporta libcurl, una librería creada por Danile Stenberg, que permite la conexión y comunicación con varios tipos de servidores diferentes y con muchos tipos de protocolos diferentes. Actualmente, libcurl soporta los portocolos http, https, ftp, gopher, telnet, dict, file y ldap. Además libcurl también soporta certificados HTTPS, métodos HTTP POST y HTTP PUT, envío por FTP (que también puede realizarse con la extensión ftp de PHP), envío mediante HTTP de archivos en formularios HTML, servidores proxy, cookies y autenticación usuario+contraseña.

Estas funciones fueron agregadas en la versión 4.0.2.

Requisitos

Para poder usar las funciones CURL deberá instalar el paquete CURL. PHP requiere que use CURL 7.0.2-beta o superior. Desde la versión 4.2.3 de PHP se necesita, al menos, CURL 7.9.0 o superior. A partir de la versión 4.3.0, se necesita una versión de CURL 7.9.8 o superior. A partir de la versión PHP 5.0.0, la versión de CURL necesaria debe ser superior a 7.10.5.

Instalación

Para poder usar estas funciones, se debe compilar PHP añadiendo el parámetro --with-curl[=DIR], donde DIR apunta al directorio que contiene los directorios lib y include de la librería. En el directorio include, debe existir una carpeta llamada "curl" y que contiene los archivos easy.h y curl.h. Además, debe existir un archivo llamado libcurl.a en el directorio "lib". A partir de la versión de PHP 4.3.0 se puede configurar que PHP haga uso de CURL para el manejo de las conexiones con URLs, mediante la opción --with-curlwrappers.

Nota para los usuarios de plataformas Windows: Para activar este módulo en entornos Windows, se deben copiar los archivos libeay32.dll y ssleay32.dll que se encuentran en la carpeta DLL del directorio PHP/Win32 a la carpeta SYSTEM de Windows, que normalmente se encuentra en C:\WINNT\SYSTEM32 o C:\WINDOWS\SYSTEM.

Constantes predefinidas

Estas constantes están definidas por esta extensión y estarán disponibles solamente cuando la extensión ha sido o bien compilada dentro de PHP o grabada dinámicamente en tiempo de ejecución.

CURLOPT_AUTOREFERER (integer)

Disponible desde PHP 5.1.0

CURLOPT_COOKIESESSION (integer)

Disponible desde PHP 5.1.0

CURLOPT_DNS_USE_GLOBAL_CACHE (integer)

CURLOPT_DNS_CACHE_TIMEOUT (integer)

CURLOPT_FTPSSLAUTH (integer)

Disponible desde PHP 5.1.0

CURLOPT_PORT (integer)

CURLOPT_FILE (integer)

CURLOPT_INFILE (integer)

CURLOPT_INFILESIZE (integer)

CURLOPT_URL (integer)

CURLOPT_PROXY (integer)

CURLOPT_VERBOSE (integer)

CURLOPT_HEADER (integer)

CURLOPT_HTTPHEADER (integer)

CURLOPT_NOPROGRESS (integer)

CURLOPT_NOBODY (integer)

CURLOPT_FAILONERROR (integer)

CURLOPT_UPLOAD (integer)

CURLOPT_POST (integer)

CURLOPT_FTPLISTONLY (integer)

CURLOPT_FTPAPPEND (integer)

CURLOPT_NETRC (integer)

CURLOPT_FOLLOWLOCATION (integer)

CURLOPT_FTPASCII (integer)

CURLOPT_PUT (integer)

CURLOPT_MUTE (integer)

CURLOPT_USERPWD (integer)

CURLOPT_PROXYUSERPWD (integer)

CURLOPT_RANGE (integer)

CURLOPT_TIMEOUT (integer)

CURLOPT_POSTFIELDS (integer)

CURLOPT_REFERER (integer)

CURLOPT_USERAGENT (integer)

CURLOPT_FTPPORT (integer)

CURLOPT_FTP_USE_EPSV (integer)

CURLOPT_LOW_SPEED_LIMIT (integer)

CURLOPT_LOW_SPEED_TIME (integer)

CURLOPT_RESUME_FROM (integer)

CURLOPT_COOKIE (integer)

CURLOPT_SSLCERT (integer)

CURLOPT_SSLCERTPASSWD (integer)

CURLOPT_WRITEHEADER (integer)

CURLOPT_SSL_VERIFYHOST (integer)

CURLOPT_COOKIEFILE (integer)

CURLOPT_SSLVERSION (integer)

CURLOPT_TIMECONDITION (integer)

CURLOPT_TIMEVALUE (integer)

CURLOPT_CUSTOMREQUEST (integer)

CURLOPT_STDERR (integer)

CURLOPT_TRANSFERTEXT (integer)

CURLOPT_RETURNTRANSFER (integer)

CURLOPT_QUOTE (integer)

CURLOPT_POSTQUOTE (integer)

CURLOPT_INTERFACE (integer)

CURLOPT_KRB4LEVEL (integer)

CURLOPT_HTTPPROXYTUNNEL (integer)

CURLOPT_FILETIME (integer)

CURLOPT_WRITEFUNCTION (integer)

CURLOPT_READFUNCTION (integer)

CURLOPT_PASSWDFUNCTION (integer)

CURLOPT_HEADERFUNCTION (integer)

CURLOPT_MAXREDIRS (integer)

CURLOPT_MAXCONNECTS (integer)

CURLOPT_CLOSEPOLICY (integer)

CURLOPT_FRESH_CONNECT (integer)

CURLOPT_FORBID_REUSE (integer)

CURLOPT_RANDOM_FILE (integer)

CURLOPT_EGDSOCKET (integer)

CURLOPT_CONNECTTIMEOUT (integer)

CURLOPT_SSL_VERIFYPEER (integer)

CURLOPT_CAINFO (integer)

CURLOPT_CAPATH (integer)

CURLOPT_COOKIEJAR (integer)

CURLOPT_SSL_CIPHER_LIST (integer)

CURLOPT_BINARYTRANSFER (integer)

CURLOPT_NOSIGNAL (integer)

CURLOPT_PROXYTYPE (integer)

CURLOPT_BUFFERSIZE (integer)

CURLOPT_HTTPGET (integer)

CURLOPT_HTTP_VERSION (integer)

CURLOPT_SSLKEY (integer)

CURLOPT_SSLKEYTYPE (integer)

CURLOPT_SSLKEYPASSWD (integer)

CURLOPT_SSLENGINE (integer)

CURLOPT_SSLENGINE_DEFAULT (integer)

CURLOPT_SSLCERTTYPE (integer)

CURLOPT_CRLF (integer)

CURLOPT_ENCODING (integer)

CURLOPT_PROXYPORT (integer)

CURLOPT_UNRESTRICTED_AUTH (integer)

CURLOPT_FTP_USE_EPRT (integer)

CURLOPT_HTTP200ALIASES (integer)

CURLOPT_HTTPAUTH (integer)

CURLAUTH_BASIC (integer)

CURLAUTH_DIGEST (integer)

CURLAUTH_GSSNEGOTIATE (integer)

CURLAUTH_NTLM (integer)

CURLAUTH_ANY (integer)

CURLAUTH_ANYSAFE (integer)

CURLOPT_PROXYAUTH (integer)

CURLCLOSEPOLICY_LEAST_RECENTLY_USED (integer)

CURLCLOSEPOLICY_LEAST_TRAFFIC (integer)

CURLCLOSEPOLICY_SLOWEST (integer)

CURLCLOSEPOLICY_CALLBACK (integer)

CURLCLOSEPOLICY_OLDEST (integer)

CURLINFO_EFFECTIVE_URL (integer)

CURLINFO_HTTP_CODE (integer)

CURLINFO_HEADER_SIZE (integer)

CURLINFO_REQUEST_SIZE (integer)

CURLINFO_TOTAL_TIME (integer)

CURLINFO_NAMELOOKUP_TIME (integer)

CURLINFO_CONNECT_TIME (integer)

CURLINFO_PRETRANSFER_TIME (integer)

CURLINFO_SIZE_UPLOAD (integer)

CURLINFO_SIZE_DOWNLOAD (integer)

CURLINFO_SPEED_DOWNLOAD (integer)

CURLINFO_SPEED_UPLOAD (integer)

CURLINFO_FILETIME (integer)

CURLINFO_SSL_VERIFYRESULT (integer)

CURLINFO_CONTENT_LENGTH_DOWNLOAD (integer)

CURLINFO_CONTENT_LENGTH_UPLOAD (integer)

CURLINFO_STARTTRANSFER_TIME (integer)

CURLINFO_CONTENT_TYPE (integer)

CURLINFO_REDIRECT_TIME (integer)

CURLINFO_REDIRECT_COUNT (integer)

CURL_VERSION_IPV6 (integer)

CURL_VERSION_KERBEROS4 (integer)

CURL_VERSION_SSL (integer)

CURL_VERSION_LIBZ (integer)

CURLVERSION_NOW (integer)

CURLE_OK (integer)

CURLE_UNSUPPORTED_PROTOCOL (integer)

CURLE_FAILED_INIT (integer)

CURLE_URL_MALFORMAT (integer)

CURLE_URL_MALFORMAT_USER (integer)

CURLE_COULDNT_RESOLVE_PROXY (integer)

CURLE_COULDNT_RESOLVE_HOST (integer)

CURLE_COULDNT_CONNECT (integer)

CURLE_FTP_WEIRD_SERVER_REPLY (integer)

CURLE_FTP_ACCESS_DENIED (integer)

CURLE_FTP_USER_PASSWORD_INCORRECT (integer)

CURLE_FTP_WEIRD_PASS_REPLY (integer)

CURLE_FTP_WEIRD_USER_REPLY (integer)

CURLE_FTP_WEIRD_PASV_REPLY (integer)

CURLE_FTP_WEIRD_227_FORMAT (integer)

CURLE_FTP_CANT_GET_HOST (integer)

CURLE_FTP_CANT_RECONNECT (integer)

CURLE_FTP_COULDNT_SET_BINARY (integer)

CURLE_PARTIAL_FILE (integer)

CURLE_FTP_COULDNT_RETR_FILE (integer)

CURLE_FTP_WRITE_ERROR (integer)

CURLE_FTP_QUOTE_ERROR (integer)

CURLE_HTTP_NOT_FOUND (integer)

CURLE_WRITE_ERROR (integer)

CURLE_MALFORMAT_USER (integer)

CURLE_FTP_COULDNT_STOR_FILE (integer)

CURLE_READ_ERROR (integer)

CURLE_OUT_OF_MEMORY (integer)

CURLE_OPERATION_TIMEOUTED (integer)

CURLE_FTP_COULDNT_SET_ASCII (integer)

CURLE_FTP_PORT_FAILED (integer)

CURLE_FTP_COULDNT_USE_REST (integer)

CURLE_FTP_COULDNT_GET_SIZE (integer)

CURLE_HTTP_RANGE_ERROR (integer)

CURLE_HTTP_POST_ERROR (integer)

CURLE_SSL_CONNECT_ERROR (integer)

CURLE_FTP_BAD_DOWNLOAD_RESUME (integer)

CURLE_FILE_COULDNT_READ_FILE (integer)

CURLE_LDAP_CANNOT_BIND (integer)

CURLE_LDAP_SEARCH_FAILED (integer)

CURLE_LIBRARY_NOT_FOUND (integer)

CURLE_FUNCTION_NOT_FOUND (integer)

CURLE_ABORTED_BY_CALLBACK (integer)

CURLE_BAD_FUNCTION_ARGUMENT (integer)

CURLE_BAD_CALLING_ORDER (integer)

CURLE_HTTP_PORT_FAILED (integer)

CURLE_BAD_PASSWORD_ENTERED (integer)

CURLE_TOO_MANY_REDIRECTS (integer)

CURLE_UNKNOWN_TELNET_OPTION (integer)

CURLE_TELNET_OPTION_SYNTAX (integer)

CURLE_OBSOLETE (integer)

CURLE_SSL_PEER_CERTIFICATE (integer)

CURLE_GOT_NOTHING (integer)

CURLE_SSL_ENGINE_NOTFOUND (integer)

CURLE_SSL_ENGINE_SETFAILED (integer)

CURLE_SEND_ERROR (integer)

CURLE_RECV_ERROR (integer)

CURLE_SHARE_IN_USE (integer)

CURLE_SSL_CERTPROBLEM (integer)

CURLE_SSL_CIPHER (integer)

CURLE_SSL_CACERT (integer)

CURLE_BAD_CONTENT_ENCODING (integer)

CURLE_LDAP_INVALID_URL (integer)

CURLE_FILESIZE_EXCEEDED (integer)

CURLE_FTP_SSL_FAILED (integer)

CURLFTPAUTH_DEFAULT (integer)

Disponible desde PHP 5.1.0

CURLFTPAUTH_SSL (integer)

Disponible desde PHP 5.1.0

CURLFTPAUTH_TLS (integer)

Disponible desde PHP 5.1.0

CURLPROXY_HTTP (integer)

CURLPROXY_SOCKS5 (integer)

CURL_NETRC_OPTIONAL (integer)

CURL_NETRC_IGNORED (integer)

CURL_NETRC_REQUIRED (integer)

CURL_HTTP_VERSION_NONE (integer)

CURL_HTTP_VERSION_1_0 (integer)

CURL_HTTP_VERSION_1_1 (integer)

CURLM_CALL_MULTI_PERFORM (integer)

CURLM_OK (integer)

CURLM_BAD_HANDLE (integer)

CURLM_BAD_EASY_HANDLE (integer)

CURLM_OUT_OF_MEMORY (integer)

CURLM_INTERNAL_ERROR (integer)

CURLMSG_DONE (integer)

Ejemplos

Una vez que se ha compilado PHP con soporte para CURL, se pueden utilizar las funciones CURL. La idea básica tras las funciones CURL es que se inicializa una sesión CURL usando la función curl_init(), luego se establecen las opciones para la transferencia a través de la función curl_setopt(), y finalmente se ejecuta la sesión con la función curl_exec() para luego cerrarla con curl_close(). Aqui hay un ejemplo que usa funciones CURL para traer el contenido de la página de inicio de www.example.com y guardarlo en un archivo:

Ejemplo 1. Usando el modulo CURL de PHP para traer la página de inicio de www.example.com

<?php

$ch
= curl_init ("http://www.example.com/");
$fp = fopen ("pagina_de_inicio.txt", "w");

curl_setopt ($ch, CURLOPT_FILE, $fp);
curl_setopt ($ch, CURLOPT_HEADER, 0);

curl_exec ($ch);
curl_close ($ch);
fclose ($fp);
?>

Tabla de contenidos
curl_close -- Cierra una sesión CURL
curl_copy_handle --  Copia un recurso CURL y todas sus opciones asociadas
curl_errno -- Devuelve el último número de error
curl_error --  Devuelve una cadena conteniendo el último error para la sesión actual.
curl_exec -- Ejecuta una sesión CURL
curl_getinfo --  Obtiene información relativa a una transferencia específica
curl_init -- Inicializa una sesión CURL
curl_multi_add_handle --  Añade un recurso de tipo CURL a un grupo de recursos CURL
curl_multi_close --  Cierra un grupo de recursos CURL
curl_multi_exec --  Ejecuta la subconexiones del manejador CURL actual
curl_multi_getcontent --  Devuelve el contenido de un recurso CURL si la opción CURLOPT_RETURNTRANSFER está activada
curl_multi_info_read --  Obtiene información sobre las transferencias actuales
curl_multi_init --  Crea un nuevo grupo de recursos CURL
curl_multi_remove_handle --  Elimina un recurso de tipo CURL de un grupo de recursos CURL
curl_multi_select --  Obtiene todos los sockets asociados a la extensión CURL, que después pueden ser seleccionados.
curl_setopt -- Asigna un valor a una opción de una sesión CURL
curl_version -- Devuelve la versión actual de CURL


curl_close> <ctype_xdigit
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Funciones CURL (Client URL Library)
arturm at union dot com dot pl 20-Apr-2010 09:03
One of the reasons why curl can be slow is that it appends header "Expect: 100-continue". Try this fix:

<?php
$headers
= array(
 
"Expect:",
 
// more headers here
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
?>
Emprivo.com 26-Aug-2009 09:58
Fixed bugs in the function posted earlier (better javascript redirect following and now supports HTTPS)

<?php

/*==================================
Get url content and response headers (given a url, follows all redirections on it and returned content and response headers of final url)

@return    array[0]    content
        array[1]    array of response headers
==================================*/
function get_url( $url$javascript_loop = 0, $timeout = 5 )
{
   
$url = str_replace( "&amp;", "&", urldecode(trim($url)) );

   
$cookie = tempnam ("/tmp", "CURLCOOKIE");
   
$ch = curl_init();
   
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
   
curl_setopt( $ch, CURLOPT_URL, $url );
   
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
   
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
   
curl_setopt( $ch, CURLOPT_ENCODING, "" );
   
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
   
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
   
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );    # required for https urls
   
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
   
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
   
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
   
$content = curl_exec( $ch );
   
$response = curl_getinfo( $ch );
   
curl_close ( $ch );

    if (
$response['http_code'] == 301 || $response['http_code'] == 302)
    {
       
ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");

        if (
$headers = get_headers($response['url']) )
        {
            foreach(
$headers as $value )
            {
                if (
substr( strtolower($value), 0, 9 ) == "location:" )
                    return
get_url( trim( substr( $value, 9, strlen($value) ) ) );
            }
        }
    }

    if (    (
preg_match("/>[[:space:]]+window\.location\.replace\('(.*)'\)/i", $content, $value) || preg_match("/>[[:space:]]+window\.location\=\"(.*)\"/i", $content, $value) ) &&
           
$javascript_loop < 5
   
)
    {
        return
get_url( $value[1], $javascript_loop+1 );
    }
    else
    {
        return array(
$content, $response );
    }
}

?>
Emprivo 11-Aug-2009 12:21
To follow ALL redirects using CURL brings up a lot of special cases. Here's a function that takes everything into account (even javascript redirects)

<?php

function get_final_url( $url, $timeout = 5 )
{
   
$url = str_replace( "&amp;", "&", urldecode(trim($url)) );

   
$cookie = tempnam ("/tmp", "CURLCOOKIE");
   
$ch = curl_init();
   
curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
   
curl_setopt( $ch, CURLOPT_URL, $url );
   
curl_setopt( $ch, CURLOPT_COOKIEJAR, $cookie );
   
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
   
curl_setopt( $ch, CURLOPT_ENCODING, "" );
   
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
   
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
   
curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
   
curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
   
curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
   
$content = curl_exec( $ch );
   
$response = curl_getinfo( $ch );
   
curl_close ( $ch );

    if (
$response['http_code'] == 301 || $response['http_code'] == 302)
    {
       
ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
       
$headers = get_headers($response['url']);

       
$location = "";
        foreach(
$headers as $value )
        {
            if (
substr( strtolower($value), 0, 9 ) == "location:" )
                return
get_final_url( trim( substr( $value, 9, strlen($value) ) ) );
        }
    }

    if (   
preg_match("/window\.location\.replace\('(.*)'\)/i", $content, $value) ||
           
preg_match("/window\.location\=\"(.*)\"/i", $content, $value)
    )
    {
        return
get_final_url ( $value[1] );
    }
    else
    {
        return
$response['url'];
    }
}

?>
Peter X. 02-May-2008 07:44
Although it has been noted that cURL outperforms both file_get_contents and fopen when it comes to getting a file over a HTTP link, the disadvantage of cURL is that it has no way of only reading a part of a page at a time.

For example, the following code is likely to generate a memory limit error:

<?php
$ch
= curl_init("http://www.example.com/reallybigfile.tar.gz");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
$output = curl_exec($ch);

$fh = fopen("out.tar.gz", 'w');
fwrite($fh, $output);
fclose($fh);
?>

While this, on the other hand, wouldn't

<?php
$hostfile
= fopen("http://www.example.com/reallybigfile.tar.gz", 'r');
$fh = fopen("out.tar.gz", 'w');

while (!
feof($hostfile)) {
   
$output = fread($hostfile, 8192);
   
fwrite($fh, $output);
}
   
fclose($hostfile);
fclose($fh);
?>
cduke420 at gmail dot com 02-May-2008 11:20
In order to prevent curl sending messages to the server error log, you need to instruct curl to use a temporary file for output on stderr.

<?php
$gacookie
="/askapache/tmp/curl-1.txt";
@
touch($gacookie);
@
chmod($gacookie,0666);

if(
$fp = tmpfile()){
 
$ch = curl_init("http://www.askapache.com/p.php");
 
curl_setopt ($ch, CURLOPT_STDERR, $fp);
 
curl_setopt ($ch, CURLOPT_VERBOSE, 2);
 
curl_setopt ($ch, CURLOPT_ENCODING, 0);
 
curl_setopt ($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
 
curl_setopt ($ch, CURLOPT_HTTPHEADER, $FF);
 
curl_setopt ($ch, CURLOPT_COOKIEFILE, $gacookie);
 
curl_setopt ($ch, CURLOPT_COOKIEJAR, $gacookie);
 
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt ($ch, CURLOPT_FAILONERROR, 1);
 
curl_setopt ($ch, CURLOPT_HEADER, 1);
 
curl_setopt ($ch, CURLINFO_HEADER_OUT, 1);
 
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 30);
 
$r=curl_exec($ch);$ch_info=curl_getinfo($ch);   
  if (
curl_errno($ch)) return false;
  else
curl_close($ch);
 
header("Content-type: text/plain");
  echo
$r;
 
sleep(2);
   
 
$postdata='keywords='.$_GET['k'];
   
 
$ch1 = curl_init("http://www.askapache.com/p.php");
 
curl_setopt ($ch1, CURLOPT_STDERR, $fp);
 
curl_setopt ($ch1, CURLOPT_VERBOSE, 2);
 
curl_setopt ($ch1, CURLOPT_ENCODING, 0);
 
curl_setopt ($ch1, CURLOPT_USERAGENT, 'Mozilla/5.0');
 
curl_setopt ($ch1, CURLOPT_COOKIEJAR, $gacookie);
 
curl_setopt ($ch1, CURLOPT_COOKIEFILE, $gacookie);
 
curl_setopt ($ch1, CURLOPT_POSTFIELDS, $postdata);
 
curl_setopt ($ch1, CURLOPT_POST, 1);
 
curl_setopt ($ch1, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt ($ch1, CURLOPT_FAILONERROR, 1);
 
curl_setopt ($ch1, CURLOPT_HEADER, 1);
 
curl_setopt ($ch1, CURLINFO_HEADER_OUT, 1);
 
curl_setopt ($ch1, CURLOPT_CONNECTTIMEOUT, 30);
 
$r=curl_exec ($ch1);$ch1_info=curl_getinfo($ch1);
  if (
curl_errno($ch1)) return false;
  else
curl_close($ch1);
 
header("Content-type: text/plain");print_r($ch1_info);echo $r;sleep(2);

}
fclose($fp);
@
unlink($gacookie);
?>

See also: http://www.askapache.com/security/curl-google-post-feed.html
fgabrieli at gmail com 08-Mar-2008 06:20
Do not forget to use the complete path for the cookies

<?php
$ch
= curl_init() ;

$myfile = "d:\\mydir\\second_dir\\cookiefile.txt" ;

curl_setopt($ch, CURLOPT_COOKIEJAR, $myfile) ;
?>

Best regards,
Fernando Gabrieli
lancelot--du-lac at hotmail dot fr 26-Jan-2008 03:26
As a windows xp user having php 5.2.5 running as an apache module on my personal computer, all I had to do in order to get this CURL stuff working is to uncomment the following line in my php.ini file:

extension=php_curl.dll

Thought I'd just mention it as it may save time to others since it seems somehow less compicated than the process mentioned (without sufficient explanation, mind you) in the above article (compile php??? options??? all I ever did to install php was to unzip the archive I downloaded and add a couple of line to my apache conf file).

I just tried downloading a web page and save its source into a text file using the example from the manual above. When the php_curl.dll extension is not active, it doesn't work (fatal error with init_curl, as you'd expect). When the php_curl.dll extension is active, it works. No need for any other intricate operation as far as I can say.

Otherwise, it's great that I now have my tool for doing any http request i want.
ryan at tankprofiler dot com 29-Oct-2007 12:26
If you have trouble on server 2003, IIS 6 ( perhaps other versions ) with getting the php_curl loading please see the following. 

- run (as an administrator) php.exe -i > C:\phpinfo.txt and go open C:\phpinfo.txt, look in the file to see if CURL was loading, if it's there then keep reading. 

- running <?PHP phpinfo(); ?> inside a text.php script on my IIS server would not show CURL loading

- A permissions problem on libeay32.dll and ssleay32.dll was causing the cli version of php allowing me access to these two dlls while IIS was not able to get them.  I gave 'everyone' read and execute on these two dll's to try to fix the issue and it just now worked. You may wish to be more restrictive, perhaps IUSR rather than EVERYONE; but check your permissions none-the-less.

Hopefully this saves someone some time!
- Ryan Nanney
Mr.KTO 07-Jul-2007 06:59
Don't foget to curl_close($ch); Even if curl_errno($ch) != 0

Because if you don't - on Windows this will produce windows-error-report (Program terminated unexpectedly)
killermonk at REMOVE dot killermonk dot com 06-Mar-2007 11:23
For anyone trying to use cURL to submit to an ASP/ASPX page that uses an image as the submit button.

Make sure that you have 'button_name.x' and 'button_name.y' in the post fields. PHP names these fields 'button_name_x' and 'button_name_y', while ASP uses a dot.

Also, as noted above, be sure to include the '__VIEWSTATE' input field in your post request.
gordon_e_rouse at yahoo dot com dot au 25-Jan-2007 02:24
Using curl to take snapshots of the current page for emailing the HTML is a clever little idea. (ie: Email this page to a friend)

<?php
//to be explained below!
session_write_close();

$pageurl = "http://www.site.com/content.php?PHPSESSID=123XYZ
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt ($ch, CURLOPT_URL, $pageurl );
$html = curl_exec ( $ch );
curl_close($ch);

//then you need to fix pathing to absolute
$search = "
/(src|href|background)="[^:,^>,^\"]*\"/i";

preg_match_all ( $search, $html, $a_matches );

//you can figure out the rest ! but thought the reg expression is useful as well
?>

But here is the catch, you may want to make sure curl connects to the server under the same session as the browser. So naturally you pass the session cookie through the curl system either by the cookie jar system, or through the query string in the path.

This is where you will get stuck. PHP will need write access to the same session file simultaneously!! causing serious hanging issues!

This is why you should close off your session before you make curl take a page snapshot!
michael (at) networkstuff co nz 20-Jan-2007 01:05
If PHP configure fails with cURL errors, try ommiting the --with-curl=path and just make this --with-curl.
Of course it will also be optimal to make sure that the cURL library directory is listed in /etc/ld.so.conf and then run 'ldconfig'.
By default this is /usr/local/lib.
jon at jonroig--- dot com 25-Aug-2006 06:53
For anyone who is having trouble getting some of the advanced functionality to work in whatever version of PHP you have, I wrote a little wrapper for the command line version of curl. The function below is for Windows (hence, the curl.exe), but it works the same way under Linux or whatever.

The curl man page enumerates a ton of options you can use...

<?php
function curlPageGrabber($destinationURL, $refererURL, $postData, $autoForward = false, $autoGrabCookies = true, $curlDebug = false)
  {
 
$curlString = "c:\curl\curl.exe -i -v -m 30 -L -b c:\curl\cookiejar.txt -c c:\curl\cookiejar.txt ";
 
$curlString .= " -A \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322;)\" ";
 
$curlString .= " -H \"Accept-Language: en-us\" ";
 
$curlString .= " -H \"Accept-Encoding: gzip, deflate\" ";
 
$curlString .= " -H \"Host: affiliate-program.amazon.com\" ";
 
$curlString .= " -H \"Accept: */*\" ";
 
$curlString .= " --compressed ";
 
//$curlString .= " --trace-ascii ";
 
 
if ($refererURL != '')
    {
   
$curlString .= "-e \"".$refererURL."\" ";
    }
  if (
$postData != '')
    {
   
$curlString.= " -d \"$postData\" ";
    }
 
$curlString .= $destinationURL;
  if (
$curlDebug == true)
    {
    echo
"<p>curlString: $curlString</p>";
    }
 
 
$temp = exec($curlString, $retval);

 
$htmlData = '';
  foreach (
$retval as $arrayLine)
    {
   
$htmlData .= $arrayLine."\r\n";
    }
  if (
$curlDebug == true)
    {
    echo
"<textarea cols=80 rows=20>$htmlData</textarea>";
    }
 
  return
$htmlData;
 
 
  }
// end function
?>
galvao at galvao.eti.br 06-Jul-2006 08:27
Note that on Win32 this documentation can get a little confusing.

In order to get this to work you need to:

1) Be sure that the folder where libeay32.dll and ssleay32.dll - tipically C:\\PHP - is present on the PATH variable.

2) Uncomment - remove the semi-colon - the line that says "extension=php_curl.dll" from php.ini

3) Restart the webserver (you should already know this one, but...)

It took me some time to realize this, since this page doesn't mention the need to uncomment that php.ini's line.
david at neocodesoftware dot com 30-May-2006 05:42
This may be obvious to everybody *except* me, but if you want to use curl to connect via ftp rather than http, then you just need to use "ftp://" in the url specification (I was looking for an use_ftp flag or something). 

Use the CURLOPT_USERPWD to login to the ftp site.
Sean Huber 05-May-2006 04:01
<?php
/*
Sean Huber CURL library

This library is a basic implementation of CURL capabilities.
It works in most modern versions of IE and FF.

==================================== USAGE ====================================
It exports the CURL object globally, so set a callback with setCallback($func).
(Use setCallback(array('class_name', 'func_name')) to set a callback as a func
that lies within a different class)
Then use one of the CURL request methods:

get($url);
post($url, $vars); vars is a urlencoded string in query string format.

Your callback function will then be called with 1 argument, the response text.
If a callback is not defined, your request will return the response text.
*/

class CURL {
    var
$callback = false;

function
setCallback($func_name) {
   
$this->callback = $func_name;
}

function
doRequest($method, $url, $vars) {
   
$ch = curl_init();
   
curl_setopt($ch, CURLOPT_URL, $url);
   
curl_setopt($ch, CURLOPT_HEADER, 1);
   
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
   
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
   
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    if (
$method == 'POST') {
       
curl_setopt($ch, CURLOPT_POST, 1);
       
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
   
$data = curl_exec($ch);
   
curl_close($ch);
    if (
$data) {
        if (
$this->callback)
        {
           
$callback = $this->callback;
           
$this->callback = false;
            return
call_user_func($callback, $data);
        } else {
            return
$data;
        }
    } else {
        return
curl_error($ch);
    }
}

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

function
post($url, $vars) {
    return
$this->doRequest('POST', $url, $vars);
}
}
?>
richardkmiller AT gmail 02-Mar-2006 04:21
Beware of any extra spaces in the URL.  A trailing space in the URL caused my script to fail with the message "empty reply from server".
stevehartken at hotmail dot com 21-Feb-2006 10:40
I had the following experience when harvesting urls with a get variable from a page using cUrl. HTML pages will output ampersands as &amp when the page is read by the curl function.

If you code a script to find all hyperlinks, it will use &amp instead of &, especially using a regular expression search.

It is hard to detect because when you output the url to the browser it renders the html. To fix, add a line to replace the &amp with &.

<?php
function processURL($url){
   
$url=str_replace('&amp;','&',$url);
   
$ch=curl_init();
   
curl_setopt($ch, CURLOPT_URL, $url);
   
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
   
$xml = curl_exec ($ch);
   
curl_close ($ch);
    echo
$xml;
}
?>
mikeb[at]xamo[dot]com 14-Oct-2004 01:11
A note of warning for PHP 5 users: if you try to fetch the CURLINFO_CONTENT_TYPE using curl_getinfo when there is a connect error, you will core dump PHP. I have informed the Curl team about this, so it will hopefully be fixed soon. Just make sure you check for an error before you look for this data.
alidrus at langkah dot com 14-Sep-2004 02:31
In recent versions of php, CURLOPT_MUTE has (probably) been deprecated. Any attempt of using curl_setopt() to set CURLOPT_MUTE will give you a warning like this:

PHP Notice:  Use of undefined constant CURLOPT_MUTE - assumed 'CURLOPT_MUTE' in ....

If you wish tu silence the curl output, use the following instead:

<?php
    curl_setopt
($ch, CURLOPT_RETURNTRANSFER, true);
?>

And then,

<?php
    $curl_output
=curl_exec($ch);
?>

The output of the curl operation will be stored as a string in $curl_output while the operation remains totally silent.
rich @ richud dot com 11-Jun-2004 07:12
If you have upgraded to using thread safe PHP (with apache 2 MPM=worker) note that
CURLOPT_COOKIEJAR / CURLOPT_COOKIEFILE both need an absolute path set for the cookie file location and no longer take a relative path.
(As before, also remember to have set correct permissions to allow a writeable cookie file/dir by apache)
[php 4.3.7/apache v2.0.49]
simon [at] vhostdirect [dot] co [dot] uk 03-Mar-2004 04:53
It took me quite some to to figure out how to get Curl (with SSL), OpenSSL and PHP to play nicely together.

After reinstalling MS-VC7 and compiling OpenSSL to finally realise this was'nt nesscary.

If your like me and like *Nix systems more than Windows then you'll most probly have similar problems.

I came across this, on a simple google with the right keywords.

http://www.tonyspencer.com/journal/00000037.htm

I read thru that and found my mistake.

Its just a small list of notes, I found them to be the best I've found on the subject and the most simplist.

Dont forget to add a simple line like this into your scripts to get them working on Win32.

<?php
if($WINDIR) curl_setopt($curl, CURLOPT_CAINFO, "c:\\windows\\ca-bundle.crt");
?>

Last note: ca-bundle.crt file is located in the Curl download. I stored mine in the windows directory and apache/php can access it fine.

All the best and I hope this helps.

Simon Lightfoot
vHost Direct Limited
hraefn at hraefn dot net 03-Feb-2004 01:15
You can request (and have deflated for you) compressed http (from mod_gzip or ob_gzhandler, for instance) by using the following:

<?php
curl_setopt
($ch,CURLOPT_ENCODING , "gzip");
?>

This seems to work fine with the latest php (4.3.4) curl (7.11.0) and zlib (1.1.4) under linux.  This is much more elegant than forcing the Accept-Encode header and using gzdeflate on an edited result.
bharris at spro dot net 25-Feb-2003 04:58
For Win2000: To get the 4.3.1 curl dll to work with https you now need to download the latest win32 curl library from http://curl.haxx.se and snag the ca-bundle.crt file from the lib directory.  Place this somewhere handy on your webserver.

Then in your PHP script, add the following setopt line to the rest of your curl_setopt commands:

<?php curl_setopt($ch, CURLOPT_CAFILE, 'C:\pathto\ca-bundle.crt'); ?>

This worked for me and allowed me to discontinue using the CURLOPT_SSL_VERIFYPEER set to zero hack.

 
show source | credits | sitemap | contact | advertising | mirror sites