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, 11 Apr 2008

view this page in

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setopt — Eine Option für einen cURL Transfer setzen

Beschreibung

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

Setzt eine Option für das angegeben cURL-Handle

Parameter-Liste

ch

Ein von curl_init() zurückgegebenes cURL-Handle.

option

Die zu setzende CURLOPT_XXX-Option

value

Der Wert für value

value sollte ein boolean für die folgenden Werte des Parameters option sein:

Option Wert für value Anmerkungen
CURLOPT_AUTOREFERER TRUE um automatisch den Referer: in Abfragen zu setzen, die einem Redirect per Location: folgen Verfügbar seit PHP 5.1.0.
CURLOPT_BINARYTRANSFER TRUE um die unbearbeiteten Daten zurüchzugeben wenn CURLOPT_RETURNTRANSFER gesetzt ist.
CURLOPT_COOKIESESSION TRUE um diesen Request als neue "Cookie Session" zu behandeln. Somit wird libcurl alle cookies die geladen werden sollen ignorieren, sofern es sich um "Session Cookies" einer vorherigen Session handelt. Standardmässig lädt und speichert libcurl alle cookies, unabhängig davon, ob es "Session Cookies" sind. Bei "Session Cookies" handelt es sich um Cookies ohne Ablaufdatum, die nur für die aktuelle Session gültig sind. Verfügbar seit PHP 5.1.0.
CURLOPT_CRLF TRUE um Unix-Zeilenumbrüche beim Transfer in CRLF-Zeilenumbrüche umzuwandeln.
CURLOPT_DNS_USE_GLOBAL_CACHE TRUE um den globalen DNS-Cache zu nutzen. Diese Option ist nicht thread-safe und standardmässig aktiviert.
CURLOPT_FAILONERROR TRUE um PHP anzuweisen, bei Fehlern (HTTP-Code ist größer oder gleich 400) ohne Fehlermeldung weiter zu arbeiten. Dieses Verhalten ist standardmässig aktiviert.
CURLOPT_FILETIME TRUE um zu versuchen, das Änderungsdatum des serverseitigen Dokuments zu ermitteln. Der Wert kann über die Funktion curl_getinfo() unter Verwendung des Parameters CURLINFO_FILETIME ermittelt werden.
CURLOPT_FOLLOWLOCATION TRUE um jedem "Location: "-Header zu folgen, den der Server als Teil der HTTP-Header zurückgibt. Die Verarbeitung erfolgt rekursiv, PHP wird jedem "Location: "-Header folgen, sofern nicht CURLOPT_MAXREDIRS gesetzt ist.
CURLOPT_FORBID_REUSE TRUE um die Verbindung nach der Verarbeitung explizit zu schliessen, so daß sie nicht wiederverwendet werden kann.
CURLOPT_FRESH_CONNECT TRUE um den expliziten Aufbau einer neuen Verbindung zu erzwingen, anstatt auf eine gecachte zurückzugreifen.
CURLOPT_FTP_USE_EPRT TRUE, um EPRT (und LPRT) für aktive FTP-Downloads zu nutzen. Auf FALSE setzen, um EPRT und LPRT zu deaktivieren und ausschliesslich PORT zu nutzen. Verfügbar seit PHP 5.0.0.
CURLOPT_FTP_USE_EPSV TRUE um vor dem Fallback auf PASV zunächst eine EPSV-Anweisung für einen FTP-Transfer auszuführen. Auf FALSE setzen, um EPSV zu deaktivieren.
CURLOPT_FTPAPPEND TRUE um Daten an die serverseitige Datei anzuhängen anstatt diese zu überschreiben.
CURLOPT_FTPASCII Ein Alias für CURLOPT_TRANSFERTEXT, das bevorzugt werden sollte.
CURLOPT_FTPLISTONLY TRUE um nur die Namen in einem FTP-Verzeichnis aufzulisten.
CURLOPT_HEADER TRUE um den Header in die Ausgabe aufzunehmen.
CURLOPT_HTTPGET TRUE um die HTTP-Request-Methode auf GET zu setzen. Da dies die Standard-Methode ist sollte dies nur nach einem Wechsel der Request-Methode notwendig sein.
CURLOPT_HTTPPROXYTUNNEL TRUE um einen vorhandenen Proxy-Tunnel zu nutzen
CURLOPT_MUTE TRUE um jegliche Ausgabe der cURL-Funktionen zu unterbinden
CURLOPT_NETRC TRUE um die lokale Datei ~/.netrc nach Benutzername/Passwort für die Authorisierung des Zugriffs zu durchsuchen.
CURLOPT_NOBODY TRUE um den Body nicht in die Ausgabe aufzunehmen.
CURLOPT_NOPROGRESS

