PHP Doku:: Eine Option für einen cURL Transfer setzen - function.curl-setopt.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzSonstige DiensteCURLcURL Funktionencurl_setopt

Ein Service von Reinhard Neidl - Webprogrammierung.

cURL Funktionen

<<curl_setopt_array

curl_version>>

curl_setopt

(PHP 4 >= 4.0.2, PHP 5)

curl_setoptEine 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
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.
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 schließen, 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 ausschließlich PORT zu nutzen.
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.
CURLINFO_HEADER_OUT TRUE um den Request-String des Handles zu verfolgen. Verfügbar seit PHP 5.1.3. DasPrefix CURLINFO_ ist beabsichtigt.
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.
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_CONNECTTIMEOUT_MS Die Anzahl Millisekunden, die der Verbindungsaufbau maximal dauern darf; 0 hebt die Begrenzung auf. Added in cURL 7.16.2. Available since PHP 5.2.3.
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.

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_PROTOCOLS

Eine Bitmaske von CURLPROTO_*-Werten. Mit dieser Einstellung lassen sich die Protokolle einschränken die libcurl für diesen Transfer nutzen darf. Damit wird es möglich ein libcurl mit einer Vielzahl an Protokollen zu benutzen, gleichzeitig aber lassen sich die für einen bestimmten Transfer zulässigen Protokolle beschränken. Standardmässig akzeptiert libcurl alle unterstützten Protokolle. Siehe auch CURLOPT_REDIR_PROTOCOLS.

Zulässige Optionen: CURLPROTO_HTTP, CURLPROTO_HTTPS, CURLPROTO_FTP, CURLPROTO_FTPS, CURLPROTO_SCP, CURLPROTO_SFTP, CURLPROTO_TELNET, CURLPROTO_LDAP, CURLPROTO_LDAPS, CURLPROTO_DICT, CURLPROTO_FILE, CURLPROTO_TFTP, CURLPROTO_ALL

Hinzugefügt in cURL 7.19.4.
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.
CURLOPT_PROXYTYPE Entweder CURLPROXY_HTTP (Standard) oder CURLPROXY_SOCKS5. Hinzugefügt in cURL 7.10.
CURLOPT_REDIR_PROTOCOLS Eine Bitmaske von CURLPROTO_*-Werten. Mit dieser Einstellung lassen sich die Protokolle einschränken die libcurl für diesen Transfer nutzen darf, wenn eine Weiterleitung stattfindet (setzt voraus daß CURLOPT_FOLLOWLOCATION erlaubt ist). Damit wird es möglich ein libcurl mit einer Vielzahl an Protokollen zu benutzen, gleichzeitig aber lassen sich die für eine Weiterleitung zulässigen Protokolle beschränken. Standardmässig akzeptiert libcurl alle unterstützten Protokolle außer FILE und SCP. Siehe auch CURLOPT_PROTOCOLS für weitere Informationen zu den Protokoll-Konstanten. Added in cURL 7.19.4.
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.
CURLOPT_TIMEOUT Die maximale Ausführungszeit in Sekunden für cURL-Funktionen.
CURLOPT_TIMEOUT_MS Die maximale Ausführungszeit in Millisekunden für cURL-Funktionen. Added in cURL 7.16.2. Available since PHP 5.2.3.
CURLOPT_TIMEVALUE Zeit in Sekunden seit dem 1. Januar 1970. Dieser Wert wird von CURLOPT_TIMECONDITION genutzt. Als Standard wird CURL_TIMECOND_IFMODSINCE 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 Beachten Sie daß mehrere Cookies durch ein Semikolon gefolgt von einem Leerzeichen getrennt werden (z.B. "fruit=apple; colour=red")
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 Schließen des Handles gespeichert werden, z.B. nach einem Aufruf von curl_close.
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. Um eine Datei zu posten stellen Sie dem Dateinamen @ voran; bitte geben Sie den vollen Pfad zur Datei an. Als Wert kann entweder ein URL-kodierter String übergeben werden wie z.B. 'para1=val1&para2=val2&...' oder ein Array, wobei die Feldnamen als Schlüssel und die Felddaten als Wert verwendet werden. Wird ein Array für value dann wird der Content-Type-Header auf multipart/form-data gesetzt.
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.
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.
CURLOPT_HTTPHEADER Ein Array von HTTP-Headern, im Format array('Content-type: text/plain', 'Content-length: 100')
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
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
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_PROGRESSFUNCTION Eine Callback-Funktion, die drei Parameter erwartet. Der erste ist die cURL-Resource, der zweite ist eine Datei-Resource und der dritte ist die Länge; liefert eineb String mit den Werten zurück.
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 Speichern der Daten bei Ihnen. Die Funktion muss die genaue Anzahl geschriebener Bytes zurückgeben!

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Changelog

Version Beschreibung
5.2.10 Es wurden CURLOPT_PROTOCOLS und CURLOPT_REDIR_PROTOCOLS eingeführt.
5.1.0 Es wurden CURLOPT_AUTOREFERER, CURLOPT_BINARYTRANSFER, CURLOPT_FTPSSLAUTH, CURLOPT_PROXYAUTH und CURLOPT_TIMECONDITION eingeführt.
5.0.0 Es wurden CURLOPT_FTP_USE_EPRT, CURLOPT_NOSIGNAL, CURLOPT_UNRESTRICTED_AUTH, CURLOPT_BUFFERSIZE, CURLOPT_HTTPAUTH, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_SSLCERTTYPE und CURLOPT_HTTP200ALIASES eingeführt.

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_HEADERfalse);

// 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);
?>

Beispiel #2 Datei-Upload

<?php

/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/

$ch curl_init();

$data = array('name' => 'Foo''file' => '@/home/user/test.png');

curl_setopt($chCURLOPT_URL'http://localhost/upload.php');
curl_setopt($chCURLOPT_POST1);
curl_setopt($chCURLOPT_POSTFIELDS$data);

curl_exec($ch);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [name] => Foo
)
Array
(
    [file] => Array
        (
            [name] => test.png
            [type] => image/png
            [tmp_name] => /tmp/phpcpjNeQ
            [error] => 0
            [size] => 279
        )

)

Anmerkungen

Hinweis:

Ein für CURLOPT_POST übergebenes Array wird als multipart/form-data, ein URL-kodierter String als application/x-www-form-urlencoded kodiert.

Siehe auch


108 BenutzerBeiträge:
- Beiträge aktualisieren...
john dot david dot steele at gmail dot com
3.12.2010 22:03
A note on the way Curl posts files...

<?php
  curl_setopt
