curl_setopt

(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)

curl_setoptSetzt eine Option für einen cURL-Transfer

Beschreibung

curl_setopt(CurlHandle $handle, int $option, mixed $value): bool

Setzt eine Option für das angegeben cURL-Handle.

Parameter-Liste

handle

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

option

Die zu setzende CURLOPT_XXX-Option

value

Der Wert, der für option gesetzt werden soll.

value sollte für die folgenden Werte des Parameters option vom Typ bool sein:

Option Wert für value Anmerkungen
CURLOPT_AUTOREFERER true, um automatisch den Referer: in Anfragen zu setzen, die einer Weiterleitung per Location: folgen
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_CERTINFO true, um die SSL Zertifikatsinformation bei sicheren Übertragungen auf STDERR auszugeben. Hinzugefügt in cURL 7.19.1. Erfordert, dass CURLOPT_VERBOSE gesetzt ist, um eine Wirkung zu haben.
CURLOPT_CONNECT_ONLY true weist die Bibliothek an, die gesamte erforderlichen Proxy-Authentifizierung und den Verbindungsaufbau durchzuführen, aber keine Datenübertragung. Diese Option ist für HTTP, SMTP und POP3 implementiert. Hinzugefügt in 7.15.2.
CURLOPT_CRLF true, um Unix-Zeilenumbrüche beim Transfer in CRLF-Zeilenumbrüche umzuwandeln.
CURLOPT_DISALLOW_USERNAME_IN_URL true, um URLs, die einen Benutzernamen enthalten, zu verbieten. Benutzernamen sind per Voreinstellung erlaubt (0). Hinzugefügt in cURL 7.61.0. Verfügbar seit PHP 7.3.0.
CURLOPT_DNS_SHUFFLE_ADDRESSES true, um die Reihenfolge aller zurückgegeber Adressen zu mischen, so dass sie in zufälliger Reihenfolge verwendet werden, wenn ein Name aufgelöst wird und mehr als eine IP-Adresse zurückgegeben wurde. Dies kann bewirken, dass IPv4 vor IPv6 verwendet wird, oder umgekehrt. Hinzugefügt in cURL 7.60.0. Verfügbar seit PHP 7.3.0.
CURLOPT_HAPROXYPROTOCOL true, um einen HAProxy PROXY-Protokoll v1 Header zu Beginn der Verbindung zu senden. Standardmäßig wird dieser Header nicht gesendet. Hinzugefügt in 7.60.0. Verfügbar seit PHP 7.3.0.
CURLOPT_SSH_COMPRESSION true, um die eingebaute SSH-Komprimierung zu aktivieren. Dies ist eine Anfrage, kein Befehl; der Server kann diese ignorieren. Hinzugefügt in 7.56.0. Verfügbar seit PHP 7.3.0.
CURLOPT_DNS_USE_GLOBAL_CACHE true, um den globalen DNS-Cache zu nutzen. Diese Option ist nicht thread-safe. Sie ist standardmäßig aktiviert, wenn PHP für Singlethread-Verwendung kompiliert wurde (CLI, FCGI, Apache2-Prefork, etc.)
CURLOPT_FAILONERROR true, um PHP anzuweisen, bei Fehlern (HTTP-Code ist größer oder gleich 400) eine ausführliche Fehlermeldung zu liefern. Das Standardverhalten ist, die Seite normal zurückzugeben und den Code zu ignorieren.
CURLOPT_SSL_FALSESTART true, um TLS-False-Start zu aktivieren. Hinzugefügt in cURL 7.42.0. Verfügbar seit PHP 7.0.7.
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. Siehe auch CURLOPT_MAXREDIRS.
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_FTP_CREATE_MISSING_DIRS true, um fehlende Verzeichnisse zu erzeugen, wenn eine FTP-Operation auf einen Pfad stößt, der zurzeit nicht existiert.
CURLOPT_FTPAPPEND true, um Daten an die serverseitige Datei anzuhängen anstatt diese zu überschreiben.
CURLOPT_TCP_NODELAY true, um den Nagle-Algorithmus von TCP zu deaktivieren, der verucht, die Anzahl kleiner Pakete im Netzwerk zu reduzieren. Verfügbar für Versionen, die mit libcurl 7.11.2 oder höher kompiliert wurden.
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. Das Prefix CURLINFO_ ist beabsichtigt.
CURLOPT_HTTP09_ALLOWED Ob HTTP/0.9 Antworten erlaubt sind. Der Standardwert ist von libcurl 7.66.0 an false; zuvor war er true. Verfügbar seit PHP 7.3.15 bzw. 7.4.3, wenn mit libcurl >= 7.64.0 kompiliert
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_HTTP_CONTENT_DECODING false, um den Original-HTTP-Response-Body zu erhalten. Verfügbar von PHP 5.5.0 an, wenn mit libcurl >= 7.16.2 kompiliert.
CURLOPT_KEEP_SENDING_ON_ERROR true, um den Anfragerumpf weiterhin zu senden, wenn der zurückgegebene HTTP-Code gleich oder größer als 300 ist. Standardmäßig würde das Senden beendet und der Stream oder die Verbindung geschlossen. Zweckmäßig für manuelle NTML-Authentifizierung. Die meisten Anwendungen benötigen diese Option nicht. Verfügbar von PHP 7.3.0 an, wenn mit libcurl >= 7.51.0 kompiliert.
CURLOPT_MUTE true, um jegliche Ausgabe der cURL-Funktionen zu unterbinden Entfernt in cURL 7.15.5 (statt dessen kann CURLOPT_RETURNTRANSFER verwendet werden)
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_PATH_AS_IS true, um Dot-Dot-Sequenzen nicht aufzulösen. Hinzugefügt in cURL 7.42.0. Verfügbar seit PHP 7.0.7.
CURLOPT_PIPEWAIT true, um auf Pipelining/Multiplexing zu warten. Hinzugefügt in cURL 7.43.0. Verfügbar seit PHP 7.0.7.
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 Transfer als String zurückzuliefern, anstatt ihn direkt auszugeben.
CURLOPT_SASL_IR true, um die Übertragung der ursprünglichen Response im ersten Paket zu aktivieren. Hinzugefügt in cURL 7.31.10. Verfügbar seit PHP 7.0.7.
CURLOPT_SSL_ENABLE_ALPN false, um ALPN im SSL-Handshake zu deaktivieren (wenn das SSL-Backend libcurl mit entsprechender Unterstüzung kompiliert wurde), was genutzt werden kann, um HTTP2 auszuhandeln. Hinzugefügt in cURL 7.36.0. Verfügbar seit PHP 7.0.7.
CURLOPT_SSL_ENABLE_NPN false, um NPN im SSL-Handshake zu deaktivieren (wenn das SSL-Backend libcurl mit entsprechender Unterstüzung kompiliert wurde), was genutzt werden kann, um HTTP2 auszuhandeln. Hinzugefügt in cURL 7.36.0. Verfügbar seit PHP 7.0.7.
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-Verzeichnis kann mit CURLOPT_CAPATH ausgewiesen werden. true als Standard seit cURL 7.10.
CURLOPT_SSL_VERIFYSTATUS true, um den Zertifikatsstatus zu überprüfen. Hinzugefügt in cURL 7.41.0. Verfügbar seit PHP 7.0.7.
CURLOPT_PROXY_SSL_VERIFYPEER false, um cURL zu veranlassen, das Peer-Zertifikat nicht zu prüfen. Alternative Zertifikate zur Prüfung können mit der CURLOPT_CAINFO Option, ein Zertifikatsverzeichnis mit der CURLOPT_CAPATH Option angegeben werden. Wenn auf false gesetzt, wird die Peer-Zertifikatsprüfung immer gelingen. true by default. Hinzugefügt in PHP 7.3.0 and libcurl >= cURL 7.52.0.
CURLOPT_SAFE_UPLOAD Immer true, was die Unterstützung für das Präfix @ für das Hochladen von Dateien in CURLOPT_POSTFIELDS deaktiviert. Das bedeutet, dass Werte, die mit @ beginnen, sicher als Felder übergeben werden können. Für das Hochladen kann stattdessen CURLFile verwendet werden.
CURLOPT_SUPPRESS_CONNECT_HEADERS true, um Proxy CONNECT Antwortheader in den Benutzercallback-Funktionen CURLOPT_HEADERFUNCTION und CURLOPT_WRITEFUNCTION zu unterdrücken, wenn CURLOPT_HTTPPROXYTUNNEL verwendet wird und ein CONNECT-Request durchgeführt wird. Hinzugefügt in cURL 7.54.0. Verfügbar seit PHP 7.3.0.
CURLOPT_TCP_FASTOPEN true, um TCP-Fast-Open zu aktivieren. Hinzugefügt in cURL 7.49.0. Verfügbar seit PHP 7.0.7.
CURLOPT_TFTP_NO_OPTIONS true, um keine TFTP-Optionen zu senden. Hinzugefügt in cURL 7.48.0. Verfügbar seit PHP 7.0.7.
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 vom Typ int 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.
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. Wenn libcurl so kompiliert wurde, dass die standard System-Namensauflösung verwendet wird, wird dieser Teil der Verbindung dennoch die volle Sekunden-Auflösung für Timeouts mit einem minimalen Timeout von einer Sekunde verwenden. Hinzugefügt in cURL 7.16.2.
CURLOPT_DNS_CACHE_TIMEOUT Die Dauer in Sekunden, die ein DNS-Eintrag im Speicher gehalten wird. Der Standard sind 120 Sekunden (2 Minuten).
CURLOPT_EXPECT_100_TIMEOUT_MS Der Timeout für Expect: 100-continue-Antworten in Millisekunden. Standardwert sind 1000 Millisekunden. Hinzugefügt in cURL 7.36.0. Verfügbar seit PHP 7.0.7.
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS Vorsprung für IPv6 für den Happy-Eyeballs-Algorithmus. Happy-Eyeballs versucht für Dual-Stack-Hosts sowohl zu IPv4- als auch IPv6-Adressen zu verbinden, wobei IPv6 für die angegebe Dauer in Millisekunden bevorzugt wird. Die Voreinstellung ist CURL_HET_DEFAULT, die zurzeit 200 Millisekunden beträgt. Hinzugefügt in 7.59.0. Verfügbar seit PHP 7.3.0.
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_HEADEROPT Wie mit Headern umzugehen ist. Eine der folgenden Konstanten: CURLHEADER_UNIFIED: die Header, die in CURLOPT_HTTPHEADER angegeben wurden, werden in Requests sowohl an Server wie auch Proxies verwendet. Ist diese Option aktiviert, hat CURLOPT_PROXYHEADER keinerlei Wirkung. CURLHEADER_SEPARATE: sendet die CURLOPT_HTTPHEADER-Header nur an einen Server, aber nicht an einen Proxy. Proxy-Header müssen mit CURLOPT_PROXYHEADER gesetzt werden, damit sie verwendet werden. Es ist zu beachten, dass libcurl bei einem non-CONNECT-Request, der an einen Proxy gesendet wird, sowohl die Server- als auch die Proxy-Header sendet. Bei einem CONNECT sendet libcurl die CURLOPT_PROXYHEADER-Header nur an den Proxy, und CURLOPT_HTTPHEADER-Header nur an den Server. Standardwert ist CURLHEADER_SEPARATE von cURL 7.42.1 an, und CURLHEADER_UNIFIED zuvor. Hinzugefügt in cURL 7.37.0. Verfügbar seit PHP 7.0.7.
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), CURL_HTTP_VERSION_1_1 (nutze HTTP/1.1), CURL_HTTP_VERSION_2_0 (versucht HTTP 2), CURL_HTTP_VERSION_2 (Alias von CURL_HTTP_VERSION_2_0), CURL_HTTP_VERSION_2TLS (versucht HTTP 2 nur über TLS (HTTPS)) oder CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (stellt nicht-TLS HTTP Anfragen unter Verwendung von HTTP/2 ohne HTTP/1.1 Upgrade).
CURLOPT_HTTPAUTH

Die zu nutzende HTTP-Authentisierungsmethode; zur Verfügung stehen: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_AWS_SIGV4, 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 setzt alle Bits. cURL wählt automatisch dasjenige aus, das es als am sichersten erachtet.

CURLAUTH_ANYSAFE setzt alle Bits außer CURLAUTH_BASIC. cURL wählt automatisch dasjenige aus, das es als am sichersten erachtet.