TRUE um die Fortschrittsanzeige für den Transfer auszublenden.

Hinweis: PHP setzt die Option automatisch auf TRUE. Dies sollte ausschließlich für die Fehlersuche geändert werden.

CURLOPT_NOSIGNAL TRUE um jegliche cURL-Funktion zu ignorieren, die ein Signal an den PHP-Prozess sendet. In multi-threaded SAPIs ist diese Option standardmässig aktiviert, so daß Timeouts weiterhin abgefangen werden können. Hinzugefügt in cURL 7.10 und PHP 5.0.0.
CURLOPT_POST TRUE um einen HTTP-POST-Request abzusetzen. Dabei handelt es sich um das übliche application/x-www-form-urlencoded, wie es im Allgemeinen von HTML-Formularen erzeugt wird.
CURLOPT_PUT TRUE um ein HTTP-PUT für eine Datei abzusetzen. Die fragliche Datei muss dabei über die Konstanten CURLOPT_INFILE und CURLOPT_INFILESIZE gesetzt werden.
CURLOPT_RETURNTRANSFER TRUE um den Tranfer als String zurückzuliefern, anstatt ihn direkt auszugeben.
CURLOPT_SSL_VERIFYPEER FALSE um die Überprüfung des Peerzertifikats seitens cURL zu unterdrücken. Alternative Zertifikate zur Überprüfung können mit der Option CURLOPT_CAINFO angegeben werden oder ein Zertifikat-Verzeichniss kann mit CURLOPT_CAPATH ausgewiesen werden. Ebenso muß CURLOPT_SSL_VERIFYHOST ggf. auf TRUE oder FALSE gesetzt werden, sofern CURLOPT_SSL_VERIFYPEER deaktiviert ist. TRUE als Standard seit cURL 7.10.
CURLOPT_TRANSFERTEXT TRUE um FTP-Transfers im ASCII-Modus durchzuführen. Für LDAP werden Daten in Klartext statt HTML übertragen. Unter Windows wird STDOUT nicht in den binären Modus gesetzt.
CURLOPT_UNRESTRICTED_AUTH TRUE um beim Folgen eines Location: -Headers (siehe CURLOPT_FOLLOWLOCATION) weiterhin Benutzername und Passwort zu senden, sogar nach einem Wechsel des Hostnamens. Hinzugefügt in PHP 5.0.0.
CURLOPT_UPLOAD TRUE um einen Upload vorzubereiten
CURLOPT_VERBOSE TRUE um ausführliche Informationen auszugeben, entweder nach STDERR oder in die mittels der Option CURLOPT_STDERR gewählte Datei.

Für die folgenden option -Parameter sollte value ein Integer sein:

Option Wert für value Anmerkungen
CURLOPT_BUFFERSIZE Die für jede Leseoperation zulässige Buffergröße. Es ist nicht garantiert, daß diese Einstellung genutzt wird. Hinzugefügt in cURL 7.10 and PHP 5.0.0.
CURLOPT_CLOSEPOLICY Sollte entweder CURLCLOSEPOLICY_LEAST_RECENTLY_USED oder CURLCLOSEPOLICY_OLDEST . Zwar existieren drei weitere CURLCLOSEPOLICY_-Konstanten, diese werden allerdings bisher nicht von cURL unterstützt.
CURLOPT_CONNECTTIMEOUT Die Anzahl Sekunden, die der Verbindungsaufbau maximal dauern darf; 0 hebt die Begrenzung auf.
CURLOPT_DNS_CACHE_TIMEOUT Die Dauer in Sekunden, die ein DNS-Eintrag im Speicher gehalten wird. Der Standard sind 120 Sekunden (2 Minuten).
CURLOPT_FTPSSLAUTH Die FTP-Authentisierungsmethode (wenn aktiviert): CURLFTPAUTH_SSL (versuche zunächst SSL), CURLFTPAUTH_TLS (versuche zunächst TLS), oder CURLFTPAUTH_DEFAULT (lass cURL entscheiden). Hinzugefügt in cURL 7.12.2 und PHP 5.1.0.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (Standard, lässt cURL entscheiden, welche Version genutzt werden soll), CURL_HTTP_VERSION_1_0 (nutze HTTP/1.0), or CURL_HTTP_VERSION_1_1 (nutze HTTP/1.1).
CURLOPT_HTTPAUTH