($ch, CURLOPT_POSTFIELDS, array('file' => '@/path/to/file.ext');
?>

will post the FULL PATH of the file in the filename field:

Content-Disposition: form-data; name="file"; filename="/path/to/file.ext"

Whereas typical browser behavior only sends the filename:

Content-Disposition: form-data; name="file"; filename="file.ext"

Workaround:
<?php
  curl_setopt
($ch, CURLOPT_POSTFIELDS, array('file' => '@file.ext');
 
$cwd = getcwd();
 
chdir('/path/to/');
 
$receivedData = curl_exec($ch);
 
chdir($cwd);
?>
scy-phpmanual at scytale dot name
29.11.2010 13:01
In order to reset CURLOPT_HTTPHEADER, set it to array(). The cURL C API says you should set it to NULL, but that doesn’t work in the PHP wrapper.
prohfesor at gmail dot com
2.11.2010 10:30
This function helps to parse netscape cookie file, generated by cURL into cookie array:

<?php
 
function _curl_parse_cookiefile($file) {
   
$aCookies = array();
   
$aLines = file($file);
    foreach(
$aLines as $line){
      if(
'#'==$line{0})
        continue;
     
$arr = explode("\t", $line);
      if(isset(
$arr[5]) && isset($arr[6]))
       
$aCookies[$arr[5]] = $arr[6];
    }
   
    return
$aCookies;
  }
?>
kavih7 at yahoo dot com
24.09.2010 5:59
When POSTing with cURL, my POSTs were magically being converted to GETs and I debugged it until finding the issue. I was setting the CURLOPT_MUTE option. Not sure why this conflicts, since the documentation doesn't specify as such. Anyways, if your $_POST is empty, make sure you aren't setting CURLOPT_MUTE.

Cheers!
curlysue
19.08.2010 11:34
If you've got problems with connecting througth a proxy using php/apache/xampp. So if you get no result string from the exec function, try enabling the following options in apache.

...\xampp\apache\conf
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

cURL seems to neet this modules.
daniel at blacklotus dot no
15.08.2010 14:33
Sime sites may protect themselves from remote logins by checking which site you came from.

Then you might want to use CURLOPT_REFERER.

<?php

// $url = page to POST data
// $ref_url = tell the server which page you came from (spoofing)
// $login = true will make a clean cookie-file.
// $proxy = proxy data
// $proxystatus = do you use a proxy ? true/false

function
curl_grab_page($url,$ref_url,$data,$login,$proxy,$proxystatus){
    if(
$login == 'true') {
       
$fp = fopen("cookie.txt", "w");
       
fclose($fp);
    }
   
$ch = curl_init();
   
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookie.txt");
   
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookie.txt");
   
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
   
curl_setopt($ch, CURLOPT_TIMEOUT, 40);
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    if (
$proxystatus == 'true') {
       
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, TRUE);
       
curl_setopt($ch, CURLOPT_PROXY, $proxy);
    }
   
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
   
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

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

   
curl_setopt($ch, CURLOPT_HEADER, TRUE);
   
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
   
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
   
curl_setopt($ch, CURLOPT_POST, TRUE);
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
   
ob_start();
    return
curl_exec ($ch); // execute the curl command
   
ob_end_clean();
   
curl_close ($ch);
    unset(
$ch);
}

echo
curl_grab_page("https://www.example.net/login.php", "https://www.example.net/", "username=foo&password=bar", "true""null", "false");

?>
sam at def dot reyssi dot net
28.07.2010 12:43
Be careful when setting the CURLOPT_POSTFIELDS setting using an array. The array used to set the POST fields must only contain scalar values. Multidimentional arrays or objects lacking a __toString implementation will cause Curl to error.

If there is a need to send non-scalar values using a POST request, consider serializing them before transmission.

<?php
$ch
= curl_init('http://host.example.com');

// Data to post
$multiDimensional = array(
  
'name' = 'foo',
  
'data' = array(1,2,3,4),
  
'value' = 'bar'
);

// Will error
curl_setopt($ch, CURLOPT_POSTFIELDS, $multiDimensional);

// Data to post
$postData = array(
 
'name' = 'foo',
 
'data' = serialize(array(1,2,3,4)),
 
'value' = 'bar'
);

// Will not error
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
?>
joeterranova at gmail dot com
26.07.2010 21:57
It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.

So do this:

<?php
curl_setopt
($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $fp);
?>

not this:

<?php
curl_setopt
($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
?>
patryk at do dot not dot spam dot com
5.07.2010 14:33
CURLOPT_HTTPPROXYTUNNEL means curl will use CONNECT method of the HTTP protocol to make a tunnel through a proxy, which is most likely not the one you want to do.
JScott jscott401 at gmail dot com
18.06.2010 16:29
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.

When you write a callback function and use it with curlopt_writefunction it will be called MULTIPLE times. Your function MUST return the ammount of data written to it each time. It is very picky about this. Here is a snippet from my code that may help you

<?php
curl_setopt
($this->curl_handle, CURLOPT_WRITEFUNCTION, array($this, "receiveResponse"));

// later on in the class I wrote my receive Response method

private function receiveResponse($curlHandle,$xmldata)
                {
                       
$this->responseString = $xmldata;
                       
$this->responseXML .=  $this->responseString;
                       
$this->length = strlen($xmldata);
                       
$this->size += $this->length;
                        return
$this->length;

                }
?>

Now I did this for a class. If you aren't doing OOP then you will obviously need to modify this for your own use.

CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
shailesh4all at gmail dot com
29.05.2010 12:42
Hi,
Anyone who is interested in submitting their information by post to HTTPS site (e.g. payment gateway) where https page needs basic authentication before submitting the information. below code will be helpful.

<?php
$submit_url
= "https://sitename/process.php";

$curl = curl_init();

curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ;
curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_SSLVERSION,3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params );
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_URL, $submit_url);

$data = split("text/html", curl_exec($curl) );
$temp = split("\r\n", $data[1]) ;

$result = unserialize( $temp[2] ) ;

print_r($result);
curl_close($curl);
?>
obones_remove_me at free dot fr
27.04.2010 12:27
For those of you wondering how to specify the content-type for a file uploaded via curl, the syntax is as follows:

<?php

$data
= array('file' => '@/home/user/test.png;type=image/png');

?>

Simply adding a semicolon with the type= at the end.
Note that this has been reported not to work in all versions of PHP and I have done the following tests:

5.2.6 (libcurl 7.18.2) : Does not work
5.2.13 (libcurl 7.20.0) : Works just fine

So it might be worth updating your installation of PHP and/or libcurl if you want to be able to use this syntax
sjungwirth at google mail dot com
23.04.2010 0:11
I couldn't find a way to force a curl request to go to a particular IP address, but you can do it with fsockopen:
<?php
    $ip
= '123.45.67.89';
   
$fp = fsockopen($ip, 80, $errno, $errstr, 5);
   