CURLOPT_INFILESIZE Die erwartete Dateigröße der hochzuladenden Datei in Bytes. Beachten Sie, dass die Verwendung dieser Option libcurl nicht daran hindern wird mehr Daten zu senden, da was genau gesendet wird von CURLOPT_READFUNCTION abhängt.
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 geduldet wird. Nach dieser Zeit wird die Transferrate als zu langsam angesehen und der Transfer wird beendet.
CURLOPT_MAIL_RCPT_ALLLOWFAILS Erlaubt, dass der Befehl RCPT TO bei manchen Empfängern fehlschlägt. Beim Senden von Daten an mehrere Empfänger bricht cURL in der Standardeinstellung die SMTP-Kommunikation ab, wenn bei mindestens einem der Empfänger der Befehl RCPT TO einen Fehler zurückgibt. Mit dieser Option wird cURL angewiesen, Fehler zu ignorieren und mit den verbleibenden gültigen Empfängern fortzufahren. Wenn alle Empfänger RCPT TO-Fehler auslösen und dieses Flag gesetzt ist, bricht cURL die SMTP-Kommunikation ab und gibt den vom letzten RCPT TO-Befehl erhaltenen Fehler zurück.
CURLOPT_MAXAGE_CONN Die maximale Leerlaufzeit, für die eine bestehende Verbindung zur Wiederverwendung in Betracht gezogen wird. Standardmäßig ist die maximale Zeit auf 118 Sekunden eingestellt.
CURLOPT_MAXFILESIZE_LARGE Die maximale Größe einer Datei in Bytes, die heruntergeladen werden darf. Ist die angeforderte Datei größer als dieser Wert, wird die Übertragung nicht gestartet und CURLE_FILESIZE_EXCEEDED zurückgegeben. Da die Größe einer Datei nicht immer bekannt ist, bevor sie heruntergeladen wird, hat diese Option keine Auswirkung, selbst wenn die Datei größer als der angegebene Grenzwert ist.
CURLOPT_MAXLIFETIME_CONN Die maximale Zeit in Sekunden, die bei einer bestehenden Verbindung seit ihrer Erstellung vergangen sein darf, um für eine erneute Verwendung in Betracht gezogen zu werden. Wenn eine Verbindung im Cache gefunden wird, die älter als dieser Wert ist, wird sie geschlossen, sobald alle laufenden Übertragungen abgeschlossen sind. Der Standardwert ist 0 Sekunden, was bedeutet, dass die Option deaktiviert ist und alle Verbindungen dafür in Frage kommen, wiederverwendet zu werden.
CURLOPT_MAXCONNECTS Die maximal erlaubte Anzahl persistenter Verbindungen; bei Erreichen des Limits wird die älteste Verbindung im Cache geschlossen, um zu verhindern, dass sich die Anzahl der offenen Verbindungen erhöht.
CURLOPT_MAXREDIRS Die maximal erlaubte Anzahl von HTTP-Weiterleitungen. Verwenden Sie diese Option zusammen mit CURLOPT_FOLLOWLOCATION. Der Standardwert von 20 wird gesetzt, um Endlos-Weiterleitungen zu verhindern. Der Wert -1 erlaubt unendlich viele Weiterleitungen, und 0 verhindert jegliche Weiterleitung.
CURLOPT_PORT Erlaubt das Setzen eines alternativen Ports für die Verbindung.
CURLOPT_POSTREDIR Eine Bitmaske von 1 (301 Moved Permanently), 2 (302 Found) und 4 (303 See Other), ob die HTTP POST Methode beibehalten werden soll, wenn CURLOPT_FOLLOWLOCATION gesetzt ist, und ein sepzifischer Typ von Weiterleitung auftritt. Hinzugefügt in cURL 7.19.1.
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_MQTT, 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), CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A oder CURLPROXY_SOCKS5_HOSTNAME. 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_SOCKS5_AUTH

Die zu verwendende SOCK5-Authentifizierungsmethode. Die Optionen sind: CURLAUTH_BASIC, CURLAUTH_GSSAPI, CURLAUTH_NONE.

Der bitweise Operator | (oder) kann verwendet werden, um mehr als eine Methode zu kombinieren. Wird dies getan, wird cURL den Server befragen, um zu sehen, welche Methoden unterstützt werden, und die beste zu wählen.

CURLAUTH_BASIC erlaubt Benutzernamen/Passwort Authentifizierung.

CURLAUTH_GSSAPI erlaubt GSS-API Authentifizierung.

CURLAUTH_NONE erlaubt keine Authentifizierung.

Voreinstellung ist CURLAUTH_BASIC|CURLAUTH_GSSAPI. Der eigentliche Benutzername und das Passwort werden mit der CURLOPT_PROXYUSERPWD Option gesetzt.

Verfügbar von PHP 7.3.0 mit curl >= 7.55.0 an.
CURLOPT_SSL_OPTIONS Setze SSL-Verhaltensoptionen, die eine Bitmaske von beliebigen der folgenden Konstanten ist: CURLSSLOPT_ALLOW_BEAST: versuche keine Workarounds für Sicherheitsmängel in den SSL3 und TLS1.0 Protokollen. CURLSSLOPT_NO_REVOKE: deaktiviere Zertifikatswiderrufsprüfungen für SSL-Backends, die dies unterstützen. CURLSSLOPT_AUTO_CLIENT_CERT: sucht und verwendet automatisch ein Client-Zertifikat für die Authentifizierung, wenn es vom Server angefordert wird. Diese Option wird nur von Schannel (der nativen Windows-SSL-Bibliothek) unterstützt. CURLSSLOPT_NATIVE_CA: für die Überprüfung von Zertifikaten wird der systemeigene CA-Speicher des Betriebssystems verwendet; funktioniert unter Windows nur, wenn es für die Verwendung von OpenSSL gebaut wurde. Diese Option ist experimentell und das Verhalten kann sich noch ändern. CURLSSLOPT_NO_PARTIALCHAIN: akzeptiert keine "teilweisen" Zertifikatsketten, was cURL sonst standardmäßig tut. Diese Option wird nur von OpenSSL unterstützt und führt dazu, dass die Zertifikatsüberprüfung fehlschlägt, wenn die Kette mit einem Zwischenzertifikat und nicht mit einem Stammzertifikat endet. CURLSSLOPT_REVOKE_BEST_EFFORT: ignoriert bei denjenigen SSL-Backends, die ein solches Verhalten unterstützen, die Überprüfung von Zertifikatswiderrufen, wenn Verteilungspunkte fehlen oder offline sind. Diese Option wird nur von Schannel (der nativen Windows-SSL-Bibliothek) unterstützt. Wenn diese Option mit CURLSSLOPT_NO_REVOKE kombiniert wird, hat die letztere Vorrang. Hinzugefügt in cURL 7.25.0. Verfügbar seit PHP 7.0.7.
CURLOPT_SSL_VERIFYHOST 2, um zu überprüfen, ob ein Common Name-Feld oder ein Subject Alternate Name-Feld im SSL-Peer-Zertifikat mit dem angegebenen Hostnamen übereinstimmt. 0, um die Namen nicht zu überprüfen. 1 sollte nicht verwendet werden. In Produktionsumgebungen sollte der Wert dieser Option auf 2 (Standardwert) belassen werden. Die Unterstützung für Wert 1 wurde in cURL 7.28.1 entfernt
CURLOPT_SSLVERSION Entweder CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5), CURL_SSLVERSION_TLSv1_2 (6) oder CURL_SSLVERSION_TLSv1_3 (7). Die höchste TLS-Version kann durch Verwendung einer der CURL_SSLVERSION_MAX_*-Konstanten spezifiziert werden. Es ist ebenfalls möglich eine der CURL_SSLVERSION_*-Konstanten mit einer der CURL_SSLVERSION_MAX_*-Konstanten ODER zu verknüpfen. CURL_SSLVERSION_MAX_DEFAULT (die höchste Version, die von der Bibliothek unterstützt wird), CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, oder CURL_SSLVERSION_MAX_TLSv1_3.

Hinweis:

Am besten ist es diese Option nicht zu setzen, und den Default zu verwenden. Die Werte 2 und 3 sind sehr gefährlich, angesichts der bekannten Sicherheitslücken in SSLv2 und SSLv3.

CURLOPT_PROXY_SSL_OPTIONS Setzt Proxy-SSL-Verhaltensoptionen, was eine Bitmaske der folgenden Konstanten ist: CURLSSLOPT_ALLOW_BEAST: versuche nicht, irgendwelche Workarounds für einen Sicherheitsmangel in den SSL3 und TLS1.0 Protokollen zu nutzen. CURLSSLOPT_NO_REVOKE: deaktiviert Zertifikatswiderrufprüfungen für SSL-Backends, wo solches Verhalten vorhanden ist. (curl >= 7.44.0) CURLSSLOPT_NO_PARTIALCHAIN: akzeptiert keine "partiellen" Zertifikatsketten, was andernfalls per Voreinstellung erfolgt. (curl >= 7.68.0) Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSL_VERIFYHOST 2 prüft Namensfelder im Zertifikat des HTTP-Proxies gegen den Proxy-Namen. Wenn auf 0 gesetzt, gelingt die Verbindung unabhängig von dem im Zertifikat verwendeten Namen. Diese Möglichkeit ist mit Vorsicht zu verwenden! 1 wird in curl 7.28.0 und früher als Debugoption behandelt. Von curl 7.28.1 bis 7.65.3 wird CURLE_BAD_FUNCTION_ARGUMENT zurückgegeben. Von curl 7.66.0 an wird 1 und 2 gleich behandelt. In Produktivumgebungen sollte der Wert dieser Option bei 2 belassen werden (Standardwert). Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLVERSION Eines aus CURL_SSLVERSION_DEFAULT, CURL_SSLVERSION_TLSv1, CURL_SSLVERSION_TLSv1_0, CURL_SSLVERSION_TLSv1_1, CURL_SSLVERSION_TLSv1_2, CURL_SSLVERSION_TLSv1_3, CURL_SSLVERSION_MAX_DEFAULT, CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, CURL_SSLVERSION_MAX_TLSv1_3 oder CURL_SSLVERSION_SSLv3.

Hinweis:

Am besten ist es, dies nicht zu setzen und den Standardwert CURL_SSLVERSION_DEFAULT zu verwenden, der versucht, die Remote-SSL-Protokollversion herauszufinden.

Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_STREAM_WEIGHT Setze die numerische Streamgewichtung (eine Zahl zwischen 1 und 256). Hinzugefügt in cURL 7.46.0. Verfügbar seit PHP 7.0.7.
CURLOPT_TCP_KEEPALIVE Wenn auf 1 gesetzt, werden TCP-Keepalive-Sonden gesendet. Die Verzögerung und Häufigkeit dieser Sonden kann mit den CURLOPT_TCP_KEEPIDLE und CURLOPT_TCP_KEEPINTVL Optionen festgelegt werden, falls das Betriebssystem diese unterstützt. Wenn auf 0 gesetzt (Voreinstellung), sind Keepalive-Sonden deaktiviert. Hinzugefügt in cURL 7.25.0.
CURLOPT_TCP_KEEPIDLE Gibt die Verzögerung in Sekunden an, die das Betriebssystem im Fall, dass die Verbindung inaktiv ist, wartet bevor Keepalive-Sonden gesendet werden, wenn CURLOPT_TCP_KEEPALIVE aktiviert ist. Nicht alle Betriebssysteme unterstützen diese Option. Die Voreinstelung ist 60. Hinzugefügt in cURL 7.25.0.
CURLOPT_TCP_KEEPINTVL Gibt den Zeitraum in Sekunden an, den das Betriebssystem zwischen dem Senden von Keepalive-Sonden warten wird, wenn CURLOPT_TCP_KEEPALIVE aktiviert ist. Nicht alle Betriebssysteme unterstützen diese Option. Die Voreinstelung ist 60. Hinzugefügt in cURL 7.25.0.
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. Verwenden Sie CURL_TIMECOND_NONE, um CURLOPT_TIMEVALUE zu ignorieren und die Seite immer zurückzugeben. Die Standardeinstellung ist CURL_TIMECOND_NONE. Vor cURL 7.46.0 war die Standardeinstellung CURL_TIMECOND_IFMODSINCE.
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. Wenn libcurl so kompiliert wurde, dass die standard System-Namensauflösung verwendet wird, wird dieser Teil der Verbindung dennoch die volle Sekunden-Auflösung für Timeouts mit einem minimalen Timeout von einer Sekunde verwenden. Hinzugefügt in cURL 7.16.2.
CURLOPT_TIMEVALUE Zeit in Sekunden seit dem 1. Januar 1970. Dieser Wert wird von CURLOPT_TIMECONDITION genutzt.
CURLOPT_TIMEVALUE_LARGE Die Zeit in Sekunden seit dem 1. Januar 1970. Die Zeit wird von CURLOPT_TIMECONDITION verwendet. Der Standardwert ist Null. Der Unterschied zwischen dieser Option und CURLOPT_TIMEVALUE ist der Typ des Arguments. Auf Systemen, auf denen 'long' nur aus 32-Bit besteht, muss diese Option verwendet werden, um Daten jenseits des Jahrs 2038 zu setzen. Hinzugefügt in cURL 7.59.0. Verfügbar seit PHP 7.3.0.
CURLOPT_UPKEEP_INTERVAL_MS Einige Protokolle verfügen über Mechanismen zur Aufrechterhaltung von Verbindungen. Diese Mechanismen senden normalerweise einen Teil des Datenverkehrs an bestehende Verbindungen, um sie aufrecht zu erhalten. Diese Option definiert das Intervall für die Aufrechterhaltung der Verbindung. Derzeit ist HTTP/2 das einzige Protokoll mit einem Mechanismus für eine solche Aufrechterhaltung. Wenn das Intervall überschritten wird, wird ein HTTP/2-PING-Frame an die Verbindung gesendet. Die Voreinstellung ist 60 Sekunden.
CURLOPT_UPLOAD_BUFFERSIZE Die bevorzugte Puffergröße für den cURL-Upload-Puffer in Bytes. Die Standardgröße des Upload-Puffers beträgt 64 Kilobytes. Als maximale Puffergröße können 2 Megabyte eingestellt werden, als Mindestgröße 16 Kilobyte.
CURLOPT_MAX_RECV_SPEED_LARGE Wenn ein Download diese Geschwindigkeit (gezählt in Bytes pro Sekunde) im Gesamtdurchschnitt während der Übertragung überschreitet, wird die Übertragung angehalten, um die durschnittliche Rate kleiner oder gleich dem Parameter-Wert zu halten. Voreinstellung ist unbegrenzte Geschwindigkeit. Hinzugefügt in cURL 7.15.5.
CURLOPT_MAX_SEND_SPEED_LARGE Wenn ein Upload diese Geschwindigkeit (gezählt in Bytes pro Sekunde) im Gesamtdurchschnitt während der Übertragung überschreitet, wird die Übertragung angehalten, um die durschnittliche Rate kleiner oder gleich dem Parameter-Wert zu halten. Voreinstellung ist unbegrenzte Geschwindigkeit. Hinzugefügt in cURL 7.15.5.
CURLOPT_SSH_AUTH_TYPES Eine Bitmaske bestehend aus einer oder mehreren von CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. CURLSSH_AUTH_ANY lässt libcurl eine wählen. Hinzugefügt in cURL 7.16.1.
CURLOPT_IPRESOLVE Erlaubt einer Applikation auszuwählen, welche Art von IP Adressen verwendet werden, wenn Hostnamen aufgelöst werden. Dies ist nur interessant, wenn Hostnamen verwendet werden, die Adressen unter mehr als einer IP-Version auflösen; mögliche Werte sind CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6; Voreinstellung ist CURL_IPRESOLVE_WHATEVER. Hinzugefügt in cURL 7.10.8.
CURLOPT_FTP_FILEMETHOD Die zu verwendende Methode, um eine Datei auf einem FTP(S) Server zu erreichen. Mögliche Werte sind CURLFTPMETHOD_DEFAULT, CURLFTPMETHOD_MULTICWD, CURLFTPMETHOD_NOCWD und CURLFTPMETHOD_SINGLECWD. Hinzugefügt in cURL 7.15.1.

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

Option Wert für value Anmerkungen
CURLOPT_ABSTRACT_UNIX_SOCKET Aktiviert die Verwendung eines abstrakten Unix Domainsocket anstatt eine TCP-Verbindung zu einem Host aufzubauen, und setzt den Pfad auf den gegebenen string. Diese Option teilt sich die gleiche Bedeutung mit CURLOPT_UNIX_SOCKET_PATH. Diese beiden Optionen verwenden den selben Speicher, und daher kann nur eine pro Handle genutzt werden. Verfügbar seit PHP 7.3.0 und cURL 7.53.0
CURLOPT_ALTSVC Gibt den Namen der Datei an, die cURL für den Alt-Svc-Cache verwenden soll, um den Inhalt des Caches auszulesen und gegebenenfalls nach einer Übertragung zurückzuschreiben. Letzteres ist allerdings nur möglich, wenn in CURLOPT_ALTSVC_CTRL nicht die Option CURLALTSVC_READONLYFILE verwendet wird.
CURLOPT_ALTSVC_CTRL Eine Bitmaske mit dem gewünschten Satz von Merkmalen. Sie wird verwendet, um cURL anzuweisen, wie Alt-Svc bei der Übertragung mit diesem Handle zu verwenden ist. cURL akzeptiert Alt-Svc-Header nur über HTTPS. Es führt auch nur dann eine Anfrage an einen alternativen Ursprung aus, wenn dieser Ursprung ordnungsgemäß über HTTPS gehostet wird. Das Setzen eines beliebigen Bits aktiviert die Alt-Svc-Engine. Folgende Optionen stehen zur Verfügung: CURLALTSVC_H1, CURLALTSVC_H2, CURLALTSVC_H3 und CURLALTSVC_READONLYFILE.
CURLOPT_AWS_SIGV4

Stellt die AWS V4-Signatur-Authentifizierung im HTTP(S)-Header bereit.

Diese Option hat Vorrang vor allen anderen Authentifizierungstypen, die in CURLOPT_HTTPAUTH angegeben wurden. Diese Methode kann nicht mit anderen Authentifizierungstypen kombiniert werden.

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. Erfodert möglicherweise einen absoluten Pfad.
CURLOPT_CAINFO_BLOB Der Name einer PEM-Datei, die ein oder mehrere Zertifikate enthält, mit denen die Gegenstelle verifiziert werden soll. Diese Option hat Vorrang vor CURLOPT_CAINFO. Verfügbar seit PHP 8.2.0 und cURL 7.77.0
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 "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. Wenn der Name eine leere Zeichenkette ist, werden keine Cookies geladen, aber die Cookie-Behandlung ist dennoch aktiviert.
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_COOKIELIST Eine Cookie-Zeichenkette (d. h. eine einzelne Zeile im Netscape/Mozilla-Format, oder ein regulärer Set-Cookie-Header im HTTP-Stil), die dieses einzelne Cookie dem internen Cookie-Speicher hinzufügt. "ALL" löscht alle Cookies, die im Speicher vorgehalten werden. "SESS" löscht alle Sitzungscookies, die im Speicher vorgehalten werden. "FLUSH" schreibt alle bekannten Cookies in die durch CURLOPT_COOKIEJAR angegebene Datei. "RELOAD" lädt alle Cookies aus der durch CURLOPT_COOKIEFILE angegebenen Datei. Verfügbar seit cURL 7.14.1.
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_DEFAULT_PROTOCOL

Das Standardprotokoll, das verwendet werden soll, wenn die URL kein Schema angibt.

Hinzugefügt in cURL 7.45.0. Verfügbar seit PHP 7.0.7.
CURLOPT_DNS_INTERFACE

Setze den Namen der Netzwerkschnittstelle, an die sich der DNS-Resolver binden soll. Dies muss ein Schnittstellenname sein (keine Adresse).

Hinzugefügt in cURL 7.33.0. Verfügbar seit PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP4

Setze die lokale IPv4 Adresse, an die sich der Resolver binden soll. Das Argument sollte eine einzige numerische IPv4 Adresse als Zeichenkette enthalten.

Hinzugefügt in cURL 7.33.0. Verfügbar seit PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP6

Setze die lokale IPv6 Adresse, an die sich der Resolver binden soll. Das Argument sollte eine einzige numerische IPv6 Adresse als Zeichenkette enthalten.

Hinzugefügt in cURL 7.33.0. Verfügbar seit PHP 7.0.7.
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-PORT-Anweisung genutzt wird. Die PORT-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_HSTS

Name der HSTS- (HTTP Strict Transport Security) Cache-Datei.

CURLOPT_HSTS_CTRL