Die zu nutzende HTTP-Authentisierungsmethode; zur Verfügung stehen: CURLAUTH_BASIC , CURLAUTH_DIGEST , CURLAUTH_GSSNEGOTIATE , CURLAUTH_NTLM , CURLAUTH_ANY , und CURLAUTH_ANYSAFE .

Um mehrere Methoden zu kombinieren kann der Bit-|(oder)-Operator verwendet werden; in diesem Fall wird cURL in Abstimmung mit dem Server die günstigste Methode auswählen.

CURLAUTH_ANY ist ein Alias für CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

CURLAUTH_ANYSAFE ist ein Alias für CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM.

Hinzugefügt in PHP 5.0.0.
CURLOPT_INFILESIZE Die erwartete Dateigröße der hochzuladenden Datei in Bytes
CURLOPT_LOW_SPEED_LIMIT Die Transfergeschwindigkeit in Bytes pro Sekunde, die bei Unterschreitung in Kombination mit der Überschreitung von CURLOPT_LOW_SPEED_TIME Sekunden bewirkt, dass der Transfer aufgrund der zu niedrigen Transferrate abgebrochen wird.
CURLOPT_LOW_SPEED_TIME Die Zeit in Sekunden, in der die Transferrate unter CURLOPT_LOW_SPEED_LIMIT gedultet wird. Nach dieser Zeit wird die Transferrate als zu langsam angesehen und der Transfer wird beendet.
CURLOPT_MAXCONNECTS Die maximal erlaubte Anzahl persistenter Verbindungen; bei Erreichen des Limits wird mittels CURLOPT_CLOSEPOLICY entschieden, welche Verbindung geschlossen wird.
CURLOPT_MAXREDIRS Die maximal erlaubte Anzahl von HTTP-Weiterleitungen. Verwenden Sie diese Option zusammen mit CURLOPT_FOLLOWLOCATION.
CURLOPT_PORT Erlaubt das Setzen eines alternativen Ports für die Verbindung.
CURLOPT_PROXYAUTH Die HTTP-Authentisierungsmethode(n) für die Proxy-Verbindung. Nutzt die gleiche Bitmaske wie in CURLOPT_HTTPAUTH beschrieben. Nur CURLAUTH_BASIC und CURLAUTH_NTLM sind momentan für Proxy-Verbindungen zulässig. Hinzugefügt in cURL 7.10.7 und PHP 5.1.0.
CURLOPT_PROXYPORT Der Port, auf den die Proxy-Verbindung erfolgen soll; kann auch mittels CURLOPT_PROXY gesetzt werden. Hinzugefügt in PHP 5.0.0.
CURLOPT_PROXYTYPE Entweder CURLPROXY_HTTP (Standard) oder CURLPROXY_SOCKS5 . Hinzugefügt in cURL 7.10 und PHP 5.0.0.
CURLOPT_RESUME_FROM Die Position in Bytes ab der ein Transfer fortgesetzt werden soll.
CURLOPT_SSL_VERIFYHOST 1 um auf die Existenz des Namens im Zertifikat zu prüfen, 2 stellt sicher, daß eine Übereinstimmung mit dem angegebenen Hostnamen vorliegt.
CURLOPT_SSLVERSION Ein Wert von 2 oder 3 wählt die entsprechende SSL-Version. Standardmässig wird PHP versuchen, die entsprechende Einstellung zu ermitteln, aber in einigen Fällen mag das manuelle Setzen dieser Option nötig sein.
CURLOPT_TIMECONDITION Dieser Wert gibt an, wie CURLOPT_TIMEVALUE behandelt werden soll. Mögliche Werte sind CURL_TIMECOND_IFMODSINCE (Standard) und CURL_TIMECOND_ISUNMODSINCE . Im ersten Fall wird geprüft, ob die Seite seit CURLOPT_TIMEVALUE geändert wurde; andernfalls wird ein "304 Not Modified"-Header zurückgegeben (vorausgesetzt CURLOPT_HEADER ist TRUE). CURL_TIMECOND_ISUNMODSINCE bewirkt das gegenteilige Verhalten. Hinzugefügt in PHP 5.1.0.
CURLOPT_TIMEOUT Die maximale Ausführungszeit in Sekunden für cURL-Funktionen.
CURLOPT_TIMEVALUE Zeit in Sekunden seit dem 1. Januar 1970. Dieser Wert wird von CURLOPT_TIMECONDITION genutzt.