$result = '';
    if (!
$fp) {
        echo
"$errstr ($errno)<br />\n";
    } else {
       
$out = "GET /path/to/the/file.ext HTTP/1.1\r\n";
       
$out .= "Host: www.exampl.com\r\n";
       
$out .= "Connection: Close\r\n\r\n";
       
fwrite($fp, $out);
        while (!
feof($fp)) {
           
$result .= fgets($fp, 128);
        }
       
fclose($fp);
    }
?>
I needed it to test the response from a set of servers behind a load balancer.
clint at fewbar dot com
16.04.2010 23:56
If you have turned on conditional gets on a curl handle, and then for a subsequent request, you don't have a good setting for CURLOPT_TIMEVALUE , you can disable If-Modified-Since checking with:

<?php

$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, $foo);
curl_setopt($ch, CURLOPT_TIMEVALUE, filemtime($foo_path));
curl_setopt($ch, CURLOPT_TIMECONDITION, CURLOPT_TIMECOND_IFMODIFIEDSINCE);
curl_exec($ch);
// Reuse same curl handle
curl_setopt($ch, CURLOPT_URL, $bar);
curl_setopt($ch, CURLOPT_TIMEVALUE, null); // don't know mtime
curl_setopt($ch, CURLOPT_TIMECONDITION, 0); // set it to 0, turns it off
curl_exec($ch);

?>
julien veneziano
8.04.2010 12:56
If you need to send deta in a DELETE request, use:

<?php
$request_body
= 'some data';
$ch = curl_init('http://www.example.com');
       
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
       
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
       
curl_setopt($ch, CURLOPT_HEADER, 0);
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
       
$response = curl_exec($ch);
var_dump($response);
?>
anderseta at gmail dot com
22.03.2010 11:48
If you wish to find the size of the file you are streaming and use it as your header this is how:

<?php

function write_function($curl_resource, $string)
{
    if(
curl_getinfo($curl_resource, CURLINFO_SIZE_DOWNLOAD) <= 2000)
    {
       
header('Expires: 0');
       
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
       
header('Pragma: public');
       
header('Content-Description: File Transfer');
       
header("Content-Transfer-Encoding: binary");
       
header("Content-Type: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_TYPE)."");
       
header("Content-Length: ".curl_getinfo($curl_resource, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    }
   
    print
$string;

    return
mb_strlen($string, '8bit');
}

1440 is the the default number of bytes curl will call the write function (BUFFERSIZE does not affect this, i actually think you can not change this value), so it means the headers are going to be set only one time.

Writefunction must return the exact number of bytes of the string, so you can return a value with mb_strlen.

?>
starosielec at googlemail dot com
20.02.2010 0:07
You can use also use object methods as callback functions. This is usefull if your curl ressource is part of an object handling transfers.
Instead of curl_setopt($curl, CURLOPT_WRITEFUNCTION, "curl_handler_recv") you can use array($object, "method") as value for callback options.

For example:

<?php
class downloader {
    private
$curl;

    function
__construct() {
       
$this->curl = curl_init();
       
curl_setopt($this->curl, CURLOPT_WRITEFUNCTION, array($this, "curl_handler_recv"));
    }

     function
curl_handler_recv($res, $data) {
     
//...
    
}
  
//...
}
?>
Ed Cradock
5.02.2010 19:47
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.

Example:

<?php
function doPut($url, $fields)
{
  
$fields = (is_array($fields)) ? http_build_query($fields) : $fields;

   if(
$ch = curl_init($url))
   {
     
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
     
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Length: ' . strlen($fields)));
     
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
     
curl_exec($ch);

     
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

     
curl_close($ch);

      return (int)
$status;
   }
   else
   {
      return
false;
   }
}

if(
doPut('http://example.com/api/a/b/c', array('foo' => 'bar')) == 200)
  
// do something
else
  
// do something else.
?>

You can grab the request data on the other side with:

<?php
if($_SERVER['REQUEST_METHOD'] == 'PUT')
{
  
parse_str(file_get_contents('php://input'), $requestData);

  
// Array ( [foo] => bar )
  
print_r($requestData);

  
// Do something with data...
}
?>

DELETE  can be done in exactly the same way.
Pawel Antczak
9.12.2009 21:07
Hello.
During problems with "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set"
I was looking for solution.
I've found few methods on this page, but none of them was good enough, so I made one.
<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
   
curl_setopt($ch, CURLOPT_HEADER, true);
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
   
$data = curl_exec($ch);
   
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if (
$http_code == 301 || $http_code == 302) {
        list(
$header) = explode("\r\n\r\n", $data, 2);
       
$matches = array();
       
preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
       
$url = trim(array_pop($matches));
       
$url_parsed = parse_url($url);
        if (isset(
$url_parsed)) {
           
curl_setopt($ch, CURLOPT_URL, $url);
           
$redirects++;
            return
curl_redirect_exec($ch, $redirects);
        }
    }
    if (
$curlopt_header)
        return
$data;
    else {
        list(,
$body) = explode("\r\n\r\n", $data, 2);
        return
$body;
    }
}
?>

Main issue in existing functions was lack of information, how many redirects was done.
This one will count it.
First parameter as usual.
Second should be already initialized integer, it will be incremented by number of done redirects.
You can set CURLOPT_HEADER if You need it.
php dot net at NO dot sgerrand dot SPAM dot com
3.11.2009 8:01
If you change the post array to a string, PHP creates the post data successfully.

As a quick and dirty example of implementing this fix:

<?php

$ch
= curl_init;
$url = 'http://www.example.com';

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);

foreach (
$postData as $var) if (strpos($var, '@') === 0) {
   
$postAsString = true;
}

if (
$postAsString === true) {
   
$str = '';

    foreach (
$postData as $key => $val) {
       
$str .= '&' . $key . '=' . $val;
    }

   
$postData = substr_replace($str, '', 0, 1);
}

curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

curl_exec($ch);

?>
Chris at PureFormSolutions dot com
23.09.2009 0:54
I've found that setting CURLOPT_HTTPHEADER more than once will clear out any headers you've set previously with CURLOPT_HTTPHEADER.

Consider the following:
<?php
   
# ...

   
curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
       
"Content-Type: text/xml; charset=utf-8",
       
"Expect: 100-continue"
   
));

   
# ... do some other stuff ...

   
curl_setopt($cURL,CURLOPT_HTTPHEADER,array (
       
"Accept: application/json"
   
));

   
# ...
?>

Both the Content-Type and Expect I set will not be in the outgoing headers, but Accept will.
Stan van de Burgt
19.09.2009 11:41
If you get a "failed creating formpost data" upon curl_exec() when POSTing a form, check if one of the field values starts with the @ character.

Took me an hour or so to find out as I wanted to post a @reply tweet to twitter which typically start with @screenname.
Tyranoweb
4.09.2009 23:42
There is a function to send POST data in page with five parameters :