Steuert das Verhalten von HSTS (HTTP Strict Transport Security). Die Bitmaske sollte mit dem gewünschten Satz von Merkmalen gefüllt werden, um cURL anzuweisen, wie HSTS für die Übertragungen mit diesem Handle verwendet werden soll. CURLHSTS_ENABLE aktiviert den speicherinternen HSTS-Cache. Wenn die HSTS-Cache-Datei definiert ist, sollte CURLHSTS_READONLYFILE gesetzt werden, um sie schreibgeschützt zu machen.

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_KEYPASSWD Das erforderliche Passwort, um die privaten CURLOPT_SSLKEY oder CURLOPT_SSH_PRIVATE_KEYFILE Schlüssel zu verwenden. Hinzugefügt in cURL 7.16.1.
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_LOGIN_OPTIONS Kann verwendet werden, um Protokoll spezifische Anmeldeoptionen, wie den bevorzugten Authentifizierungsmechanismus per "AUTH=NUM" oder "AUTH=*", zu setzen, und sollte in Verbindung mit der CURLOPT_USERNAME Option verwendet werden. Hinzugefügt in cURL 7.34.0. Verfügbar seit PHP 7.0.7.
CURLOPT_PINNEDPUBLICKEY Setze den pinned öffentlichen Schlüssel. Die Zeichenkette kann der Dateiname des pinned öffentlichen Schlüssels sein. Das erwartete Dateiformat ist "PEM" oder "DER". Die Zeichenkette kann ebenfalls eine beliebige Anzahl von base64 kodierten SHA-256 Hashes sein, denen "sha256//" vorangestellt ist, und die durch ";" getrennt sind. Hinzugefügt in cURL 7.39.0. Verfügbar seit PHP 7.0.7.
CURLOPT_POSTFIELDS Die in einem HTTP-POST-Request zu nutzenden Daten. Als Wert für diesen Parameter 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. Ist value ein Array, dann wird der Content-Type-Header auf multipart/form-data gesetzt. Dateien können mit CURLFile oder CURLStringFile gesendet werden. In diesem Fall muss value ein Array sein.
CURLOPT_PRIVATE Beliebige Daten, die mit diesem cURL-Handle assoziert werden sollen. Diese Daten können in der Folge mit der CURLINFO_PRIVATE Option von curl_getinfo() abgerufen werden. cURL tut sonst nichts mit diesen Daten. Bei cURL-Multi-Handles sind diese privaten Daten typischerweise ein eindeutiger Schlüssel, um ein Standard-cURL-Handle zu identifizieren. Hinzugefügt in cURL 7.10.3.
CURLOPT_PRE_PROXY Ein Wert vom Typ string, der den Hostnamen des Preproxys oder dessen IP-Adresse in Dezimalpunktschreibweise enthält, mit dem sich curl für die kommende Anfrage verbinden soll bevor es sich mit dem in CURLOPT_PROXY angegebenen HTTP(S)-Proxy verbindet. Der Preproxy kann nur ein SOCKS-Proxy sein und sollte mit vorangestelltem [scheme]:// angegeben werden, um anzugeben welcher Typ von Socks verwendet wird. Eine numerische IPv6-Adresse muss in [eckigen Klammen] angegeben werden. Wird der Preproxy als leere Zeichenkette angegeben, deaktiviert dies ausdrücklich die Verwendung eines Preproxys. Um eine Portnummer in dieser Zeichenkette anzugeben, wird ein :[port] am Ende des Hostnamens angefügt. Die Portnummer des Proxys kann optinal separat mit der Option CURLOPT_PROXYPORT angegeben werden. Wenn kein Port angegeben wird, wird für Proxys standardmäßig Port 1080 verwendet. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY Der HTTP-Proxy, durch den Requests getunnelt werden sollen.
CURLOPT_PROXY_SERVICE_NAME Der Name des Proxy-Authentifizierungsdienstes. Hinzugefügt in cURL 7.43.0 für HTTP-Proxys und in cURL 7.49.0 für SOCKS5-Proxys. Verfügbar seit PHP 7.0.7.
CURLOPT_PROXY_CAINFO Der Pfad zu einem Proxy-Zertifikatsautoritätspaket (CA). Der Pfad wird als String angegeben, der eine Datei benennt, die ein oder mehrere Zertifikate enthält, die zur Prüfung des HTTPS-Proxys verwendet werden. Diese Option gilt für die Verbindung zu einem HTTP-Proxy, nicht zu einem HTTPS-Server. Der Standardwert ist der System-Pfad unter dem das cacert-Paket von libcurl erwartet wird. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_CAINFO_BLOB Der Name einer PEM-Datei, die ein oder mehrere Zertifikate enthält, mit denen der HTTPS-Proxy verifiziert werden soll. Diese Option ist für die Verbindung mit einem HTTPS-Proxy, nicht mit einem HTTPS-Server. Standardmäßig ist dies der Systempfad, in dem das cacert-Bundle von libcurl gespeichert werden soll. Verfügbar seit PHP 8.2.0 und libcurl >= cURL 7.77.0.
CURLOPT_PROXY_CAPATH Das Verzeichnis, das mehrere CA-Zertifikate enthält, mit denen der HTTPS-Proxy geprüft wird. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_CRLFILE Setzt den Dateinamen mit der Verkettung von CRL (Zertifikatswiderrufsliste) im PEM-Format, die in der Zertifikatsprüfung, die während des SSL-Austauschs stattfindet, verwendet wird. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_KEYPASSWD Setzt die Zeichenkette, die als Passwort erforderlich ist, um den CURLOPT_PROXY_SSLKEY privaten Schlüssel zu verwenden. Es wird niemals ein Passwort benötigt, um ein Zertifikat zu laden, aber es wird eins benötigt, um den privaten Schlüssel zu laden. Diese Option gilt für die Verbindung zu einem HTTPS-Proxy, nicht zu einem HTTPS-Server. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_PINNEDPUBLICKEY Setzt den festgesteckten (pinned) öffentlichen Schlüssel für den HTTPS-Proxy. Die Zeichenkette kann der Dateiname des festgesteckten öffentlichen Schlüssels sein. Das erwartete Dateiformat ist "PEM" oder "DER". Die Zeichenkette kann ebenfalls eine beliebige Anzahl von Base64-kodierten SHA256-Hashwerten enthalten, denen "sha256://" vorangestellt, und die durch ";" getrennt sind. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLCERT Der Dateiname des Client-Zertifikats, das zur Verbindung mit dem HTTPS-Proxy verwendet wird. Das Standardformat ist "P12" bei Secure Transport, und "PEM" bei anderen Engines, kann aber mit CURLOPT_PROXY_SSLCERTTYPE geändert werden. Bei Verwendung von NSS oder Secure Transport kann es ebenfalls der Spitzname des Zertifikats sein, das zur Authentifizierung verwendet werden soll, wie in der Sicherheitsdatenbank hinterlegt. Soll eine Datei im aktuellen Verzeichnis verwendet werden, sollte sie mit einem "./"-Präfix angegeben werden, um Verwechslungen mit einem Spitznamen zu vermeiden. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLCERTTYPE Das Format des Client-Zertifikats, das zur Verbindung mit dem HTTPS-Proxy verwendet wird. Unterstützte Formate sind "PEM" und "DER", außer bei Secure Transport. OpenSSL (Version 0.9.3 und später) und Secure Transport (unter iOS 5 oder später, oder OS X 10.7 oder später) unterstützen ebenso "P12" für PKCS#12-kodierte Dateien. Der Standardwert ist "PEM". Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSL_CIPHER_LIST Die Liste von Chiffren, die zur Verbindung mit dem HTTPS-Proxy verwendet wird. Die Liste muss syntaktisch korrekt sein; sie besteht aus einer oder mehreren Chiffre-Zeichenketten, die durch Doppelpunkt getrennt sind. Kommas und Leerzeichen sind ebenfalls als Trennzeichen erlaubt, aber normalerweise werden Doppelpunkte verwendet; !, - und + können als Operatoren verwendet werden. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLS13_CIPHERS Die Liste von Chiffre-Folgen, die für die TLS 1.3 Verbindung zu einem Proxy verwendet werden. Die Liste muss syntaktisch korrekt sein; sie besteht aus einer oder mehreren Chiffre-Folgen-Zeichenketten, die durch Doppelpunkt getrennt sind. Die Option wird zurzeit nur verwendet, wenn curl mit OpenSSL 1.1.1 oder später kompiliert wurde. Wird ein anderes SSL-Backend verwendet, kann versucht werden die Chiffre-Folgen unter Verwendung der CURLOPT_PROXY_SSL_CIPHER_LIST Option zu setzen. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.61.0. Verfügbar wenn mit OpenSSL >= 1.1.1 kompiliert.
CURLOPT_PROXY_SSLKEY Der Dateiname des privaten Schlüssels, der für die Verbindung zum HTTPS-Proxy verwendet wird. Das Standardformat ist "PEM" und kann mit CURLOPT_PROXY_SSLKEYTYPE geändert werden. (nur für iOS und Mac OS X) Diese Option wird ignoriert, wenn curl mit Secure Transport kompiliert wurde. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0. Verfügbar wenn beim Kompilieren TLS aktivert war.
CURLOPT_PROXY_SSLKEYTYPE Das Format des privaten Schlüssels. Unterstützte Formate sind "PEM", "DER" und "ENG". Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_PASSWORD Das Passwort, das für die TLS-Authentifizierungsmethode, die mit der CURLOPT_PROXY_TLSAUTH_TYPE Option angegeben wurde, verwendet werden soll. Erfordert, dass die CURLOPT_PROXY_TLSAUTH_USERNAME Option ebenfalls angegeben wird. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_TYPE Die Methode der TLS-Authentifizierung, die für die HTTPS-Verbindung verwendet wird. Die unterstützte Methode is "SRP".

Hinweis:

Die Secure Remote Password (SRP) Authentifizierung für TLS bietet gegenseitige Authentifizierung, wenn beide Seiten ein geteiltes Geheimnis (shared secret) haben. Um TLS-SRP zu verwenden, müssen ebenfalls die CURLOPT_PROXY_TLSAUTH_USERNAME und CURLOPT_PROXY_TLSAUTH_PASSWORD Optionen gesetzt werden.

Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_USERNAME Der Benutzername für die HTTPS-Proxy TLS-Authentifizierungsmethode, die mit der CURLOPT_PROXY_TLSAUTH_TYPE Option angegeben wurde. Erfordert, dass die CURLOPT_PROXY_TLSAUTH_PASSWORD Option ebenfalls angegeben wird. Verfügbar seit PHP 7.3.0 and libcurl >= cURL 7.52.0.
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_SASL_AUTHZID Die Autorisierungskennung (authzid) für die Übertragung. Gilt nur für den Authentifizierungsmechanismus PLAIN SASL, wo sie optional ist. Wird nichts angegeben, wird nur die durch den Benutzernamen angegebene Authentifizierungskennung (authcid) zusammen mit dem Passwort an den Server gesendet. Wenn die authzid nicht angegeben wurde, leitet der Server die authzid von der authcid ab und verwendet sie intern.
CURLOPT_SERVICE_NAME Der Name des Authentifizierungsdienstes. Hinzugefügt in cURL 7.43.0. Verfügbar seit PHP 7.0.7.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 Eine Zeichenkette, die 32 hexadezimale Ziffern enthält. Die Zeichenkette sollte die MD5 Prüfsumme des öffentlichen Schlüssels des Remote-Hosts sein. libcurl wird die Verbindung zum Host zurückweisen, falls die Prüfsummen nicht übereinstimmen. Diese Option gilt nur für SCP und SFTP Übertragungen. Hinzugefügt in cURL 7.17.1.
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 Der öffentliche Schlüssel des entfernten Hosts in Form eines Base64-kodierten SHA256-Hashes. Wenn der angegebene Hash nicht mit dem Hash des entfernten Hosts übereinstimmt, schlägt die Übertragung fehl.
CURLOPT_SSH_PUBLIC_KEYFILE Der Dateiname des öffentlichen Schlüssels. Wenn nicht gesetzt, nimmt libcurl $HOME/.ssh/id_dsa.pub an, falls die HOME Umgebungsvariable gesetzt ist, und andernfalls "id_dsa.pub" im aktuellen Verzeichnis. Hinzugefügt in cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE Der Dateiname des privaten Schlüssels. Wenn nicht gesetzt, nimmt libcurl $HOME/.ssh/id_dsa an, falls die HOME Umgebungsvariable gesetzt ist, und andernfalls "id_dsa" im aktuellen Verzeichnis. Wenn die Datei passwort geschützt ist, muss das Passwort mit CURLOPT_KEYPASSWD bestimmt werden. Hinzugefügt in cURL 7.16.1.
CURLOPT_SSL_CIPHER_LIST Eine Liste der für SSL zulässigen Chiffren. RC4-SHA und TLSv1 sind zulässig.
CURLOPT_SSL_EC_CURVES Eine durch Doppelpunkte getrennte Liste von elliptischen Kurvenalgorithmen. Zum Beispiel ist X25519:P-521 eine gültige Liste von zwei elliptischen Kurven. Diese Option definiert die Schlüsselaustauschalgorithmen des Clients im SSL-Handshake, wenn das SSL-Backend, für das cURL gebaut wurde, dies unterstützt.
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. Von OpenSSL 0.9.3 an wird "P12" (für PKCS#12-kodierte Dateien) ebenfalls unterstützt. 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 benötigt wird.

Hinweis:

Da diese Option sensible Daten enthält, sollte das PHP-Skript 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_TLS13_CIPHERS Die Liste von Chiffre-Folgen, die für die TLS 1.3 Verbindung verwendet werden. Die List muss syntaktisch korrekt sein; sie besteht aus einer oder mehreren Chiffre-Folgen-Zeichenketten, die durch Doppelpunkt getrennt sind. Die Option wird zurzeit nur verwendet, wenn curl mit OpenSSL 1.1.1 oder später kompiliert wurde. Wird ein anderes SSL-Backend verwendet, kann versucht werden die TLS 1.3 Chiffre-Folgen unter Verwendung der CURLOPT_SSL_CIPHER_LIST Option zu setzen. Verfügbar seit PHP 7.3.0 und libcurl >= cURL 7.61.0. Verfügbar wenn mit OpenSSL >= 1.1.1 kompiliert.
CURLOPT_UNIX_SOCKET_PATH Aktiviert die Verwendung von Unix-Domain-Sockets als Verbindsendpunkt, und setzt den Pfad auf den angegebenen String. Hinzugefügt in cURL 7.40.0. Verfügbar seit PHP 7.0.7.
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_USERNAME Der für die Authentifizierung zu verwendende Benutzername. Hinzugefügt in cURL 7.19.1.
CURLOPT_PASSWORD Das Passwort, das für die Authentifizierung verwendet wird. Hinzugefügt in cURL 7.19.1.
CURLOPT_USERPWD Benutzername und Passwort im Format "[benutzername]:[passwort]"
CURLOPT_XOAUTH2_BEARER Gibt das OAuth 2.0 Access-Token an. Hinzugefügt in cURL 7.33.0. Verfügbar seit PHP 7.0.7.

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

Option Wert für value Anmerkungen
CURLOPT_CONNECT_TO Verbinde zu einem bestimmten Host und Port anstatt dem Host und Port, der in der URL angegeben ist. Erwartet ein Array von Zeichenketten im Format HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT. Hinzugefügt in cURL 7.49.0. Verfügbar seit PHP 7.0.7.
CURLOPT_HTTP200ALIASES Ein Array von HTTP-200-Status die als gültige Antoworten 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_PROXYHEADER Ein Array von benutzerdefinierten HTTP-Headern, die an Proxies gesendet werden sollen. Hinzugefügt in cURL 7.37.0. Verfügbar seit PHP 7.0.7.
CURLOPT_QUOTE Ein Array von FTP-Kommandos, die vor dem FTP-Request auf dem Server ausgeführt werden sollen.
CURLOPT_RESOLVE Nutze eine benutzerdefinierte Adresse für eine bestimmte Host und Port-Kombination Ein Array von Hostname-, Port- und IP-Adressen-Zeichenketten, wobei jedes Element durch einen Doppelpunkt getrennt ist; im Format: array("example.com:80:127.0.0.1") Hinzugefügt in cURL 7.21.3.

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 der Name einer gültigen Funktion oder eine Closure sein.

Option Wert für value Anmerkungen
CURLOPT_HEADERFUNCTION Ein Callback, der 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 Ein Callback, der 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. Entfernt in PHP 7.3.0.
CURLOPT_PROGRESSFUNCTION

Ein Callback, die fünf Parameter erwartet. Der erste ist die cURL-Resource, der zweite ist die erwartete Gesamtanzahl von Bytes, die in dieser Übertragung herunter geladen werden, der dritte ist die Anzahl von Bytes die bisher herunter geladen wurden, der vierte ist die erwartete Gesamtanzahl von Bytes, die bei dieser Übertragung hochgeladen werden, und der fünfte ist die Anzahl von Bytes, die bisher hochgeladen wurden.

Hinweis:

Der Callback wird nur aufgerufen, wenn die CURLOPT_NOPROGRESS Option auf false gesetzt ist.

Ein Rückgabewert ungleich 0 bricht die Übertragung ab. In diesem Fall setzt der Transfer einen CURLE_ABORTED_BY_CALLBACK Fehler.

 
CURLOPT_READFUNCTION Ein Callback, der drei Parameter erwartet. Der erste ist die cURL- Resource, der zweite ist eine Stream-Resource, die cURL durch die Option CURLOPT_INFILE zur Verfügung gestellt wird, und der dritte ist die Höchstmenge von Daten die gelesen werden. Der Callback muss eine Zeichenkette mit einer Länge gleich oder kleiner als der angeforderten Datenmenge zurückgeben, typischerweise durch Lesen von der übergebenen Stream-Resource. Er soll eine leere Zeichenkette zurückgeben, um EOF zu signalisieren.  
CURLOPT_WRITEFUNCTION Ein Callback, der 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!  
CURLOPT_XFERINFOFUNCTION Ein Callback, der zwei Parameter erwartet. Dient einem ähnlichen Zweck wie CURLOPT_PROGRESSFUNCTION, ist aber moderner und die bevorzugte Option von cURL. Hinzugefügt in 7.32.0. Verfügbar ab PHP 8.2.0.

Andere Werte:

Option Wert für value
CURLOPT_SHARE Ein Ergebnis von curl_share_init(). Veranlasst das cURL-Handle die Daten des geteilten Handle zu verwenden.

Rückgabewerte

Gibt bei Erfolg true zurück. Bei einem Fehler wird false zurückgegeben.

Changelog

Version Beschreibung
8.0.0 handle erwartet nun eine CurlHandle-Instanz; vorher wurde eine Ressource erwartet.
7.3.15, 7.4.3 CURLOPT_HTTP09_ALLOWED wurde eingeführt.
7.3.0 CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPT_PRE_PROXY, CURLOPT_PROXY_CAINFO, CURLOPT_PROXY_CAPATH, CURLOPT_PROXY_CRLFILE, CURLOPT_PROXY_KEYPASSWD, CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPT_PROXY_SSLCERT, CURLOPT_PROXY_SSLCERTTYPE, CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPT_PROXY_SSLKEY, CURLOPT_PROXY_SSLKEYTYPE, CURLOPT_PROXY_SSL_OPTIONS, CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPT_PROXY_SSLVERSION, CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPT_SOCKS5_AUTH, CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPT_HAPROXYPROTOCOL, CURLOPT_PROXY_TLS13_CIPHERS, CURLOPT_SSH_COMPRESSION, CURLOPT_TIMEVALUE_LARGE und CURLOPT_TLS13_CIPHERS wurden eingeführt.
7.0.7 CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT und CURLSSLOPT_NO_REVOKE wurden 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($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

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

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

add a note add a note

User Contributed Notes 124 notes

up
199
rmckay at webaware dot com dot au
11 years ago
Please everyone, stop setting CURLOPT_SSL_VERIFYPEER to false or 0. If your PHP installation doesn't have an up-to-date CA root certificate bundle, download the one at the curl website and save it on your server:

http://curl.haxx.se/docs/caextract.html

Then set a path to it in your php.ini file, e.g. on Windows:

curl.cainfo=c:\php\cacert.pem

Turning off CURLOPT_SSL_VERIFYPEER allows man in the middle (MITM) attacks, which you don't want!
up
46
joey
8 years ago
It is important that anyone working with cURL and PHP keep in mind that not all of the CURLOPT and CURLINFO constants are documented. I always recommend reading the cURL documentation directly as it sometimes contains better information. The cURL API in tends to be fubar as well so do not expect things to be where you would normally logically look for them.

curl is especially difficult to work with when it comes to cookies. So I will talk about what I found with PHP 5.6 and curl 7.26.

If you want to manage cookies in memory without using files including reading, writing and clearing custom cookies then continue reading.

To start with, the way to enable in memory only cookies associated with a cURL handle you should use:

    curl_setopt($curl, CURLOPT_COOKIEFILE, "");

cURL likes to use magic strings in options as special commands. Rather than having an option to enable the cookie engine in memory it uses a magic string to do that. Although vaguely the documentation here mentions this however most people like me wouldn't even read that because a COOKIEFILE is the complete opposite of what we want.

To get the cookies for a curl handle you can use:

    curl_getinfo($curl, CURLINFO_COOKIELIST);

This will give an array containing a string for each cookie. It is tab delimited and unfortunately you will have to parse it yourself if you want to do anything beyond copying the cookies.

To clear the in memory cookies for a cURL handle you can use:

    curl_setopt($curl, CURLOPT_COOKIELIST, "ALL");

This is a magic string. There are others in the cURL documentation. If a magic string isn't used, this field should take a cookie in the same string format as in getinfo for the cookielist constant. This can be used to delete individual cookies although it's not the most elegant API for doing so.

For copying cookies I recommend using curl_share_init.

You can also copy cookies from one handle to another like so:

    foreach(curl_getinfo($curl_a, CURLINFO_COOKIELIST) as $cookie_line)
        curl_setopt($curl, CURLOPT_COOKIELIST, $cookie_line);

An inelegant way to delete a cookie would be to skip the one you don't want.

I only recommend using COOKIELIST with magic strings because the cookie format is not secure or stable. You can inject tabs into at least path and name so it becomes impossible to parse reliably. If you must parse this then to keep it secure I recommend prohibiting more than 6 tabs in the content which probably isn't a big loss to most people.

A the absolute minimum for validation I would suggest:

    /^([^\t]+\t){5}[^\t]+$/D

Here is the format:

    #define SEP  "\t"  /* Tab separates the fields */

    char *my_cookie =
      "example.com"    /* Hostname */
      SEP "FALSE"      /* Include subdomains */
      SEP "/"          /* Path */
      SEP "FALSE"      /* Secure */
      SEP "0"          /* Expiry in epoch time format. 0 == Session */
      SEP "foo"        /* Name */
      SEP "bar";       /* Value */
up
6
Victor Jerlin
14 years ago
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.
up
8
ohcc at 163 dot com
6 years ago
This is howto upload an existing file to an FTP server with cURL in PHP.

You should remember that CURLOPT_URL should contain the file's basename to save on the FTP server. For example, if you upload hello.txt to ftp://www.wuxiancheng.cn/text/, CURLOPT_URL should be ftp://www.wuxiancheng.cn/text/hello.txt rather than ftp://www.wuxiancheng.cn/text/, otherwise you will get an error message like "Uploading to a URL without a file name! " when you call curl_error();

<?php
    $ch
= curl_init();
   
$filepath = 'D:\Web\www\wuxiancheng.cn\hello.txt';
   
$basename = pathInfo($filepath, PATHINFO_BASENAME);
   
$filesize = fileSize($filepath);
   
curl_setopt_array(
       
$ch,
        array(
           
CURLOPT_URL => 'ftp://www.wuxiancheng.cn/text/' . $basename,
           
CURLOPT_USERPWD => 'USERNAME:PASSWORD',
           
CURLOPT_PROTOCOLS => CURLPROTO_FTP,
           
CURLOPT_UPLOAD => true,
           
CURLOPT_INFILE => $filepath,
           
CURLOPT_INFILESIZE => $filesize,
           
CURLOPT_RETURNTRANSFER => true,
           
CURLOPT_HEADER => false,
        )
    );
   
curl_exec($ch);
   
$message = curl_errno($ch) === CURLE_OK ? 'success' : 'failure';
    echo
$message;
?>
up
9
ashw1 - at - no spam - post - dot - cz
16 years ago
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);
    }

?>
up
26
Philippe dot Jausions at 11abacus dot com
17 years ago
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
up
25
sgamon at yahoo dot com
15 years ago
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/
up
14
dweingart at pobox dot com
20 years ago
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
up
10
JScott jscott401 at gmail dot com
13 years ago
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
up
36
Ed Cradock
14 years ago
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.
up
28
Steve Kamerman
12 years ago
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature"  on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached".  The explanation for this behavior is:

"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."

What this means to PHP developers is "You can use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"

The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.

The solution is to disable signals using CURLOPT_NOSIGNAL.  Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

<?php
if (!isset($_GET['foo'])) {
       
// Client
       
$ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
       
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
       
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
       
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
       
$data = curl_exec($ch);
       
$curl_errno = curl_errno($ch);
       
$curl_error = curl_error($ch);
       
curl_close($ch);

        if (
$curl_errno > 0) {
                echo
"cURL Error ($curl_errno): $curl_error\n";
        } else {
                echo
"Data received: $data\n";
        }
} else {
       
// Server
       
sleep(10);
        echo
"Done.";
}
?>
up
8
jancister at gmail dot com
9 years ago
Please note that if you want to handle progress using CURLOPT_PROGRESSFUNCTION option, you need to take into consideration what version of PHP are you using. Since version 5.5.0, compatibility-breaking change was introduced in number/order of the arguments passed to the callback function, and cURL resource is now passed as first argument.

Prior to version 5.5.0:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
   
// Handle progress
}
?>

From version 5.5.0:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
   
// Handle progress
}
?>

However, if your code needs to be compatible with PHP version both before and after 5.5.0, consider adding a version check:
<?php
// ...
curl_setopt($resource, CURLOPT_PROGRESSFUNCTION, 'progressCallback');
curl_setopt($resource, CURLOPT_NOPROGRESS, false);
// ...
function progressCallback($resource, $download_size = 0, $downloaded = 0, $upload_size = 0, $uploaded = 0)
{
  
/**
    * $resource parameter was added in version 5.5.0 breaking backwards compatibility;
    * if we are using PHP version lower than 5.5.0, we need to shift the arguments
    * @see http://php.net/manual/en/function.curl-setopt.php#refsect1-function.curl-setopt-changelog
    */
   
if (version_compare(PHP_VERSION, '5.5.0') < 0) {
       
$uploaded = $upload_size;
       
$upload_size = $downloaded;
       
$downloaded = $download_size;
       
$download_size = $resource;
    }

   
// Handle progress
}
?>
up
10
anderseta at gmail dot com
13 years ago
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.

write_function must return the exact number of bytes of the string, so you can return a value with mb_strlen.
up
35
jade dot skaggs at gmail dot com
16 years ago
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);
        }

?>
up
13
PHP at RHaworth dot net
12 years ago
When CURLOPT_FOLLOWLOCATION and CURLOPT_HEADER are both true and redirect/s have happened then the header returned by curl_exec() will contain all the headers in the redirect chain in the order they were encountered.
up
14
luca dot manzo at bbsitalia dot com
18 years ago
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
up
11
yann dot corno at free dot fr
21 years ago
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
up
14
badman
10 years ago
Many hosters use PHP safe_mode or/and open_basedir, so you can't use CURLOPT_FOLLOWLOCATION. If you try, you see message like this:
CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in [you script name & path] on line XXX