Für die folgenden option -Parameter sollte value ein String sein:

Option Wert für value Anmerkungen
CURLOPT_CAINFO Der Name einer Datei, die ein oder mehrere Zerifikate enthält, gegen die der Peer geprüft wird. Macht nur Sinn in Verbindung mit CURLOPT_SSL_VERIFYPEER.
CURLOPT_CAPATH Ein Verzeichnis, das mehrere CA-Zertifikate enthält. Diese Option sollte In Kombination mit CURLOPT_SSL_VERIFYPEER genutzt werden.
CURLOPT_COOKIE Der Inhalt des im HTTP-Request zu setzenden "Set-Cookie: "-Headers
CURLOPT_COOKIEFILE Der Name einer Datei, die Cookiedaten enthält. Diese Datei kann im Netscape-Format sein oder HTTP-geformte Header enthalten.
CURLOPT_COOKIEJAR Der Name einer Datei in der alle internen Cookies beim Schliessen der Verbindung gespeichert werden.
CURLOPT_CUSTOMREQUEST

Eine benutzerdefinierte Request-Methode, die anstelle von GET oder HEAD für den HTTP-Request benutzt werden soll. Dies ist nützlich bei DELETE oder anderen unüblichen Requests. Zulässige Werte sind GET, POST, CONNECT etc. Vollständige HTTP-Requests wie GET /index.html HTTP/1.0\r\n\r\n sind unzulässig!

Hinweis: Führen Sie diese Anfragen nicht durch ohne sicherzugehen, daß Ihr Server die betreffenden Kommandos unterstützt.

CURLOPT_EGDSOCKET Analog CURLOPT_RANDOM_FILE, hier wird der Dateiname eines Entropy Gathering Daemon Socket erwartet.
CURLOPT_ENCODING Der Inhalt des "Accept-Encoding: "-Headers. Damit wird das Dekodieren der Serverantwort aktiviert. Unterstützte Kodierungen sind identity, deflate und gzip. Wird ein leerer String "" gesetzt wird ein Header mit allen unterstützten Kodierungen gesetzt. Hinzugefügt in cURL 7.10.
CURLOPT_FTPPORT Ein String, der genutzt wird, um die IP-Adresse zu erlangen, die von der FTP-POST-Anweisung genutzt wird. Die POST-Anweisung teilt dem entfernten Server mit, zu der angegebenen IP-Adresse zu verbinden. Der String kann eine einfache IP-Addresse, ein Hostname, der Name eines Netzwerkinterfaces (unter Unix) oder nur '-' sein, um die vordefinierte IP-Addresse (des Systems) zu nutzen.
CURLOPT_INTERFACE Der Name des zu nutzenden Netzwerkinterfaces für ausgehende Daten. Statt des Namens des Interfaces kann auch eine IP-Adresse oder ein Hostname übergeben werden.
CURLOPT_KRB4LEVEL Die KRB4 (Kerberos 4) Sicherheitsstufe. Folgende Werte (von niedriger zu höherer Stufe) sind gültig: clear, safe, confidential, private. Sollte der String keinen dieser Werte enthalten dann wird die höchste Stufe genutzt, d.h private. Sollte diese Option mit dem Wert NULL besetzt werden, wird KRB4 Security deaktiviert. Bislang wird KRB4 nur unter Verwendung des FTP unterstützt.
CURLOPT_POSTFIELDS Die in einem HTTP-POST-Request zu nutzenden Daten.
CURLOPT_PROXY Der HTTP-Proxy, durch den Requests getunnelt werden sollen.
CURLOPT_PROXYUSERPWD Benutzername und Passwort in der Form "[benutzername]:[passwort]" für die Proxy-Verbindung.
CURLOPT_RANDOM_FILE Ein Dateiname der zur Initialisierung des Zufallsgenerators für SSL benutzt wird.
CURLOPT_RANGE Bereiche an Daten, die empfangen werden sollen. Das Format sollte "X-Y" sein, wobei X oder Y optional sind. HTTP-Transfers unterstützen auch mehrere Komma-getrennte Intervalle im Format "X-Y,N-M".
CURLOPT_REFERER Der Inhalt des "Referer: "-Headers
CURLOPT_SSL_CIPHER_LIST Eine Liste der für SSL zulässigen Chiffren. RC4-SHA und TLSv1 sind zulässig.
CURLOPT_SSLCERT Der Name einer Datei die ein Zertifikat im PEM-Format enthält.
CURLOPT_SSLCERTPASSWD Das Passwort für das CURLOPT_SSLCERT-Zertifikat.
CURLOPT_SSLCERTTYPE Das Format des Zertifikats. Unterstützt werden PEM (Standard), DER und ENG. Hinzugefügt in cURL 7.9.3 und PHP 5.0.0.
CURLOPT_SSLENGINE Der Bezeichner für die Crypto Engine des privaten SSL-Schlüssels, der in CURLOPT_SSLKEY definiert ist.
CURLOPT_SSLENGINE_DEFAULT Der Bezeichner für die Crypto-Engine für asymmetrische kryptographische Operationen.
CURLOPT_SSLKEY Der Name einer Datei, die einen privaten SSL-Schlüssel enthält.
CURLOPT_SSLKEYPASSWD