$post must be an array
$page is the page where POST datas will be send.
$n must be true to continue if they are php redirection (Location: )
$session must be define true if you want to use cookies
$referer must be a link to get a wrong referer or only to have a referer.

<?php
function curl_data_post($post, $page, $n, $session, $referer)
    {
        if(!
is_array($post))
        {
         return
false;
        }
       
       
$DATA_POST = curl_init();
       
curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
       
curl_setopt($DATA_POST, CURLOPT_URL, $page);
       
curl_setopt($DATA_POST, CURLOPT_POST, true);
        if(
$n)
        {
        
curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
        }
        if(
$session)
        {
        
curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
        
curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
        }
       
        if(
$referer)
        {
        
curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
        }
       
       
curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
       
$data = curl_exec($DATA_POST);
        if(
$data == false)
        {
         echo
'Warning : ' . curl_error($DATA_POST);
        
curl_close($DATA_POST);
         return
false;
        }
        else
        {
        
curl_close($DATA_POST);
         return
$data;
        }
    }
?>
rob
24.08.2009 6:07
Whats not mentioned in the documentation is that you have to set CURLOPT_COOKIEJAR to a file for the CURL handle to actually use cookies, if it is not set then cookies will not be parsed.
Sylvain R
28.07.2009 12:05
When you are using CURLOPT_FILE to download directly into a file you must close the file handler after the curl_close() otherwise the file will be incomplete and you will not be able to use it until the end of the execution of the php process.

<?php

$fh
= fopen('/tmp/foo', 'w');
$ch = curl_init('http://example.com/foo');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_exec($ch);
curl_close($ch);

# at this point your file is not complete and corrupted

fclose($fh);

# now you can use your file;

read_file('/tmp/foo');

?>
mikeseth at gmail dot com
15.07.2009 11:32
When using CURLOPT_FILE, pass it the file handle that is open for write only (eg fopen('blahblah', 'w+')). If you also open the file for reading (eg fopen('blahblah', 'rw')), curl will fail with error 23.
Victor Jerlin
3.07.2009 13:12
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.

I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
xektrum at gmail dot com
2.07.2009 18:14
As of php 5.3 CURLOPT_PROGRESSFUNCTION its supported here's how:

<?php

function callback($download_size, $downloaded, $upload_size, $uploaded)
{
   
// do your progress stuff here
}

$ch = curl_init('http://www.example.com');

// This is required to curl give us some progress
// if this is not set to false the progress function never
// gets called
curl_setopt($ch, CURLOPT_NOPROGRESS, false);

// Set up the callback
curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, 'callback');

// Big buffer less progress info/callbacks
// Small buffer more progress info/callbacks
curl_setopt($ch, CURLOPT_BUFFERSIZE, 128);

$data = curl_exec($ch);

?>

Hope this help.
Andrew
14.06.2009 13:56
I noticed that if you want to get current cookie file after curl_exec() - you need to close current curl handle (like it said in manual), but if you want cookies to be dumped to file after any curl_exec (without curl_close) you can:

<?php
#call it normally
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/');
$result1 = curl_exec($ch);

#and then  make a temp copy
$ch_temp=curl_copy_handle(ch);
curl_close($ch);
$ch=$ch_temp;
?>

Only this way, if you close $ch_temp - cookies wont be dumped.
ericbianchetti at gmail dot com
4.06.2009 12:06
if you need to send a SOAP string that is the CURL you must use :

<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
curl_setopt ($ch, CURLOPT_HTTPHEADER, array('SOAPAction: ""'));   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
curl_setopt($ch, CURLOPT_HEADER, 0);

$output = curl_exec($ch);
?>

Note : Having based my snipet on Chemo demonstration (oscommerce user know who he is), XML_POST_URL and XML_PAYLOAD where defined as constant with define().

The point is : at the opposite of .xml , SOAP must send the header 'SOAPAction: ""' that can be a valid URI, an empty string (that is here) or nothing ('SOAPAction: '). The later case baing not accepted by all server, the second one indicating the target is the URI used to post the SOAP.
http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528
franciscocha at gmail dot com
20.05.2009 0:11
Example how to connect to FTPES (FTP explicit SSL). This script will connect to any FTPES server and out put the list of directories.

<?php
    $username
= 'username';
   
$password = 'password';
   
$url = 'example.com';
   
$ftp_server = "ftp://" . $username . ":" . $password . "@" . $url;
   
    echo
"Starting CURL.\n";
   
$ch = curl_init();
    echo
"Set CURL URL.\n";
   
   
//curl FTP
   
curl_setopt($ch, CURLOPT_URL, $ftp_server);
   
   
//For Debugging
    //curl_setopt($ch, CURLOPT_VERBOSE, TRUE);   
   
    //SSL Settings
   
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
   
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
   
curl_setopt($ch, CURLOPT_FTP_SSL, CURLFTPSSL_TRY);
   
   
//List FTP files and directories
   
curl_setopt($ch, CURLOPT_FTPLISTONLY, TRUE);
   
   
//Output to curl_exec
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    echo
"Executing CURL.\n";
   
$output = curl_exec($ch);
   
curl_close($ch);
    echo
"Closing CURL.\n";
    echo
$output . "\n";

  
$files = explode("\n", $output);
  
print_r($files);
?>
ashooner - - gmail , com
23.03.2009 0:28
When passing CURLOPT_POSTFIELDS a url-encoded string in order to use Content-Type: application/x-www-form-urlencoded, you can pass a string directly:
<?php
curl_setopt
(CURLOPT_POSTFIELDS, 'field1=value&field2=value2');
?>

rather than passing the string in an array, as in fred at themancan dot com's example.
Ariz Jacinto
2.02.2009 3:36
if unserialize() returns FALSE on a serialized PHP object due to an extraneous string (e.g. "1") appended at the end of the object, you need to set the ff cURL option:

<?php
curl_setopt
($ch, CURLOPT_RETURNTRANSFER, true);
?>
urkle at outoforder dot cc
28.01.2009 15:49
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json'));
?>

[EDIT BY danbrown AT php DOT net: Contains a typofix by 'KdoubleU' on 3-FEB-09.]
fnjordy at gmail dot com
1.12.2008 8:28
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.

default - callbacks will be called as expected.
true - content will be returned but callback function will not be called.
false - content will be output and callback function will not be called.

Note that CURLOPT_HEADERFUNCTION callbacks are always called.
saidk at phirebranding dot com
19.11.2008 22:31
Passing in PHP's $_SESSION into your cURL call:

<?php
session_start
();
$strCookie = 'PHPSESSID=' . $_COOKIE['PHPSESSID'] . '; path=/';
session_write_close();

$curl_handle = curl_init('enter_external_url_here');
curl_setopt( $curl_handle, CURLOPT_COOKIE, $strCookie );
curl_exec($curl_handle);
curl_close($curl_handle);
?>