First, I try to use zsalab function (http://us2.php.net/manual/en/function.curl-setopt.php#102121) from this page, but for some reason it did not work properly. So, I wrote my own.

It can be use instead of curl_exec. If server HTTP response codes is 30x, function will forward the request as long as the response is not different from 30x (for example, 200 Ok). Also you can use POST.

function curlExec(/* Array */$curlOptions='', /* Array */$curlHeaders='', /* Array */$postFields='')
{
  $newUrl = '';
  $maxRedirection = 10;
  do
  {
    if ($maxRedirection<1) die('Error: reached the limit of redirections');

    $ch = curl_init();
    if (!empty($curlOptions)) curl_setopt_array($ch, $curlOptions);
    if (!empty($curlHeaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
    if (!empty($postFields))
    {
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    }
   
    if (!empty($newUrl)) curl_setopt($ch, CURLOPT_URL, $newUrl); // redirect needed
   
    $curlResult = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    if ($code == 301 || $code == 302 || $code == 303 || $code == 307)
    {
      preg_match('/Location:(.*?)\n/', $curlResult, $matches);
      $newUrl = trim(array_pop($matches));
      curl_close($ch);

      $maxRedirection--;
      continue;
    }
    else // no more redirection
    {
      $code = 0;
      curl_close($ch);
    }
  }
  while($code);
  return $curlResult;
}
up
22
joeterranova at gmail dot com
13 years ago
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);
?>
up
2
Tyranoweb
14 years ago
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;
        }
    }
?>
up
10
S\
13 years ago
When using CURLOPT_POSTFIELDS with an array as parameter, you have to pay high attention to user input. Unvalidated user input will lead to serious security issues.

<?php

/**
* test.php:
*/
$ch = curl_init('http://example.com');

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, array(
   
'foo' => $_GET['bar']
));

curl_exec($ch);

?>

Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com.
Make sure you remove the leading "@" from user input.
up
4
michaeledwards.com
18 years ago
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);
?>
up
2
paczor
17 years ago
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');
?>
up
8
Aaron Wells
9 years ago
If you use cURL to fetch user-supplied URLs (for instance, in a web-based RSS aggregator), be aware of the risk of server-side request forgery (SSRF). This is an attack where the user takes advantage of the fact that cURL requests are sent from the web server itself, to reach network locations they wouldn't be able to reach from outside the network.

For instance, they could enter a "http://localhost" URL, and access things on the web server via "localhost". Or, "ftp://localhost". cURL supports a lot of protocols!

If you are using CURLOPT_FOLLOWLOCATION, the malicious URL could be in a redirect from the original request. cURL also will follow redirect headers to other protocols! (303 See Other; Location: ftp://localhost).

So if you're using cURL with user-supplied URLs, at the very least use CURLOPT_PROTOCOLS (which also sets CURLOPT_REDIR_PROTOCOLS), and either disable CURLOPT_FOLLOWLOCATION or use the "SafeCurl" library to safely follow redirects.
up
2
php at miggy dot org
17 years ago
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.
up
13
regan dot corey at gmail dot com
11 years ago
I spent a couple of days trying to POST a multi-dimensional array of form fields, including a file upload, to a remote server to update a product. Here are the breakthroughs that FINALLY allowed the script to run as desired.

Firstly, the HTML form used input names like these:
<input type="text" name="product[name]" />
<input type="text" name="product[cost]" />
<input type="file" name="product[thumbnail]" />
in conjunction with two other form inputs not part of the product array
<input type="text" name="method" value="put" />
<input type="text" name="mode" />

I used several cURL options, but the only two (other than URL) that mattered were:
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
Pretty standard so far.
Note: headers didn't need to be set, cURL automatically sets headers (like content-type: multipart/form-data; content-length...) when you pass an array into CURLOPT_POSTFIELDS.
Note: even though this is supposed to be a PUT command through an HTTP POST form, no special PUT options needed to be passed natively through cURL. Options such as
curl_setopt($handle, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT', 'Content-Length: ' . strlen($fields)));
or
curl_setopt($handle, CURLOPT_PUT, true);
or
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "PUT);
were not needed to make the code work.

The fields I wanted to pass through cURL were arranged into an array something like this:
$postfields = array("method" => $_POST["method"],
                    "mode" => $_POST["mode"],
                    "product" => array("name" => $_POST["product"],
                                        "cost" => $_POST["product"]["cost"],
                                        "thumbnail" => "@{$_FILES["thumbnail"]["tmp_name"]};type={$_FILES["thumbnail"]["type"]}")
                    );

-Notice how the @ precedes the temporary filename, this creates a link so PHP will upload/transfer an actual file instead of just the file name, which would happen if the @ isn't included.
-Notice how I forcefully set the mime-type of the file to upload. I was having issues where images filetypes were defaulting to octet-stream instead of image/png or image/jpeg or whatever the type of the selected image.

I then tried passing $postfields straight into curl_setopt($this->handle, CURLOPT_POSTFIELDS, $postfields); but it didn't work.
I tried using http_build_query($postfields); but that didn't work properly either.
In both cases either the file wouldn't be treated as an actual file and the form data wasn't being sent properly. The problem was HTTP's methods of transmitting arrays. While PHP and other languages can figure out how to handle arrays passed via forms, HTTP isn't quite as sofisticated. I had to rewrite the $postfields array like so:
$postfields = array("method" => $_POST["method"],
                    "mode" => $_POST["mode"],
                    "product[name]" => $_POST["product"],
                    "product[cost]" => $_POST["product"]["cost"],
                    "product[thumbnail]" => "@{$_FILES["thumbnail"]["tmp_name"]}");
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);

This, without the use of http_build_query, solved all of my problems. Now the receiving host outputs both $_POST and $_FILES vars correctly.
up
11
joelhy
8 years ago
Please notice that CURLINFO_HEADER_OUT and CURLOPT_VERBOSE option does not work together:
"When CURLINFO_HEADER_OUT is set to TRUE than CURLOPT_VERBOSE does not work."(from https://bugs.php.net/bug.php?id=65348).
This took me an hour or two to figure it out.
up
10
c00lways at gmail dot com
16 years ago
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 ;)
up
11
Ojas Ojasvi
16 years ago
<?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
up
8
Pawel Antczak
14 years ago
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.
up
10
Chris at PureFormSolutions dot com
14 years ago
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.
up
4
rob at infoglobe dot net
16 years ago
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.
up
13
saidk at phirebranding dot com
15 years ago
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!
up
4
skyogre __at__ yandex __dot__ ru
18 years ago
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) );

?>
up
7
fnjordy at gmail dot com
15 years ago
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.
up
10
mr at coder dot tv
17 years ago
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
up
9
zsalab
13 years ago
Handling redirections with curl if safe_mode or open_basedir is enabled. The function working transparent, no problem with header and returntransfer options. You can handle the max redirection with the optional second argument (the function is set the variable to zero if max redirection exceeded).
Second parameter values:
- maxredirect is null or not set: redirect maximum five time, after raise PHP warning
- maxredirect is greather then zero: no raiser error, but parameter variable set to zero
- maxredirect is less or equal zero: no follow redirections

<?php
function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
   
$mr = $maxredirect === null ? 5 : intval($maxredirect);
    if (
ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
       
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
       
curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
    } else {
       
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        if (
$mr > 0) {
           
$newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

           
$rch = curl_copy_handle($ch);
           
curl_setopt($rch, CURLOPT_HEADER, true);
           
curl_setopt($rch, CURLOPT_NOBODY, true);
           
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
           
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
            do {
               
curl_setopt($rch, CURLOPT_URL, $newurl);
               
$header = curl_exec($rch);
                if (
curl_errno($rch)) {
                   
$code = 0;
                } else {
                   
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                    if (
$code == 301 || $code == 302) {
                       
preg_match('/Location:(.*?)\n/', $header, $matches);
                       
$newurl = trim(array_pop($matches));
                    } else {
                       
$code = 0;
                    }
                }
            } while (
$code && --$mr);
           
curl_close($rch);
            if (!
$mr) {
                if (
$maxredirect === null) {
                   
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
                } else {
                   
$maxredirect = 0;
                }
                return
false;
            }
           
curl_setopt($ch, CURLOPT_URL, $newurl);
        }
    }
    return
curl_exec($ch);
}
?>
up
1
JM
4 years ago
Note that CURLOPT_TIMEOUT takes integers, so you cannot use it to set a timeout smaller than one second.
up
1
cmatiasvillanueva at gmail dot com
6 years ago
What is not mentioned in the documentation is that if you want to set  a local-port or local-port-range to establish a connection is possible by adding   CURLOPT_LOCALPORT and CURLOPT_LOCALPORTRANGE options.  

Ex:
$conn=curl_init ('example.com');
curl_setopt($conn, CURLOPT_LOCALPORT, 35000);
curl_setopt($conn, CURLOPT_LOCALPORTRANGE, 200);

CURLOPT_LOCALPORT: This sets the local port number of the socket used for the connection.

CURLOPT_LOCALPORTRANGE:  The range argument is the number of attempts libcurl will make to find a working local port number. It starts with the given CURLOPT_LOCALPORT and adds one to the number for each retry. Setting this option to 1 or below will make libcurl do only one try for the exact port number.

Interface can be also configured using CURLOPT_INTERFACE:

Ex:

curl_setopt($conn,  CURLOPT_INTERFACE, "eth1");
up
4
Martin K.
10 years ago
If you only want to enable cookie handling and you don't need to save the cookies for a separate session, just set CURLOPT_COOKIEFILE to an empty string.  I was given the advice to use php://memory but that did not seem to have the same effect.

Although this is stated in the documentation I thought it was worth reiterating since it cause me so much trouble.
up
9
Adam Monsen
12 years ago
CURLOPT_POST must be left unset if you want the Content-Type header set to "multipart/form-data" (e.g., when CURLOPT_POSTFIELDS is an array). If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to TRUE, Content-Length will be -1 and most sane servers will reject the request. If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to FALSE, cURL will send a GET request.
up
4
scy-phpmanual at scytale dot name
13 years ago
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.
up
2
juozaspo at gmail dot com
11 years ago
I've created an example that gets the file on url passed to script and outputs it to the browser.

<?php
//get the file (e.g. image) and output it to the browser
$ch = curl_init(); //open curl handle
curl_setopt($ch, CURLOPT_URL, $_GET['url']); //set an url
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //do not output directly, use variable
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); //do a binary transfer
curl_setopt($ch, CURLOPT_FAILONERROR, 1); //stop if an error occurred
$file=curl_exec($ch); //store the content in variable
if(!curl_errno($ch))
{
   
//send out headers and output
   
header ("Content-type: ".curl_getinfo($ch, CURLINFO_CONTENT_TYPE)."");
   
header ("Content-Length: ".curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD)."");
    echo
$file;
} else echo
'Curl error: ' . curl_error($ch);
curl_close($ch); //close curl handle
?>

p.s. Make sure that there're no new lines before and after code or script may not work.
up
2
Joey Hewitt
11 years ago
Note that if you put a certificate chain in a PEM file, the certificates need to be ordered so that each certificate is followed by its issuer (i.e., root last.)

Source: http://publib.boulder.ibm.com/tividd/td/ITIM/SC32-1493-00/en_US/HTML/im451_config09.htm
up
2
mw+php dot net at lw-systems dot de
11 years ago
The description of the use of the CURLOPT_POSTFIELDS option should be emphasize, that using POST with HTTP/1.1 with cURL implies the use of a "Expect: 100-continue" header. Some web servers will not understand the handling of chunked transfer of post data.

To disable this behavior one must disable the use of the "Expect:" header with

    curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
up
2
gskluzacek at gmail dot com
13 years ago
FYI... unless you specifically set the user agent, no user agent will be sent in your request as there is no default value like some of the other options.

As others have said, not sending a user agent may cause you to not  get the results that you expected, e.g., 0 byte length content, different content, etc.
up
3
Sylvain R
14 years ago
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');

?>
up
5
eion at bigfoot dot com
17 years ago
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;
        }
    }
?>
up
2
clint at fewbar dot com
13 years ago
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);

?>
up
5
Dustin Hawkins
18 years ago
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.
up
11
Richard
9 years ago
CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6) only work for PHP versions using curl 7.34 or newer.
up
3
markandrewslade at gmail dot com
7 years ago
Contrary to the documentation, CURLOPT_STDERR should be set to a handle to the file you want to write to, not the file's location.
up
5
m at mar dot lt
11 years ago
Be careful when changing CURLOPT_SSL_VERIFYHOST or other options to true (boolean). It may cause insecure behavior [1]

This is because boolean true casts into integer 1, and CURLOPT_SSL_VERIFYHOST = 1 is not secure behavior.