Das geheime Passwort das für den in CURLOPT_SSLKEY definierten privaten SSL-Schlüssel.

Hinweis: Da diese Option sensible Daten enthält sollte das PHP-Script in einer sicheren Umgebung liegen.

CURLOPT_SSLKEYTYPE Der Typ des in CURLOPT_SSLKEY definierten privaten SSL-Schlüssels. Unterstützte Schlüssel-Typen sind PEM (Standard), DER und ENG.
CURLOPT_URL Der abzurufende URL; kann auch beim initialisieren der Session mittels curl_init() gesetzt werden.
CURLOPT_USERAGENT Der Wert des "User-Agent: "-Headers für den HTTP-Request
CURLOPT_USERPWD Benutzername und Passwort im Format "[benutzername]:[passwort]"

Für die folgenden option -Parameter sollte value ein Array sein:

Option Wert für value Anmerkungen
CURLOPT_HTTP200ALIASES Ein Array von HTTP-200-Status die als gültige Antowrten und nicht als Fehler behandelt werden. Hinzugefügt in cURL 7.10.3 und PHP 5.0.0.
CURLOPT_HTTPHEADER Ein Array von HTTP-Headern.
CURLOPT_POSTQUOTE Ein Array von FTP-Kommandos, die nach dem FTP-Request auf dem Server ausgeführt werden sollen.
CURLOPT_QUOTE Ein Array von FTP-Kommandos, die vor dem FTP-Request auf dem Server ausgeführt werden sollen.

Für die folgenden option -Parameter sollte value eine Stream-Resource sein, so wie sie z.B. mittels fopen() erstellt werden kann

Option Wert für value Anmerkungen
CURLOPT_FILE Die Datei, in die der Transfer geschrieben werden soll. Standard ist STDOUT (der Browser).
CURLOPT_INFILE Die Datei die zum Upload gelesen werden soll.
CURLOPT_STDERR Eine Datei, in die Fehler ausgegeben werden, alternativ zu STDERR.
CURLOPT_WRITEHEADER In diese Datei werden die Header eines Transfers geschrieben.

Für die folgenden option -Parameter sollte value ein Callback sein, der eine valide Callback-Funktion repräsentiert.