This worked great for me.  I was calling pages from the same server and needed to keep the $_SESSION variables.  This passes them over.  If you want to test, just print_r($_SESSION);

Enjoy!
dorphalsig at gmail dot com
10.10.2008 23:20
This may not be a surprise for many, but I know I bled my eyes out trying to implement this in php. And when I knew it was this simple, I really felt extremely stupid. So I put this just so google will save somebody some time in the future.

PHP NTLM AUTH

Make sure you have the 'curl' extension loaded
now just do...

<?php
curl_setopt
($ch,CURLAUTH_NTLM);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
?>

and just continue to use curl in the ordinary fashion.
OPALA
26.09.2008 9:37
To fetch (or submit data to) multiple pages during one session,use this:

<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

curl_setopt($ch, CURLOPT_URL, 'http://example.com/page1.php');
$result1 = curl_exec($ch);

curl_setopt($ch, CURLOPT_URL, 'http://example.com/page2.php');
$result2 = curl_exec($ch);

curl_close($ch);
?>
rkirilow at gmail dot com
16.09.2008 10:34
Some of you may noticed that curl is not transferring cookies between sequent calls to a host. This is because you must activate curl`s "cookie parser". That is achieved using an external file like this:
<?php
curl_setopt
(CURLOPT_FILE, '/tmp/cookies_file');
?>
If you don`t need to read any cookies but you still want the "cookie parser" use the same code but with dummy file with no data like '/dev/null', that way curl is storing cookies internaly per curl_handle:
<?php
curl_setopt
(CURLOPT_FILE, '/dev/null');
?>