The *correct* value here is CURLOPT_SSL_VERIFYHOST = 2. By setting this value equal to 1 the peer certificate must contain a Common Name field, but it doesn't matter what name it says.

[1] Martin Georgiev and Subodh Iyengar and Suman Jana and Rishita Anubhai and Dan Boneh and Vitaly Shmatikov, The most dangerous code in the world: validating SSL certificates in non-browser software, ACM CCS '12, pp. 38-49, 2012
up
4
fred at themancan dot com
15 years ago
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.
up
5
Madcat
10 years ago
If you have a mixture of strings starting with @ (at character) and files in CURLOPT_POSTFIELDS you have a problem (such as posting a tweet with attached media) because curl tries to interpret anything starting with @ as a file.

<?php

$postfields
= array(
   
'upload_file' => '@file_to_upload.png',
   
'upload_text' => '@text_to_upload'
);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://example.com/upload-test');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postfields);
curl_exec($curl);
curl_close($curl);

?>

To get around this, prepend the text string with the NULL character like so:

<?php
    $postfields
= array(
       
'upload_file' => '@file_to_upload.png',
       
'upload_text' => sprintf("\0%s", '@text_to_upload')
    );
?>

Original source: http://bit.ly/AntMle
up
3
ron at ttvavanti dot nl
19 years ago
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).
up
4
rob
14 years ago
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.
up
3
tceburashka at yandex dot ru
7 years ago
Send body file use RFC7578 ("multipart/form-data")

// class contain file
class oFile
{
     private $name;
     private $mime;
     private $content;

     public function __construct($name, $mime=null, $content=null)
      {
          if(is_null($content))
           {
               $info = pathinfo($name);
// check is exist and readable file
               if(!empty($info['basename']) && is_readable($name))
                {
                    $this->name = $info['basename'];
// get MIME
                    $this->mime = mime_content_type($name);
// load file
                    $content = file_get_contents($name);
                    if($content!==false) $this->content = $content;
                        else throw new Exception('Don`t get content - "'.$name.'"');
                } else throw new Exception('Error param');
           } else
              {
                   $this->name = $name;
                   if(is_null($mime)) $mime = mime_content_type($name);
                   $this->mime = $mime;
                   $this->content = $content;
              };
      }

    public function Name() { return $this->name; }

    public function Mime() { return $this->mime; }

    public function Content() { return $this->content; }

};

// create body for POST request
class BodyPost
{
// part "multipart/form-data"
    public static function PartPost($name, $val)
     {
         $body = 'Content-Disposition: form-data; name="' . $name . '"';
// check instance of oFile
         if($val instanceof oFile)
          {
              $file = $val->Name();
              $mime = $val->Mime();
              $cont = $val->Content();

              $body .= '; filename="' . $file . '"' . "\r\n";
              $body .= 'Content-Type: ' . $mime ."\r\n\r\n";
              $body .= $cont."\r\n";
          } else $body .= "\r\n\r\n".urlencode($val)."\r\n";
         return $body;
     }

    public static function Get(array $post, $delimiter='-------------0123456789')
     {
         if(is_array($post) && !empty($post))
          {
              $bool = false;
              foreach($post as $val) if($val instanceof oFile) {$bool = true; break; };
              if($bool)
               {
                   $ret = '';
                   foreach($post as $name=>$val)
                       $ret .= '--' . $delimiter. "\r\n". self::PartPost($name, $val);
                   $ret .= "--" . $delimiter . "--\r\n";
               } else $ret = http_build_query($post);
          } else throw new \Exception('Error input param!');
         return $ret;
     }
};

$delimiter = '-------------'.uniqid();
$file = new oFile('sample.txt', 'text/plain', 'Content file');
$post = BodyPost::Get(array('field'=>'text', 'file'=>$file), $delimiter);

var_dump($post);

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://server/upload/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; boundary=' . $delimiter,
    'Content-Length: ' . strlen($post)));

curl_exec($ch);
up
2
tim dot php at ebw dot ca
20 years ago
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.
up
2
xektrum at gmail dot com
14 years ago
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.
up
2
ikendra at yken dot nospam dot org
18 years ago
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;
}
?>
up
3
dotpointer at gmail dot com
12 years ago
I noted something when using CURLOPT_POSTFIELDS in combination with arrays from PHP.

You may supply an array, but there may not be any sub-arrays in this array, as this will give Array-to-string-conversion notice.

Example:

<?php
$ch
= curl_init();

# this works
$data = array('name' => 'value');

# this gives "Notice: Array to string conversion..."
$data = array('name' => array('subname' => 'subvalue'));

curl_setopt($ch, CURLOPT_URL, 'http://localhost/test.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>
up
1
Joan
10 years ago
Using CURLOPT_NOPROXY to avoid using the proxy for some urls is very convenient.
For example when the page is trying to look for itself.
The parameter can be found at least in version 5.5.7, (probably earlier)
Unfortunately it's not present on debian wheezy (5.4.4) but it will be on jessie (it's already there)

A related bug: https://bugs.php.net/bug.php?id=53543
up
3
Tim Severien
12 years ago
I've been stuck when using the CURLOPT_CONNECTTIMEOUT_MS constant. In fact, on my PHP version (5.3.1) it's not a number but rather a string. Same thing for CURLOPT_TIMEOUT_MS.

I got this error: Warning: curl_setopt() expects parameter 2 to be long, string given

If you are experiencing simular problems, you can replace the constant with the actual number or (re)define the constant.

CURLOPT_TIMEOUT_MS should be 155
CURLOPT_CONNECTTIMEOUT_MS should be 156

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 2500); // error
curl_setopt($ch, 156, 2500); // problem solved
up
1
jID
15 years ago
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
up
1
shiplu at programmer dot net
10 years ago
CURLOPT_POST should be set before CURLOPT_POSTFIELDS. Otherwise you might encounter 411 Length required error.

Following code generates "411 Length Required" on nginx/1.1.15
<?php
curl_setopt
($ch, CURLOPT_POSTFIELDS, $postfields);
curl_setopt ($ch, CURLOPT_POST, 1);
?>

But this one works.

<?php
curl_setopt
($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
?>
up
1
anonymous
11 years ago
This may be not obvious, but if you specify the CURLOPT_POSTFIELDS and don't specify the CURLOPT_POST - it will still send POST, not GET (as you might think - since GET is default).
So the line:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

is synonym to:

curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Even if you set the options like this (in this order):

curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

it will send POST, since CURLOPT_POSTFIELDS is latter.
So if you want GET - make sure you don't have CURLOPT_POSTFIELDS specified somewhere.
up
1
heyrocker at yahoo dot com
18 years ago
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://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";
?>
up
2
ac at an dot y-co dot de
15 years ago
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, '2');
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
up
1
phpnet at wafflehouse dot de
18 years ago
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.
up
1
ROXORT at TGNOOB dot FR
18 years ago
<?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.
*/
?>
up
1
mavook at gmail dot com
16 years ago
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
?>
up
1
qeremy [atta] gmail [dotta] com
11 years ago
If you are trying to update something on your server and you need to handle this update operation by PUT;

<?php
curl_setopt
($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_PUT, 1);
?>

are "useless" without;

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
?>

Example;

Updating a book data in database identified by "id 1";

--cURL Part--
<?php
$data
= http_build_query($_POST);
// or
$data = http_build_query(array(
  
'name'  => 'PHP in Action',
  
'price' => 10.9
));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.localhost/rest/books/1");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // no need anymore
// or
// curl_setopt($ch, CURLOPT_PUT, 1); // no need anymore
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$ce = curl_exec($ch);
curl_close($ch);
print_r($ce);
?>

--API class--
<?php
public function putAction() {
    echo
"putAction() -> id: ". $this->_getParam('id') ."\n";
   
print_r($_POST);
   
// do stuff with post data
   
...
?>

--Output--
putAction() -> id: 15
Array
(
    [name] => PHP in Action
    [price] => 10.9
)

---Keywords--
rest, restfull api, restfull put, curl put, curl customrequest put
up
1
adrian at foeder dot de
11 years ago
if you want to do a GET request with additional body data it will become tricky not to implicitly change the request to a POST, like many notes below correctly state.
So to do the analogy of command line's

curl -XGET 'http://example.org?foo=bar' -d '<baz>some additional data</baz>'

in PHP you'll do, besides your other necessary stuff,

<?php
    curl_setopt
($curlHandle, CURLOPT_CUSTOMREQUEST, 'GET');
   
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, '<baz>some additional data</baz>');
?>

during my experiments, every other "similar" way, like e.g. CURLOPT_HTTPGET, didn't send the additional data or fell into POST.
up
1
qwertz182
3 years ago
As the "example #2 Uploading file" says it is deprecated as of PHP 5.5.0 but doesn't tell you how it's done right,
here is a really easy example using the CURLFile class:

<?php
$request
= [
   
'firstName' => 'John',
   
'lastName' => 'Doe',
   
'file' => new CURLFile('example.txt', 'text/plain') // or use curl_file_create()
];

$curlOptions = [
   
CURLOPT_URL => 'http://example.com/upload.php',
   
CURLOPT_POST => true,
   
CURLOPT_HEADER => false,
   
CURLOPT_RETURNTRANSFER => true,
   
CURLOPT_POSTFIELDS => $request,
];

$ch = curl_init();
curl_setopt_array($ch, $curlOptions);

$response = curl_exec($ch);
?>

This is just like posting a html form with an input[type=file] field.
The result on windows could look like this:

<?php
// $_POST
Array
(
    [
firstName] => John
   
[lastName] => Doe
)

// $_FILES
Array
(
    [
file] => Array
        (
            [
name] => example.txt
           
[type] => text/plain
           
[tmp_name] => C:\wamp64\tmp\php3016.tmp
           
[error] => 0
           
[size] => 14
       
)

)
?>

Since the request is an array (and not a string), curl will automatically encode the data as "multipart/form-data".
Please be aware that if you pass an invalid file path to CURLFile, setting the CURLOPT_POSTFIELDS option will fail.
So if you are using curl_setopt_array for setting the options at once, according to the manual, "If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.".
So you should make sure that the file exists or set CURLOPT_POSTFIELDS with curl_setopt() and check if it returns false and act accordingly.
up
1
urkle at outoforder dot cc
15 years ago
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER,array('Content-Type: application/json'));
?>
up
1
julien veneziano
13 years ago
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);
?>
up
0
joel at mojamail dot com
6 years ago
In the long documentation, it's easy to miss the fact that CURLOPT_POSTFIELDS will set the Content-Type to "multipart/form-data" (instead of the usual "application/x-www-form-urlencoded") IFF you supply an array (instead of a query string)!

Some servers will return weird errors (like "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104") for the wrong Content-Type, and you may waste many hours of time trying to figure out why!
up
-1
bash at noemailaddress dot com
5 years ago
Be sure not to set CURLOPT_POST to 1 (or True) if you are uploading a file, even if you are also providing textual Post data in your request. Took two hours to discover that including this option was the cause of my receiving script not having $_FILES set. The documentation explains it, but many examples around the web incorrectly include the CURLOPT_POST option in their example code. (Their examples only work because they happen to set this option first, and curl automatically resets it if you set CURLOPT_POSTFIELDS and it includes a file. Set your post fields first and then the CURLOPT_POST option however, and your code will not work.)

Per the documentation:
CURLOPT_POST: "TRUE to do a regular HTTP POST. This POST is the normal application/x-www-form-urlencoded kind, most commonly used by HTML forms. "
up
0
nabikaz at gmail dot com
7 years ago
About this post in here:
http://php.net/manual/en/function.curl-setopt.php#102121
>Handling redirections with curl if safe_mode or open_basedir is enabled.
>...
>function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null) {
>...
~~~~~~~~~~~~~
IMPORTANT:
This is not work if set "CURLOPT_FILE".
For resolve this issue, can return $ch instead of curl_exec($ch), and after then set CURLOPT_FILE and use curl_exec($ch).
up
-2
eric dot van dot eldik at peercode dot nl
5 years ago
When you get this error using a PUT request: "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104")

It could be caused by:
<?php
curl_setopt
($ch, CURLOPT_PUT, TRUE);
?>