Option Wert für value Anmerkungen
CURLOPT_HEADERFUNCTION Eine Callback-Funktion, die zwei Parameter erwartet. Der erste ist die cURL-Resource, der zweite ist ein String mit den zu schreibenden Headern. Bei Nutzung dieser Callback-Funktion liegt die Verantwortung für das Schreiben der Header bei Ihnen. Die Funktion sollte die Anzahl der geschriebenen Bytes zurückgeben.
CURLOPT_PASSWDFUNCTION Eine Callback-Funktion, die drei Parameter erwartet. Der erste ist die cURL-Resource, der zweite ein String der ein Passwort-Prompt enthält, der dritte Parameter enthält die maximal zulässige Länge des Passworts. Die Funktion sollte das Passwort als String zurückgeben.
CURLOPT_READFUNCTION Eine Callback-Funktion, die zwei Parameter erwartet. Der erste ist die cURL-Resource, der zweite ist ein String mit den zu lesenden Daten. Bei Nutzung dieser Callback-Funktion liegt die Verantwortung für das Lesen der Daten bei Ihnen. Die Funktion sollte die Anzahl der gelesenen Bytes zurückgeben, 0 um EOF zu signalisieren.
CURLOPT_WRITEFUNCTION Eine Callback-Funktion, die zwei Parameter erwartet. Der erste ist die cURL-Resource, der zweite ist ein String mit den zu schreibenden Daten. Bei Nutzung dieser Callback-Funktion liegt die Verantwortung für das Schreiben der Daten bei Ihnen. Die Funktion muss die genaue Anzahl geschriebener Bytes zurückgeben!

Rückgabewerte

Gibt bei Erfolg TRUE zurück, im Fehlerfall FALSE.

Beispiele

Beispiel #1 Initialisierung einer neuen cURL-Session und das Abrufen einer Webseite

<?php
 
// erzeuge einen neuen cURL-Handle
 
$ch curl_init();
  
 
// setze die URL und andere Optionen
 
curl_setopt($chCURLOPT_URL"http://www.example.com/");
 
curl_setopt($chCURLOPT_HEADER0);
  
 
// führe die Aktion aus und gebe die Daten an den Browser weiter
 
curl_exec($ch);
  
 
// schließe den cURL-Handle und gebe die Systemresourcen frei
 
curl_close($ch);
?>

Siehe auch



curl_version> <curl_setopt_array
Last updated: Fri, 11 Apr 2008
 
add a note add a note User Contributed Notes
curl_setopt
f00f
13-May-2008 12: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
06-May-2008 06: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 02: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
09-Apr-2008 05: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 09: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
15-Feb-2008 10: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
28-Dec-2007 09: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 12: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 02: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 09: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
05-Jul-2007 03: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 11: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 02: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 01: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
11-May-2007 09: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 09: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
13-Mar-2007 05: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 06: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 06: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 11: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
21-Nov-2006 08: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 11: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 04: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 10: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
13-Jul-2006 03: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 11: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 07: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 02: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 02: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 02: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;
}

curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );

?>
phpnet at wafflehouse dot de
23-Oct-2005 06:34
Resetting CURLOPT_FILE to STDOUT won't work by calling curl_setopt() with the STDOUT constant or a php://output stream handle (at least I get error messages when trying the code from phpnet at andywaite dot com). Instead, one can simply reset it as a side effect of CURLOPT_RETURNTRANSFER. Just say

        curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,0);

and following calls to curl_exec() will output to STDOUT again.
webmaster () stauceni.com
20-Oct-2005 01:42
A little mistake, that took a half-day to fix it:
When specifing CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR options, don't forget to "chmod 777" that directory where cookie-file must be created.
mcknight at chek dot com
22-Aug-2005 08:10
when specifing the file for either CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR you may need to use the full file path instead of just the relative path.
phpnet at andywaite dot com
07-Jun-2005 02:08
After setting CURLOPT_FILE, you may want want to revert back to the normal behaviour of displaying the results. This can be achieved using:

$fp = fopen ("php://output", "w") or die("Unable to open stdout for writing.\n");
curl_setopt($ch, CURLOPT_FILE, $fp);
ikendra at yken dot nospam dot org
09-May-2005 09:26
Using cURL, I needed to call a third-party script which was returning binary data as attachment to pass on retrieved data again as attachment.

Problem was that the third-party script occassionally returned HTTP errors and I wanted to avoid passing on zero-length attachment in such case.

Combination of using CURLOPT_FAILONERROR and CURLOPT_HEADERFUNCTION callback helped to process the third-party script HTTP errors neatly:

<?
function curlHeaderCallback($resURL, $strHeader) {
    if (preg_match('/^HTTP/i', $strHeader)) {
        header($strHeader);
        header('Content-Disposition: attachment; filename="file-name.zip"');
    }
    return strlen($strHeader);
}

$strURL = 'http://www.somesite.com/script-whichs-dumps-binary-attachment.php';

$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $strURL);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);

curl_exec ($resURL);

$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);

if ($intReturnCode != 200) {
    print 'was error: ' . $intReturnCode;
}
?>
ale at desarrolloweburuguay dot com
05-May-2005 05:00
I don't know if in PHP 5+ this problem is solved, but, when I send via POST using CURLOPT_POSTFIELDS some times it doesnt work an associative array as parameter... and, if I need to send non-ascii characters (like á,é,ñ,ü,etc..) this problem appears too.
The solution is to encode in a unique string all the post key=>values

Possibly this code doesnt work:

<?php

    $post_data
= array();
   
$post_data['var1'] = "Diseño web uruguay";
   
$post_data['var2'] = "Other string";
   
$url = "http://www.someurl.com/";

   
$ch = curl_init();
   
curl_setopt($ch, CURLOPT_POST, 1);
   
curl_setopt($ch, CURLOPT_HEADER, 0);
   
curl_setopt($ch, CURLOPT_URL, );   
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
   
$result = curl_exec($ch);

?>

But this works:
<?php

    $post_data
= array();
   
$post_data['var1'] = "Diseño web uruguay";
   
$post_data['var2'] = "Other string";
   
$url = "http://www.someurl.com/";

   
$o="";
    foreach (
$post_data as $k=>$v)
    {
       
$o.= "$k=".utf8_encode($v)."&";
    }
   
$post_data=substr($o,0,-1);
   
   
$ch = curl_init();
   
curl_setopt($ch, CURLOPT_POST, 1);
   
curl_setopt($ch, CURLOPT_HEADER, 0);
   
curl_setopt($ch, CURLOPT_URL, );   
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
   
$result = curl_exec($ch);

?>

Rgds.
Alejandro Moreno.-
azcappy at azcappy dot com
23-Mar-2005 10:03
AZAds is a traffic exchange that we wrote. We wanted to come up with a way to check the UP or DOWN status of a submitted URL. Here is the solution we came up with. Can also be used for a site monitoring service.

<?
$uServer="$url";
@$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$uServer");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
@curl_exec($ch);
$errnum=curl_errno($ch);
@curl_close($ch);
if($errnum != "0") {
     print "Remote Site Status: DOWN";
} else {
     print "Remote Site Status: UP";
}
?>

Simply feed the URL to be tested into $url. The code will check the site and return the error code if there is one and display to appropriate message.

Hope this is useful.

Keith
www.azads.net
mcknight at chek dot com
21-Feb-2005 09:38
Another way to automate a login process and store multiple cookies for additional transfers.

(The easiest way is probably just to use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE and save them to a file. But if you need to change those cookie values or add/delete them then you can use the code below to set them.)

Continuing with Paul Ebermann's parsing function.
 function parse_response($this_response)
    {
    // Split response into header and body sections
    list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2);
    $response_header_lines = explode("\r\n", $response_headers);

    // First line of headers is the HTTP response code
    $http_response_line = array_shift($response_header_lines);
    if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; }

    // put the rest of the headers in an array
    $response_header_array = array();
    foreach($response_header_lines as $header_line)
        {
        list($header,$value) = explode(': ', $header_line, 2);
        $response_header_array[$header] .= $value."\n";
        }

    return array("code" => $response_code, "header" => $response_header_array, "body" => $response_body);
    }

// Do transfer, and make sure to include header in response
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "[login process]");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);

// Parse the response message
$response = parse_response($response);

// Create the basic header
$this_header = array(
    "MIME-Version: 1.0",
    "Content-type: text/html; charset=iso-8859-1",
    "Content-transfer-encoding: text"
);

// Add each cookie that has been returned in the response
// If cookies need to be added/deleted or value changed, then add code here
$cookies = explode("\n", $response["header"]["Set-Cookie"]);
foreach($cookies as $this_cookie) { array_push($this_header, "Cookie: ".$this_cookie); }

// Next set of transfers
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "[new transfer]");
curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
Aaron Stephanic
10-Nov-2004 09:51