[EDIT BY danbrown AT php DOT net: In a note dated 26-SEP-08, (adamplumb AT gmail DOT com) offered the following addendum:

[It] should really be CURLOPT_COOKIEFILE.  I was bitten by this issue myself with code that previously worked for logging into a website and posting a form.  However, at some point the code just stopped working, and I eventually found that I needed to set this option to /dev/null for it to work.
]
George
23.08.2008 2:14
If you set CURLOPT_RESUME_FROM to resume the file, and then reuse the same Curl handle to download another file, you must reset the resume status by calling curl_setopt( $ch, CURLOPT_RESUME_FROM, 0 ). It will not reset, and will apply to all subsequent transfers even if the URL is the same.
w dot danford at electronics-software dot com
12.08.2008 19: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
6.08.2008 1:28
To find what encoding a given HTTP POST request uses 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
5.08.2008 13: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
ac at an dot y-co dot de
10.07.2008 19: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
7.07.2008 18: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.06.2008 23:19
Someone posted this under tmpfile (http://us3.php.net/manual/en/function.tmpfile.php#69419), and I thought it was particularly useful:

[The PHP function tmpfile()] is really useful for libcurl's CURLOPT_PUT feature if what you're trying to PUT is a string.   For example:

<?php
/* 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.06.2008 18: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);
?>
sgamon at yahoo dot com
10.04.2008 2: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
4.04.2008 18: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:

<?php
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);
}
?>
c00lways at gmail dot com
4.03.2008 22:16
if you would like to send xml request to a server (lets say, making a soap proxy),
you have to set

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
?>

makesure you watch for cache issue:
the below code will prevent cache...

<?php
curl_setopt
($ch, CURLOPT_FORBID_REUSE, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
?>

hope it helps ;)
mavook at gmail dot com
16.02.2008 7:26
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.

<?php
curl_setopt
($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
// ^^ This will post multipart/form-data
?>
jade dot skaggs at gmail dot com
7.01.2008 18:48
After much struggling, I managed to get a SOAP request requiring HTTP authentication to work.  Here's some source that will hopefully be useful to others.

         <?php

         $credentials
= "username:password";
        
        
// Read the XML to send to the Web Service
        
$request_file = "./SampleRequest.xml";
       
$fh = fopen($request_file, 'r');
       
$xml_data = fread($fh, filesize($request_file));
       
fclose($fh);
               
       
$url = "http://www.example.com/services/calculation";
       
$page = "/services/calculation";
       
$headers = array(
           
"POST ".$page." HTTP/1.0",
           
"Content-type: text/xml;charset=\"utf-8\"",
           
"Accept: text/xml",
           
"Cache-Control: no-cache",
           
"Pragma: no-cache",
           
"SOAPAction: \"run\"",
           
"Content-length: ".strlen($xml_data),
           
"Authorization: Basic " . base64_encode($credentials)
        );
      
       
$ch = curl_init();
       
curl_setopt($ch, CURLOPT_URL,$url);
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
       
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
       
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
       
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);
       
       
// Apply the XML to our curl call
       
curl_setopt($ch, CURLOPT_POST, 1);
       
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

       
$data = curl_exec($ch);

        if (
curl_errno($ch)) {
            print
"Error: " . curl_error($ch);
        } else {
           
// Show me the result
           
var_dump($data);
           
curl_close($ch);
        }

?>
contacto at hardcode dot com dot ar
12.12.2007 21: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..

<?php
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
Ojas Ojasvi
25.09.2007 19:52
<?php
/*
* Author: Ojas Ojasvi
* Released: September 25, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

$url = 'http://www.php.net';

// disguises the curl using fake headers and a fake user agent.
function disguise_curl($url)
{
 
$curl = curl_init();

 
// Setup headers - I used the same headers from Firefox version 2.0.0.6
  // below was split up because php.net said the line was too long. :/
 
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
 
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
 
$header[] = "Cache-Control: max-age=0";
 
$header[] = "Connection: keep-alive";
 
$header[] = "Keep-Alive: 300";
 
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
 
$header[] = "Accept-Language: en-us,en;q=0.5";
 
$header[] = "Pragma: "; // browsers keep this blank.

 
curl_setopt($curl, CURLOPT_URL, $url);
 
curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
 
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
 
curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
 
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
 
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
 
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 
curl_setopt($curl, CURLOPT_TIMEOUT, 10);

 
$html = curl_exec($curl); // execute the curl command
 
curl_close($curl); // close the connection

 
return $html; // and finally, return $html
}

// uses the function and displays the text off the website
$text = disguise_curl($url);
echo
$text;
?>

Ojas Ojasvi
charles at tastik dot net
1.09.2007 11:27
FYI,

Anyone trying to connect to .NET with CURL to send a simple XML post, pay attention to the following. This will save you hours! There is a previous note that I saw either on this page, or somewhere else on this site that explains the correct way to specify the header option is to create an array, then reference the array from the CURLOPT.

ie.  Do something like this:

<?php
// Req. HTTP Header Values
 
$header[] = "Content-type: text/xml";

// Target URL
 
$sendTo = "http://www.example.com";

// Post Data
 
$post = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n....etc, etc,";

// Create CURL Connection
 
$ch = curl_init();
 
curl_setopt($ch, CURLOPT_USERAGENT, 'XtraDoh xAgent');
 
curl_setopt($ch, CURLOPT_URL, $sendTo);
 
curl_setopt($ch, CURLOPT_TIMEOUT, 900);
 
curl_setopt($ch, CURLOPT_CONNECTIONTIMEOUT, 30);
 
curl_setopt($ch, CURLOPT_FAILONERROR, false);
 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
 
curl_setopt($ch, CURLOPT_POST, true);
 
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
?>

Notice the HTTPHEADER, $header above. I have not been able to get .NET to properly read the HTTP header as specified (in this case as text/xml) when using the following:

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array('Content-Type'=>'text/xml'));
?>

Although this may work when working with other PHP, IIS, or even PHP, Apache, it does not (at least in my experience) work with .NET, IIS.
andrabr at gmail dot com
20.08.2007 23:03
This is very clear in hindsight, but it still cost me several hours:

<?php 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...
michael sky
6.07.2007 0:09
if you are trying to connect to 'https://...' and after that want to work with POST data - that's the way:

<?php
$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.06.2007 20: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:

<?php
$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.06.2007 23:35
If you are getting the following error:

SSL: certificate subject name 'example.com' does not match target host name 'example.net'

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

<?php curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); ?>
vincent at ludden dot nl
12.06.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.
ashw1 - at - no spam - post - dot - cz
4.06.2007 1:51
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.

This piece of code solves it:

<?php

if ($cookies != '')
    {
    if (
substr(PHP_OS, 0, 3) == 'WIN')
        {
$cookies = str_replace('\\','/', getcwd().'/'.$cookies);}
   
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookies);
   
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookies);
    }

?>
Jon Freilich
12.05.2007 6: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.04.2007 18: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.03.2007 1: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
8.03.2007 15:50
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.

<?php
function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback');
?>
null at nahdah dot com
27.11.2006 22:42
I was having problems with Authorize.net and the SSL cert matching even after adding:

<?php
curl_setopt
($ch, CURLOPT_SSL_VERIFYPEER, 0);
?>

What I found after a lot of stumbling was I needed to set VERIFYHOST to FALSE.  So if you are still have a problem with Authorize.NET SSL and cURL add this:

<?php
curl_setopt
($ch, CURLOPT_SSL_VERIFYHOST, 0);
?>
pyroevi at yahoo dot com
22.11.2006 19:33
I was working on using php to interface with an authorize.net gateway, and I ran into a problem with certificates using curl to talk the https:// url.

curl_error() told me "SSL certificate problem, verify that the CA cert is OK."

I googled it and found the same "solution" over and over again: bypass verification by adding this line after curl_init():

<?php
curl_setopt
($connection, CURLOPT_SSL_VERIFYPEER, false);
?>

This worked great, but I was required to verify, so here's what I did. Add the following lines:

<?php
curl_setopt
($connection, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($connection, CURLOPT_CAINFO, "path:/ca-bundle.crt");
?>

with "path:/ca-bundle.crt" being the path to that certificate file. You can get this file by downloading the curl package (http://curl.haxx.se/download.html) and looking for it in the lib folder.

Feel free to email me.
eion at bigfoot dot com
22.11.2006 5: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;
        }
    }
?>
zarko at svetlozar dot net
1.10.2006 13: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:

<?php
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):

<?php
#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.08.2006 19:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

<?php 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.
Philippe dot Jausions at 11abacus dot com
30.05.2006 20: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.04.2006 16: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
heyrocker at yahoo dot com
23.02.2006 22:57
The examples below for HTTP file upload work great, but I wanted to be able to post multiple files through HTTP upload using HTML arrays as specified in example 38.3 at

http://us3.php.net/features.file-upload

In this case, you need to set the arrays AND keys in the $post_data, it will not work with just the array names. The following example shows how this works:

<?php

    $post_data
= array();
   
   
$post_data['pictures[0]'] = "@cat.jpg";
   
$post_data['pictures[1]'] = "@dog.jpg";
   

   
$ch = curl_init();
   
curl_setopt($ch, CURLOPT_URL, "http://example.com/my_url.php" );
   
curl_setopt($ch, CURLOPT_POST, 1 );
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   
$postResult = curl_exec($ch);

    if (
curl_errno($ch)) {
       print
curl_error($ch);
    }
   
curl_close($ch);
    print
"$postResult";
?>
petelu $ post dot sk
17.02.2006 13:19
load https:// or  http://example.com/exam.php 
with  POST  data (name=alex&year=18) and apply COOKIEs

<?php
$sessions
= curl_init();
curl_setopt($sessions,CURLOPT_URL,'http://example.com/exam.php');
curl_setopt($sessions, CURLOPT_POST, 1);
curl_setopt($sessions,CURLOPT_POSTFIELDS,'name=alex&year=18');
curl_setopt($sessions,CURLOPT_COOKIEJAR,
dirname(__FILE__).'/cookie.txt');
curl_setopt($sessions,CURLOPT_FOLLOWLOCATION,0);
curl_setopt($sessions, CURLOPT_HEADER , 1);
curl_setopt($sessions, CURLOPT_RETURNTRANSFER,1);
$my_load_page = curl_exec($this->sessions);
?>
luca dot manzo at bbsitalia dot com
2.02.2006 12:55
If you're getting trouble with cookie handling in curl:

- curl manages tranparently cookies in a single curl session
- the option
<?php curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName"); ?>

makes curl to store the cookies in a file at the and of the curl session

- the option
<?php curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName"); ?>

makes curl to use the given file as source for the cookies to send to the server.

so to handle correctly cookies between different curl session, the you have to do something like this:

<?php
       $ch
= curl_init();
      
curl_setopt ($ch, CURLOPT_URL, $url);
      
curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE_PATH);
      
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE_PATH);

      
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
      
$result = curl_exec ($ch);
      
curl_close($ch);
       return
$result;
?>

in particular this is NECESSARY if you are using PEAR_SOAP libraries to build a webservice client over https and the remote server need to establish a session cookie. in fact each soap message is sent using a different curl session!!

I hope this can help someone
Luca
Dustin Hawkins
27.12.2005 23: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.12.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;
}

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

?>
phpnet at wafflehouse dot de
23.10.2005 15: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

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

and following calls to curl_exec() will output to STDOUT again.
webmaster () stauceni.com
20.10.2005 22: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.
ROXORT at TGNOOB dot FR
21.09.2005 16:09
<?php
/*
  Here is a script that is usefull to :
  - login to a POST form,
  - store a session cookie,
  - download a file once logged in.
*/

// INIT CURL
$ch = curl_init();

// SET URL FOR THE POST FORM LOGIN
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Login.php');

// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);

// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'fieldname1=fieldvalue1&fieldname2=fieldvalue2');

// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');

# Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
# not to print out the results of its query.
# Instead, it will return the results as a string return value
# from curl_exec() instead of the usual true/false.
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

// EXECUTE 1st REQUEST (FORM LOGIN)
$store = curl_exec ($ch);

// SET FILE TO DOWNLOAD
curl_setopt($ch, CURLOPT_URL, 'http://www.example.com/Members/Downloads/AnnualReport.pdf');

// EXECUTE 2nd REQUEST (FILE DOWNLOAD)
$content = curl_exec ($ch);

// CLOSE CURL
curl_close ($ch);

/*
  At this point you can do do whatever you want
  with the downloaded file stored in $content :
  display it, save it as file, and so on.
*/
?>
mcknight at chek dot com
23.08.2005 5: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
7.06.2005 23: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:

<?php
$fp
= fopen ("php://output", "w") or die("Unable to open stdout for writing.\n");
curl_setopt($ch, CURLOPT_FILE, $fp);
?>
michaeledwards.com
1.06.2005 23:57
Problems can occur if you mix CURLOPT_URL with a 'Host:' header in CURLOPT_HEADERS on redirects because cURL will combine the host you explicitly stated in the 'Host:' header with the host from the Location: header of the redirect response.

In short, don't do this:

<?php
$host
= "www.example.com";
$url = "http://$host/";

$headers = array("Host: $host");

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

Do
this instead:

$host = "www.example.com";
$url = "http://$host/";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
?>
samlowry at e-baka dot net
14.05.2005 15:09
About CURLOPT_ENCODING:
added in curl in 7.10 - Oct 1 2002
In 7.10.5 - May 19 2003 syntax was chnaged:
"setting CURLOPT_ENCODING to "" automaticly enables all supported encodings"
ikendra at yken dot nospam dot org
9.05.2005 18: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:

<?php
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.example.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;
}
?>
mcknight at chek dot com
21.02.2005 18: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.