Instead try:
<?php
curl_setopt
($ch, CURLOPT_CUSTOMREQUEST, "PUT");
?>
up
0
mikko dot rantalainen at peda dot net
8 years ago
If you need to do DELETE request, use CURLOPT_CUSTOMREQUEST with "DELETE" and use CURLOPT_POSTFIELDS for parameters. Do not put request parameters into the URL (GET-like) or bad things will happen (at least Apache+mod_php does not like such requests).
up
-1
steve at websmithery dot co dot uk
7 years ago
It may not be an issue which affects anyone, but I think it’s worth noting that using the CURLOPT_POSTFIELDS option has the side effect of setting the CURLOPT_POST option to TRUE.

When testing some code that required the post method, I commented out my CURLOPT_POST line to see how it failed and it didn't. Further investigation using curl_getinfo revealed that setting the CURLOPT_POSTFIELDS option was also setting the POST option.
up
0
lachlan at radelaide dot net
10 years ago
For those using CURLAUTH_NTLM, it may come to no surprise  that NTLM request will fail if you have set CURLOPT_FORBID_REUSE to true.

This is because NTLM authorisation is connect-based, not request-based. If the connection is not kept alive and re-used, cURL can never complete the request.

You may notice this if you get a 401 status code or max out the number of redirects.
up
-1
White Gandalf
9 years ago
to complement shiplu's  comment on the neccessary option sequence of CURLOPT_POST before CURLOPT_POSTFIELDS:

The crux is not some error on nginx, but that nothing at all will be send over the line by curl. Parameters set by a "CURLOPT_POSTFIELDS" option setting will be completely ignored, as long as no "CURLOPT_POST" has been encountered beforehand: Neigther the Content-Type header will be set/generated accordingly nor Content-Length nor any data will be send in the body.

When using curl_setopt_array, the sequence in the array matters as well.
up
0
S.F.
10 years ago
I spent a couple of days trying to upload a file using a curl post.

The problem I ran into was the filename had an '@' in the middle of it.  It turned out that at least on my system if I encoded the file path using the quoted_printable_encode() function the upload works.

I'm posting this in the hopes that it will help someone else, and for my own future reference.

Code:
<?php

$filepath
= '/tmp/test@example.txt';
$postdata['file'] = '@' . quoted_printable_encode($filepath);

//... supporting code.

$result = curl_exec($ch);

?>
I'm not exactly sure why this works when escaping the '@' doesn't work but it does for me.

If anyone can offer insight into why this works or a better way to handle the '@' symbol in a filename when using curl to upload I would love to hear it.

Thanks
up
-1
Martin K.
10 years ago
If you need to read page contents in between file downloads, while still using the same curl handle, you'll probably need this code:
<?php
    curl_setopt
($handle, CURLOPT_FILE, fopen('php://stdout','w'));   // 'php://output' didn't work for me
   
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);  // using CURLOPT_FILE sets this to false automatically
?>
up
0
miloshio at gmail dot com
11 years ago
Remember:

- 'Server-side' cookies exists as information even before they were set on browser agent(HTTP COOKIE HEADER),
- javascript cookies does NOT exists as information before they were set on browser agent,

so, if you're trying to save cookies using CURLOPT_COOKIEJAR to a local file, that cookie must be server - side cookie, otherwise you are wasting time, javascript-produced cookies only exists when client browser's JS interpreter set them.
up
0
ellert at _removeme_ vankoperen dot nl
11 years ago
If you are using curl to do a soap request and consistently get the following error back:
The server cannot service the request because the media type is unsupported.
You are sending the Content-type of soap 1.2 to a 1.1 server.
Soap 1.1 needs Content-Type: text/xml;
Soap 1.2 should have Content-Type: application/soap+xml;
up
0
v dot tverdun at gmail dot com
12 years ago
Make sure to set keys for array if passing to CURLOPT_POSTFIELDS.

<?php
//This can cause errors
$data = array('bar');

//Use this instead
$data = array('foo' => 'bar');

curl_setopt(CURLOPT_POSTFIELDS, $data);
?>
up
0
john dot david dot steele at gmail dot com
13 years ago
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);
?>
up
0
prohfesor at gmail dot com
13 years ago
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;
  }
?>
up
0
kavih7 at yahoo dot com
13 years ago
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!
up
0
sam at def dot reyssi dot net
13 years ago
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);
?>
up
0
starosielec at googlemail dot com
14 years ago
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) {
     
//...
    
}
  
//...
}
?>
up
0
Andrew
14 years ago
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.
up
0
ericbianchetti at gmail dot com
14 years ago
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
up
0
ashooner - - gmail , com
14 years ago
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.
up
0
w dot danford at electronics-software dot com
15 years ago
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.
up
0
Salil Kothadia
15 years ago
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);
?>
up
0
andrabr at gmail dot com
16 years ago
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...
up
0
mcbreen at gmail dot com
16 years ago
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); ?>
up
0
alfredoaguirre dot v at gmail dot com
17 years ago
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
up
0
petelu $ post dot sk
18 years ago
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);
?>
up
0
Jakub Horky <jakub dot php at horky dot net>
19 years ago
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.]
up
-1
support at lostair dot com
13 years ago
Force Curl Request To Go To A Particular IP Address

Yes, there is a method of passing an IP address to curl.  Excellent for services with multiple IP addresses and also to take DNS out of the equation for testing/debugging.

<?php
   
function fetch_page($url, $host_ip = NULL)
    {

     
$ch = curl_init();

      if (!
is_null($host_ip))
      {
       
$urldata = parse_url($url);

       
//  Ensure we have the query too, if there is any...
       
if (!empty($urldata['query']))
         
$urldata['path'] .= "?".$urldata['query'];

       
//  Specify the host (name) we want to fetch...
       
$headers = array("Host: ".$urldata['host']);
       
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

       
//  create the connecting url (with the hostname replaced by IP)
       
$url = $urldata['scheme']."://".$host_ip.$urldata['path'];
      }

     
curl_setopt($chCURLOPT_URL, $url);
     
curl_setopt ($ch, CURLOPT_HEADER, 0);
     
curl_setopt($chCURLOPT_RETURNTRANSFER, true);

     
$result = curl_exec ($ch);
     
curl_close ($ch);

      return
$result;
    }
?>
up
-1
W at RHaworth dot net
13 years ago
I had problems with the Wikimedia software and sending a POST request where the data was more than 1024 bytes long. I traced this to cURL adding: Expect: 100-continue to the headers.

I added curl_setopt($ch,CURLOPT_HTTPHEADER,array("Expect:")); and that suppresses the Expect line.
up
-1
alvaro at demogracia dot com
8 years ago
With the legacy file upload feature, Curl sends the file name of the actual file and there isn't a documented way to change that behaviour. If you aren't able to use the CURLFile class there's a workaround that apparently works: append "; filename=" after the value (and make sure it comes after "type=").

<?php

$postfields
= array(
   
'document[]' => '@/tmp/upload_qm5ee8FBxi; type=image/jpeg; filename=Kitten.jpg',
);
up
-1
obones_remove_me at free dot fr
13 years ago
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
up
-1
phpnet at andywaite dot com
18 years ago
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);
?>
up
-3
OPALA
15 years ago
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);
?>
up
-1
joey
8 years ago
Sorry, I made a mistake. For validating cookie entries it is best to use at least:

/^([^\t]+\t){6}[^\t]+$/

There was not enough space for me to put in the rationale for not using persistent storage with cookies but it should be obvious. It's YAGNI for most scenarios. In this case at best it complicate things, at the worst you perform an operation using the wrong cookie session. It can also increase the chance of failure, waste resources, reduce performance and create mess in the file system.

The plus of persistent is that In some cases it may be used to accelerate across processes but not many people actually need that and when they do there tend to be better options such as using memcached.

If someone can edit and merge the comments it would be appreciated.
up
-1
Simeon Anastasov
9 years ago
One note of importance when you open several cURL handles simultaneously: If you want to share cookies via cookie-jar file among all your handles - be sure to curl_close() one before using the cookie-jar file from the other.

It appears that during cURL handler execution the cookies are kept in some sort of handler specific internal session storage and only upon explicit curl_close() call or interpreter exit garbage collection these cookies are actually flushed to the file on the hard disk ( I guess for performance reasons ).

I hope this note will save you couple of hours debugging :)
up
-1
xuyan83121 at gmail dot com
11 years ago
when use curl_multi_exec, the CURLOPT_TIMEOUT need curl version newer than 7.21.2.
this can be found at curl changelog.
up
-1
wonderfish+php at gmail dot com
12 years ago
As of at least PHP 5.3.9, if you are continuing to use a cURL session handle after downloading a file and closing the file handle, you will need to change CURLOPT_FILE back to stdout, and cannot count simply on a side effect of CURLOPT_RETURNTRANSFER to do so, even if you are setting it.  For example:

<?php
$ch
= curl_init();
$fh = fopen('/path/to/stored/file/example_file.dat', 'w');
curl_setopt($ch, CURLOPT_FILE, $fh);
curl_setopt($ch, CURLOPT_URL, 'http://example.com/example_file.dat');
curl_exec($ch);
fflush($fh);
fclose($fh);

//must reset cURL file handle. Not doing so will cause a warning to be
//thrown and for cURL to default to output regardless
//for our example, we'll set return transfer.
curl_setopt($ch, CURLOPT_FILE, fopen('php://stdout', 'w'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, 'http://example.org/index.html');
$html = curl_exec($ch); //this will now work
?>
up
-2
sjungwirth at google mail dot com
13 years ago
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.
up
-1
chris at ocproducts dot com
6 years ago
On recent versions of MacOS CURLOPT_SSL_VERIFYPEER cannot be disabled, unless you have compiled PHP yourself with the official cURL library and OpenSSL.

Why?
1) MacOS is bundling its own version of cURL which has Apple SecureTransport as the SSL handling.
2) The implementation will complain if CURLOPT_SSL_VERIFYPEER is disabled but CURLOPT_CAINFO is set ("CA certificate set, but certificate verification is disabled").
3) The implementation will consider CURLOPT_CAINFO set even if it is set to blank/null/false ("can't load CA certificate file").  This error comes from ""SSL: can't load CA certificate file %s"" in https://opensource.apple.com/source/curl/curl-95/curl/lib/vtls/darwinssl.c, you can see there's no blank verification.

To confirm this is what is affecting you look for what "SSL Version" is set at in the PHP-info. This is under the cURL settings.

To resolve you need to compile cURL (e.g. using Homebrew) with OpenSSL enabled:
brew install curl --with-openssl

Then compile PHP with something like this in the configure command:
'--with-curl=/usr/local/opt/curl'

It may also be possible to use Homebrew to compile PHP using it's own cURL, I haven't checked this.

Once resolved "SSL Version" will report something like "OpenSSL/1.0.2l".

Of course you shouldn't disable certificate validation. I am only doing it because I'm writing code to detect if a site's SSL is broken (works with verify peer, doesn't work without). Others maybe are using self-signed certificates and don't want to work out how to make them a root authority. Never ever use live.
up
-1
chris at ocproducts dot com
7 years ago
Never provide a CURLOPT_CUSTOMREQUEST value of 'HEAD'. It will cause cURL to timeout. Instead set CURLOPT_NOBODY to true.

The problem occurs because CURLOPT_CUSTOMREQUEST directly substitutes what cURL sends in transit, but not the response handling logic. It causes it to stall waiting for data that will never come.
up
-1
jeffb at nospam dot videx dot com
11 years ago
When trying to pass a multi-dimensional array to CURLOPT_POSTFIELDS, first run it through http_build_query().  That will get rid of the Array to String conversion notice.
up
-2
Stan van de Burgt
14 years ago
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.
up
-2
Anonymous
5 years ago
If you have problems with CURLOPT_SSL_VERIFYPEER and using Apache.
Download certificate bundle:
http://curl.haxx.se/docs/caextract.html

Then set a path not in your php.ini, but in phpForApache.ini file.
Example:
curl.cainfo=c:\php\cacert.pem
up
-2
Manasi
10 years ago
CURLAUTH_ANY is not an alias for CURLAUTH_NTLM. I had to specify CURLAUTH_NTLM for a Windows authenticated URL
up
-4
patryk at do dot not dot spam dot com
13 years ago
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.
up
-6
starrychloe at oliveyou dot net
7 years ago
You may also specify the certificate authority file with an environment variable.

export SSL_CERT_FILE=/path/to/cacert.pem
To Top