<?php
 
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
11.11.2004 6:51
The parse_response code below does not return multiple cookies as the value of 'Set-Cookie' if multiple cookies are set by the server.  It appears to only return the last cookie set.
raul at navenetworks dot com
21.07.2004 22:19
Hi!

I have found some information I am sure it could help lot of programmers when they want to connect with curl to any https website and they haven't a good or right CA Cert :)

I give you just one example It has resolved me 2 hours of my time looking for a solution.

It is simple, just if you get any error in the curl_exec (use curl_error(...) to see the error to trace it) add the next line and everything is solved:

(note: replace $ch with the right curl variable)

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

<?php

$ch
= curl_init();
$res= curl_setopt ($ch, CURLOPT_URL,"https://yoururl/cgi");

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Idc=si&");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$xyz = curl_exec ($ch);

curl_close ($ch);
echo
$xyz;
if (
$xyz == NULL) {
           echo
"Error:<br>";
           echo
curl_errno($ch) . " - " . curl_error($ch) . "<br>";
}
?>

I hope this helps.

Raul Mate Galan
Ceo Navenetworks Corp.

Note: Thanks to Ruben Lopez Gea for his help too.
ron at ttvavanti dot nl
7.05.2004 17:00
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
brett at brettbrewer dot com
29.04.2004 4:48
I found it very annoying that cURL did not offer any easy way to extract the response headers. If you do

  <?php curl_setopt($ch, CURLOPT_HEADER, 1); ?>

then you only get the headers output inline with the rest of your response. Here's a nice little function to parse the cURL response when you use CURLOPT_HEADER.  I took it from an example on another site and turned it into a function. It assumes you're using CURLOPT_RETURNTRANSFER to return the response to some variable that is then passed to the function. You just pass it a curl_exec result and it returns the result parsed into an array with headers broken up into their correct parts.

<?php
function parse_response($response){
   
/*
    ***original code extracted from examples at
    ***http://www.webreference.com/programming/php/cookbook/chap11/1/3.html

    ***returns an array in the following format which varies depending on headers returned

        [0] => the HTTP error or response code such as 404
        [1] => Array
        (
            [Server] => Microsoft-IIS/5.0
            [Date] => Wed, 28 Apr 2004 23:29:20 GMT
            [X-Powered-By] => ASP.NET
            [Connection] => close
            [Set-Cookie] => COOKIESTUFF
            [Expires] => Thu, 01 Dec 1994 16:00:00 GMT
            [Content-Type] => text/html
            [Content-Length] => 4040
        )
        [2] => Response body (string)
*/

   
list($response_headers,$response_body) = explode("\r\n\r\n",$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;
    }

    return array(
$response_code,$response_header_array,$response_body);
}
?>
Jakub Horky
4.04.2004 22:20
A bit more documentation (without minimum version numbers):

- CURLOPT_WRITEFUNCTION
- CURLOPT_HEADERFUNCTION
  Pass a function which will be called to write data or headers respectively. The callback function prototype:

long write_callback (resource ch, string data)

The ch argument is CURL session handle. The data argument is data received. Note that its size is variable. When writing data, as much data as possible will be returned in all invokes. When writing headers, exactly one complete header line is returned for better parsing.
The function must return number of bytes actually taken care of. If that amount differs from the amount passed to this function, an error will occur.

- CURLOPT_READFUNCTION
  Pass a function which will be called to read data. The callback function prototype:

string read_callback (resource ch, resource fd, long length)

The ch argument is CURL session handle. The fd argument is file descriptor passed to CURL by CURLOPT_INFILE option. The length argument is maximum length which can be returned.
The function must return string containing the data which were read. If length of the data is more than maximum length, it will be truncated to maximum length. Returning anything else than a string means an EOF.

[Note: there is more callbacks implemented in current cURL library but they aren't unfortunately implemented in php curl interface yet.]
tim dot php at ebw dot ca
19.11.2003 3:18
The page http://curl.haxx.se/libcurl/c/curl_easy_setopt.html at the cURL site has a list of all the CURLOPTS, including many not mentioned here. Also see http://curl.haxx.se/libcurl/php/examples/ for cURL examples in PHP.
eric at imap dot ch
7.07.2003 18:38
I managed to use curl to retrieve information from severs on ports other than 80 or 443 (for https) on some installations but not on all.
If you get an "CURLE_COULDNT_CONNECT /* 7 */" error, try adding the port : (for example)

<?php curl_setopt($ch, CURLOPT_PORT, $_SERVER['SERVER_PORT']); ?>
me
14.05.2003 18:36
Just a reminder: When setting your CURLOPT_POSTFIELDS remember to replace the spaces in your values with %20
dweingart at pobox dot com
3.04.2003 1:08
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:

<?php curl_setopt($ch, CURLOPT_COOKIEJAR, '-'); ?>

'-' means stdout

-dw
yann dot corno at free dot fr
13.11.2002 13:19
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:

<?php curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml")); ?>

Yann

23.10.2002 21:04
beware that not all cURLlib constants are supported under php :
e.g. CURLOPT_PROGRESSFUNCTION or CURLOPT_WRITEDATA are not supported.

CURLOPT_WRITEFUNCTION, although undocumented is supported. It takes the name of a user_defined function.
the function should take two arguments (the curl handle, and the inputdata) and return the length of the written data
e.g.

<?php
function myPoorProgressFunc($ch,$str){
global
$fd;
$len = fwrite($fd,$str);
print(
"#");
return
$len;
}

curl_setopt($ch,CURLOPT_WRITEFUNCTION,"myPoorProgressFunc");
?>

Also be aware that CURLOPT_WRITEFUNCTION  does NOT take the CURLOPT_FILE as a parameter!
in curl lib it would take CURLOPT_WRITEDATA but this is not supported by php; that's why I use "global $fd;" in my exemple function.

CURLOPT_HEADERFUNCTION works the same, and is guaranteed to receive complete header lines as input!

Hope this helps

Ivan
mrcheezy at hotmail dot com
13.09.2002 23:34
If you set return transfer to 1 and are sending a post form and find that this crashes php try setting follow location to 1 also. I'm not exactly sure why this crashed, but after i used follow it stopped.

<?php
  curl_setopt
($sess, CURLOPT_FOLLOWLOCATION, '1');
 
curl_setopt ($sess, CURLOPT_RETURNTRANSFER, '1');
?>
paul at zgtec dot com
26.08.2002 23:31
To make a POST in multipart/form-data mode
this worked for me, the " \n" at the end of the variables was very important on my OS X server.

<?php

$file
= "file_to_upload.txt";
$submit_url = "http://www.example.com/upload_page.php";

$formvars = array("cc"=>"us \n");
$formvars[variable_1] = "bla bla \n";
$formvars[variable_2] = "bla bla \n";
$formvars[variable_3] = "bla bla \n";
$formvars[variable_4] = "bla bla \n";
$formvars[upfile] = "@$file"; // "@" causes cURL to send as file and not string (I believe)

    // init curl handle
   
$ch = curl_init($submit_url);
   
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt");  //initiates cookie file if needed
   
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt");  // Uses cookies from previous session if exist
   
curl_setopt($ch, CURLOPT_REFERER, "http://www.example.net");  //if server needs to think this post came from elsewhere
   
curl_setopt($ch, CURLOPT_VERBOSE, 1);
   
curl_setopt($ch, CURLOPT_HEADER, 1);
   
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); // follow redirects recursively
   
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   
curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars);

   
// perform post
   
echo $pnp_result_page = curl_exec($ch);
   
curl_close ($ch);

?>
tychay at alumni dot caltech dot edu
3.04.2002 11:14
CURLOPT_HTTPHEADER is NOT like the -H command line switch. The command line switch adds or replaces headers (much like the header() line in PHP, but for HTTP clients instead of servers), but the curl extension will eliminate the headers cURL sends by default.

For instance, your Authorization, Host, Referer, Pragma, and Accept headers which are normally written by default or by other CURLOPT_*'s.

Also, it might seem intuitive that this should accept an array hash of header->values, but this is not the case. It accepts an array of strings of the format "Header: Value", much like the -H command-line switch.

Hope this helps,

terry
asmith at crawlspace dot com
1.03.2002 4:18
It's possible to take advantage of multiple URLs on the same host in one curl_exec transaction ... just use multiple instances of CURLOPT_URL.

Example:

<?php
$ch
= curl_init();
curl_setopt($ch, CURLOPT_URL, "http://example.com/a.html");
curl_setopt($ch, CURLOPT_URL, "http://example.com/b.html");
curl_setopt($ch, CURLOPT_URL, "http://example.com/c.html");
curl_exec($ch);
curl_close($ch);
?>

... the URLs appear to be hit in the same order they are entered. This takes advantage of cURL's Persistant Connection capability if all the URLs are on the same host!
bvwj at swbell dot net
18.12.2001 10:35
To collect cookies recieved with a request, set CURLOPT_COOKIEJAR "cookieFileName".  Then use CURLOPT_COOKIEFILE "cookieFileName" to recall them in subsequent transactions.

22.09.2001 18:52
To make a POST in multipart/form-data mode

(to upload a file for example) you can use

<?php curl_setopt($ch,CURLOPT_POSTFIELDS,$post); ?>

where $post is an array :

<?php
$post
['key1'] = 'data1';
//  like a text field in a POST
$post['file1'] = '@filename1'
// upload filename1
?>

For more informations see the

curl_formparse man page.
sr2899.at.hotmail.com
14.05.2001 23:00
CURLOPT_RETURNTRANSFER has the interesting behaviour of tacking a null char onto the end of the string.  This null char is actually on the end of the php string, and can cause some odd results if you're not expecting it to be there.
fil at rezox dot com
22.02.2001 2:50
If you want to connect to a secure server for posting info/reading info, you need to make cURL with the openSSL options. Then the sequence is nearly identical to the previous example (except http_S_://, and possibly add the useragent):

<?php
curl_setopt
($ch, CURLOPT_URL,"https://example.com");
//some sites only accept your request if your browser looks legit, so send a useragent profile...
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
?>
bvr at xs4all dot nl
7.02.2001 16:09
If you'd like to include extra headers in your POST request, you can accomplish this by setting the following option:

CURLOPT_HTTPHEADER

This is similar to the CURL -H command line switch.

Thanks to Daniel Stenberg for pointing out this usefull feature!

Note: this option was first supported in PHP version 4.03 .
awestholm at imail dot usi dot net
25.01.2001 20:33
Just because the docs are rather sparse on this, to set multiple values in a cookie, you separate them with a semicolon, as usual. An example, yo set j to j and k to k:

<?php curl_setopt($ch,CURLOPT_COOKIE,"j=j;k=k"); ?>

    -- Alex
dan dot polansky at seznam dot cz
17.01.2001 23:31
I used to download www pages to my script and one of the pages was different in MS explorer and different, when I downloaded it. Namely, information, I was really interested in was missing. That was because the server on the other bank of the river was looking at who is downloading the page. Everything got fixed when I pretended I was MSIE. It is done with curl. Here is a function, that you may use in similar situation

<?php
function download_pretending($url,$user_agent) {
  
$ch = curl_init();
  
curl_setopt ($ch, CURLOPT_URL, $url);
  
curl_setopt ($ch, CURLOPT_USERAGENT, $user_agent);
  
curl_setopt ($ch, CURLOPT_HEADER, 0);
  
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  
$result = curl_exec ($ch);
  
curl_close ($ch);
   return
$result;
}
?>



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)