PHP 8.3.4 Released!

curl_setopt

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

curl_setoptDéfinit une option de transmission cURL

Description

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

Définit une option pour le gestionnaire de session cURL fournit.

Liste de paramètres

handle

Un gestionnaire cURL retourné par curl_init().

option

L'option CURLOPT_XXX à définir.

value

La valeur à définir pour option.

value doit être un booléen pour les valeurs suivantes du paramètre option :

Option Définir value à Notes
CURLOPT_AUTOREFERER true pour définir automatiquement le champ Referer: dans les requêtes où une redirection Location: suit.
CURLOPT_COOKIESESSION true pour marquer ceci comme un nouveau cookie "session". Cela forcera libcurl à ignorer tous les cookies qui sont prêts à être chargés qui sont des "cookies de session" provenant des sessions antérieures. Par défaut, libcurl enregistre et charge toujours tous les cookies, indépendamment s'ils sont des cookies de session ou pas. Les cookies de session sont des cookies sans date d'expiration et existeront que pour cette "session" seulement.
CURLOPT_CERTINFO true pour sortir les informations de certification SSL vers STDERR pour les transferts sécurisés. Ajouté en cURL version 7.19.1. Nécessite CURLOPT_VERBOSE d'être activé.
CURLOPT_CONNECT_ONLY true indique à la bibliothèque d'effectuer toutes les configurations nécessaires à l'authentification et la connexion au proxy, mais ne transfère aucune donnée. Cette option est implémentée pour HTTP, SMTP et POP3. Ajouté en cURL 7.15.2.
CURLOPT_CRLF true pour convertir les nouvelles lignes Unix en nouvelles lignes CRLF durant les transferts.
CURLOPT_DISALLOW_USERNAME_IN_URL true pour ne pas permettre les URLs qui incluent un nom d'utilisateur. Les noms d'utilisateurs sont autorisé par défaut (0). Ajouté en cURL 7.61.0. Disponible à partir de PHP 7.3.0.
CURLOPT_DNS_SHUFFLE_ADDRESSES true pour mélanger l'ordre de toutes les addresses retournées pour qu'elles soit utilisées dans un ordre aléatoire, quand un nom est résolu et que plus d'une addresse IP est retournée. Ceci peut causer d'utiliser IPv4 avant IPv6 ou vice versa. Ajouté en cURL 7.60.0. Disponible à partir de PHP 7.3.0.
CURLOPT_HAPROXYPROTOCOL true pour envoyer un en-tête HAProxy PROXY protocol v1 au début de la connexion. L'action par défaut est de ne pas envoyer cet en-tête. Ajouté en cURL 7.60.0. Disponible à partir de PHP 7.3.0.
CURLOPT_SSH_COMPRESSION true pour activer la compression SSH intégré. Ceci est une demande, pas un ordre ; le serveur peut ou ne peut pas le faire. Ajouté en cURL 7.56.0. Disponible à partir de PHP 7.3.0.
CURLOPT_DNS_USE_GLOBAL_CACHE true pour utiliser un cache DNS global. Cette option n'est pas compatible avec les threads. Elle est conditionellement activée par défaut si PHP est compilé pour une utilisation non threadé (CLI, FFCGI, Apache2-Prefork, etc.).
CURLOPT_FAILONERROR true pour échouer verbalement si le code HTTP retourné est supérieur ou égal à 400. Le comportement par défaut est de retourner la page normalement, en ignorant le code.
CURLOPT_SSL_FALSESTART true pour activer le faux départ TLS. Ajouté en cURL 7.42.0. Disponible à partir de PHP 7.0.7.
CURLOPT_FILETIME true pour tenter de récupérer la date de modification du document distant. Cette valeur peut être récupérée en utilisant l'option CURLINFO_FILETIME avec curl_getinfo().
CURLOPT_FOLLOWLOCATION true pour suivre tous les en-têtes "Location: " que le serveur envoie dans les en-têtes HTTP. Voir aussi CURLOPT_MAXREDIRS.
CURLOPT_FORBID_REUSE true pour forcer à fermer explicitement la connexion lorsque le processus est terminé. Elle ne sera donc pas mise en cache pour réutilisation.
CURLOPT_FRESH_CONNECT true pour forcer l'utilisation d'une nouvelle connexion au lieu d'une en cache.
CURLOPT_FTP_USE_EPRT true pour utiliser EPRT (et LPRT) lors des téléchargements FTP actifs. Utilisez false pour désactiver EPRT et LPRT et ainsi n'utiliser que PORT.
CURLOPT_FTP_USE_EPSV true pour tenter tout d'abord une commande EPSV pour les transferts FTP avant de revenir à une commande PASV. Définir à false pour désactiver EPSV.
CURLOPT_FTP_CREATE_MISSING_DIRS true pour créer les dossiers intermédiaires lorsqu'une opération FTP est demandée sur un chemin qui n'existe pas.
CURLOPT_FTPAPPEND true pour que PHP ajoute les informations au fichier distant plutôt que de l'écraser.
CURLOPT_TCP_NODELAY true pour désactiver l'algorithme Nagle de TCP, qui tente de réduire le nombre de petits paquets sur le réseau. Disponible pour les versions compilées avec libcurl 7.11.2 ou supérieur.
CURLOPT_FTPASCII Un alias de CURLOPT_TRANSFERTEXT. Utilisez celui-là à la place.
CURLOPT_FTPLISTONLY true pour ne lister que les noms dans un dossier FTP.
CURLOPT_HEADER true pour inclure l'en-tête dans la valeur de retour.
CURLINFO_HEADER_OUT true pour suivre la chaîne de caractères du gestionnaire de requête. Le préfixe CURLINFO_ est intentionnel.
CURLOPT_HTTP09_ALLOWED Si on doit ou non autoriser les réponses HTTP/0.9. Par défaut, vaut false depuis libcurl 7.66.0; Auparavant, vallait true par défaut. Available since PHP 7.3.15 and 7.4.3, respectively, if built against libcurl >= 7.64.0
CURLOPT_HTTPGET true pour réinitialiser la méthode de la requête HTTP à GET. Sachant que GET est la valeur par défaut, cela est uniquement nécessaire si la méthode de la requête a été modifiée.
CURLOPT_HTTPPROXYTUNNEL true pour passer par un proxy HTTP donné.
CURLOPT_HTTP_CONTENT_DECODING false pour récupérer le corps de la réponse HTTP brute. Disponible si compilé contre libcurl >= 7.16.2.
CURLOPT_KEEP_SENDING_ON_ERROR true pour continuer d'envoyer le corps de la requête si le code HTTP est supérieur ou égal à 300. La valeur par défaut est d'arrêter l'envoie et de fermer le flux ou connexion. Adapté pour une authentication NTLM manuelle. La plupart des applications n'ont pas besoin de cette option. Disponible à partir de PHP 7.3.0 si compilé contre libcurl >= 7.51.0.
CURLOPT_MUTE true pour que PHP soit totalement silencieux concernant toutes les fonctions cURL. Supprimé en cURL 7.15.5 (Utiliser CURLOPT_RETURNTRANSFER à la place)
CURLOPT_NETRC true pour analyser le fichier ~./netrc pour trouver un nom d'utilisateur et mot de passe pour le site distant où une connexion est en train d'être établie.
CURLOPT_NOBODY true pour exclure le corps de la sortie. La méthode de la requête est alors définie à HEAD. Modifier ceci à false ne modifie pas la méthode en GET.
CURLOPT_NOPROGRESS

true pour désactiver la barre de progression des transferts cURL.

Note:

PHP définit automatiquement cette option à true, ceci devrait être modifié uniquement pour des raisons de déboguage.

CURLOPT_NOSIGNAL true pour ignorer toutes les fonctions cURL qui causent l'envoi d'un signal au processus PHP. Activée par défaut dans les SAPIs multithreadés afin que les options d'expiration puissent toujours être utilisées. Ajouté dans cURL 7.10.
CURLOPT_PATH_AS_IS true pour ne pas gérer les séquences point point. Ajouté dans cURL 7.42.0. Disponible à partir de PHP 7.0.7.
CURLOPT_PIPEWAIT true pour attendre pour le pipelining/multiplexing. Ajouté dans cURL 7.43.0. Disponible à partir de PHP 7.0.7.
CURLOPT_POST true pour que PHP fasse un HTTP POST régulier. Ce POST est le type normal application/x-www-form-urlencoded, utilisé couramment par les formulaires HTML.
CURLOPT_PUT true pour HTTP PUT un fichier. Le fichier à téléverser avec PUT doit être définit avec CURLOPT_INFILE et CURLOPT_INFILESIZE.
CURLOPT_RETURNTRANSFER true pour retourner le transfert en tant que chaîne de caractères de la valeur retournée par curl_exec() au lieu de l'afficher directement.
CURLOPT_SASL_IR true pour permettre d'envoyer la réponse initiale dans le premier paquet. Ajouté dans cURL 7.31.10. Disponible à partir de PHP 7.0.7.
CURLOPT_SSL_ENABLE_ALPN false pour désactiver ALPN dans la poignée de main SSL (si le back-end SSL libcurl est compilé pour utiliser le supporte), qui peut être utilisée pour négocier http2. Ajouté dans cURL 7.36.0. Disponible à partir de PHP 7.0.7.
CURLOPT_SSL_ENABLE_NPN false pour désactiver NPN dans la poignée de main SSL (si le back-end SSL libcurl est compilé pour utiliser le supporte), qui peut être utilisé pour négocier http2. Ajouté dans cURL 7.36.0. Disponible à partir de PHP 7.0.7.
CURLOPT_SSL_VERIFYPEER false pour arrêter cURL de vérifier le certificat du pair. Les certificats alternatifs à vérifier contre peuvent être spécifiés avec l'option CURLOPT_CAINFO ou un répertoire de certificat peut être spécifié avec l'option CURLOPT_CAPATH. true par défaut à partir de cURL 7.10. Paquet installé par défaut à partir de cURL 7.10.
CURLOPT_SSL_VERIFYSTATUS true pour vérifier l'état du certificat. Ajouté dans cURL 7.41.0. Disponible à partir de PHP 7.0.7.
CURLOPT_PROXY_SSL_VERIFYPEER false pour arrêter cURL de vérifié le certificat du homologue. Des certificats alternatifs à vérifier contre peuvent être définie avec l'option CURLOPT_CAINFO ou un dossier de certificat peut être définie avec l'option CURLOPT_CAPATH. Quand définie à false, la vérification du certificat homologue réussit malgré tout. true par défaut. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_SAFE_UPLOAD Toujours true, ce qui désactive la prise en charge du préfixe @ pour le téléversement de fichiers dans CURLOPT_POSTFIELDS, ce qui signifie que les valeurs commençant par @ peuvent être transmises en tant que champs en toute sécurité. CURLFile peut être utilisé pour les téléversements à la place.
CURLOPT_SUPPRESS_CONNECT_HEADERS true pour réprimer les en-têtes de réponse proxy CONNECT des fonctions de rappels utilisateurs CURLOPT_HEADERFUNCTION et CURLOPT_WRITEFUNCTION, quand CURLOPT_HTTPPROXYTUNNEL est utilisé et une requête CONNECT est faite. Ajouté dans cURL 7.54.0. Disponible à partir de PHP 7.3.0.
CURLOPT_TCP_FASTOPEN true pour activer TCP Fast Open. Ajouté dans cURL 7.49.0. Disponible à partir de PHP 7.0.7.
CURLOPT_TFTP_NO_OPTIONS true pour ne pas envoyer les requêtes d'options TFTP. Ajouté dans cURL 7.48.0. Disponible à partir de PHP 7.0.7.
CURLOPT_TRANSFERTEXT true pour utiliser le mode ASCII pour les transferts FTP. Pour LDAP, il récupère les données en texte plein au lieu d'HTML. Sur les systèmes Windows, STDOUT ne sera pas définie en mode binaire.
CURLOPT_UNRESTRICTED_AUTH true pour continuer d'envoyer le nom d'utilisateur et le mot de passe lorsque l'on suit les chemins (en utilisant CURLOPT_FOLLOWLOCATION), même si le nom d'hôte change.
CURLOPT_UPLOAD true pour préparer pour un téléversement.
CURLOPT_VERBOSE true pour afficher les informations de façon verbeuse. Écrit la sortie sur STDERR, ou dans le fichier spécifié en utilisant CURLOPT_STDERR.

value devrait être un entier pour les valeurs suivantes du paramètres option :

Option Définir value à Notes
CURLOPT_BUFFERSIZE La taille du tampon à utiliser pour chaque lecture. Cependant, il n'y a aucune garantie que cette requête soit accomplie. Ajouté en cURL 7.10.
CURLOPT_CONNECTTIMEOUT Le nombre de secondes à attendre durant la tentative de connexion. Utiliser 0 pour attendre indéfiniment.
CURLOPT_CONNECTTIMEOUT_MS Le nombre de millisecondes à attendre durant la tentative de connexion. Utiliser 0 pour attendre indéfiniment. Si libcurl est compilé pour utiliser le système standard de résolution de noms, cette partie de la connexion utilisera toujours la seconde résolution pour le délai d'attente maximal avec un délai d'attente maximal minimum autorisé d'une seconde. Ajouté en cURL 7.16.2.
CURLOPT_DNS_CACHE_TIMEOUT Le temps en seconde pour conserver les entrées DNS en mémoire. Cette option est définie à 120 secondes (2 minutes) par défaut.
CURLOPT_EXPECT_100_TIMEOUT_MS Le délais d'attente pour les réponses Expect: 100-continue en millisecondes. Par défaut 1000 millisecondes. Ajouté dans cURL 7.36.0. Disponible à partir de PHP 7.0.7.
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS Une longueur d'avance pour ipv6 pour l'algorithme happy eyeballs. Happy eyeballs tente se connecter à la fois aux adresses IPv4 et IPv6 pour les hôtes à double pile, préférant IPv6 d'abord pour les millisecondes d'expiration. Par défaut CURL_HET_DEFAULT, qui est actuellement 200 millisecondes. Ajouté en cURL 7.59.0. Disponible à partir de PHP 7.3.0.
CURLOPT_FTPSSLAUTH La méthode d'identification FTP, lorsqu'elle est activée : CURLFTPAUTH_SSL (tenter SSL en premier), CURLFTPAUTH_TLS (tenter TLS en premier), ou CURLFTPAUTH_DEFAULT (laisser cURL décider). Ajouté en cURL 7.12.2.
CURLOPT_HEADEROPT Comment gérer les en-têtes. Une des constantes suivantes : CURLHEADER_UNIFIED : les en-têtes spécifié dans CURLOPT_HTTPHEADER seront utilisés dans les requêtes à la fois aux serveurs ainsi qu'aux proxies. Avec cette option activé, CURLOPT_PROXYHEADER n'aura pas d'effet. CURLHEADER_SEPARATE : fait que les en-têtes CURLOPT_HTTPHEADER sont uniquement envoyés aux serveurs et pas à un proxy. Les en-têtes pour les proxies doivent être définit avec CURLOPT_PROXYHEADER pour être utilisé. Il est à noter que si une requête non-CONNECT est envoyé à un proxy, libcurl envera à la fois les en-têtes de serveur et de proxy. Lors de CONNECT, libcurl envera les en-têtes CURLOPT_PROXYHEADER seulement au proxy et les en-têtes CURLOPT_HTTPHEADER seulement au serveur. Par défaut CURLHEADER_SEPARATE à partir de cURL 7.42.1, et CURLHEADER_UNIFIED auparavant. Ajouté dans cURL 7.37.0. Disponible à partir de PHP 7.0.7.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (défaut, laisse cURL décider la version à utiliser), CURL_HTTP_VERSION_1_0 (force HTTP/1.0), ou CURL_HTTP_VERSION_1_1 (force HTTP/1.1), CURL_HTTP_VERSION_2_0 (tente HTTP 2), CURL_HTTP_VERSION_2 (alias de CURL_HTTP_VERSION_2_0) ,CURL_HTTP_VERSION_2TLS (tente HTTP 2 sur TLS (HTTPS) uniquement) ou CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (émet des requêtes HTTP non TLS en utilisant HTTP / 2 sans mise à niveau HTTP / 1.1).
CURLOPT_HTTPAUTH

La méthode d'identification HTTP à utiliser. Ces options sont : CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_AWS_SIGV4, CURLAUTH_ANY et CURLAUTH_ANYSAFE.

L'opérateur bit à bit | (ou) peut être utilisé pour combiner plus d'une méthode. Si ceci est fait, cURL interrogera le serveur pour voir quelles sont les méthodes supportées et prendra la meilleur.

CURLAUTH_ANY définit tous les bits. cURL sélectionnera automatiquement celui qu'il trouve le plus sécurisé.

CURLAUTH_ANYSAFE définit tous les bits sauf CURLAUTH_BASIC. cURL sélectionnera automatiquement celui qu'il trouve le plus sécurisé.

CURLOPT_INFILESIZE La taille attendue, en octets, du fichier lors du téléversemement d'un fichier vers un site distant. Notez que l'utilisation de cette option n'arrêtera pas libcurl d'envoyer plus de données, de la même façon que ce qui est envoyé dépend de l'option CURLOPT_READFUNCTION.
CURLOPT_LOW_SPEED_LIMIT La vitesse de transfert, en octets par secondes en dessous de laquelle, et pendant CURLOPT_LOW_SPEED_TIME secondes, PHP considérera qu'elle est trop lente, et annulera le transfert.
CURLOPT_LOW_SPEED_TIME Le temps en secondes, pendant lequel si le transfert reste en dessous de CURLOPT_LOW_SPEED_LIMIT, PHP considérera que la connexion est trop lente, et l'annulera.
CURLOPT_MAIL_RCPT_ALLLOWFAILS Autorise l'échec de la commande RCPT TO pour certains destinataires. Lors de l'envoi de données à plusieurs destinataires, cURL interrompt la conversation SMTP par défaut si au moins l'un des destinataires provoque une erreur avec la commande RCPT TO. Cette option indique à cURL d'ignorer les erreurs et de continuer avec les destinataires valides restants. Si tous les destinataires génèrent des échecs RCPT TO et que ce drapeau est activé, cURL interrompra la conversation SMTP et renverra l'erreur reçue de la dernière commande RCPT TO.
CURLOPT_MAXAGE_CONN Le temps d'inactivité maximal autorisé pour qu'une connexion existante soit considérée comme réutilisable. La durée maximale par défaut est de 118 secondes.
CURLOPT_MAXFILESIZE_LARGE La taille maximale du fichier en octets autorisée à télécharger. Si la taille du fichier demandé est supérieure à cette valeur, le transfert ne commencera pas et CURLE_FILESIZE_EXCEEDED sera renvoyé. La taille du fichier n'est pas toujours connue avant le téléchargement, et pour de tels fichiers, cette option n'a aucun effet, même si le transfert de fichier finit par être plus grand que cette limite donnée.
CURLOPT_MAXLIFETIME_CONN Le temps maximal en secondes, depuis la création de la connexion, qui est autorisé pour qu'une connexion existante soit considérée pour être réutilisable. Si une connexion est trouvée dans la mémoire cache et est plus ancienne que cette valeur, elle sera fermée une fois que tous les transferts en cours seront terminés. La valeur par défaut est de 0 seconde, ce qui signifie que l'option est désactivée et que toutes les connexions sont éligibles pour être réutilisées.
CURLOPT_MAXCONNECTS Le nombre maximal de connexions persistantes autorisées. Lorsque la limite est atteinte, la plus ancienne dans le cache est fermée pour éviter d'augmenter le nombre de connexions ouvertes.
CURLOPT_MAXREDIRS Le nombre maximal de redirections HTTP à suivre. Utilisez cette option avec l'option CURLOPT_FOLLOWLOCATION. Une valeur par défaut de 20 est définit pour prévenir les redirections infinies. Définir à -1 permet les redirections infinies, et 0 refuse toute redirection.
CURLOPT_PORT Un numéro de port alternatif auquel se connecter.
CURLOPT_POSTREDIR Un masque de bit de 1 (301 Moved Permanently), 2 (302 Found) et 4 (303 See Other) si la méthode HTTP POST doit être maintenu quand CURLOPT_FOLLOWLOCATION est défini et un type spécifique de redirection se produit. Ajouté dans cURL 7.19.1.
CURLOPT_PROTOCOLS

Champ de bits de valeurs CURLPROTO_*. S'il est utilisé, ce champ limite les protocoles qui peuvent être utilisés durant un transfert. Cela vous permet de limiter le nombre de protocoles utilisés par la libcurl, tout en la compilant avec un grand nombre d'entre eux. Par défaut, libcurl va accepter tous les protocoles qu'elle supporte. Voir aussi CURLOPT_REDIR_PROTOCOLS.

Les options valides de protocoles sont : 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

Ajouté en cURL 7.19.4.
CURLOPT_PROXYAUTH La méthode d'authentifucation HTTP à utiliser pour la connexion à un proxy. Utilisez la même méthode que celle décrite dans CURLOPT_HTTPAUTH. Pour une identification avec un proxy, seuls CURLAUTH_BASIC et CURLAUTH_NTLM sont actuellement supportés. Ajouté en CURL 7.10.7.
CURLOPT_PROXYPORT Le numéro du port du proxy à utiliser pour la connexion. Ce numéro de port peut également être défini dans CURLOPT_PROXY.
CURLOPT_PROXYTYPE Soit CURLPROXY_HTTP (par défaut), CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A ou CURLPROXY_SOCKS5_HOSTNAME. Ajouté en cURL 7.10.
CURLOPT_REDIR_PROTOCOLS Masque de bits des valeurs CURLPROTO_*. S'il est utilisé, ce masque limite les protocoles que libcurl peut utiliser dans un transfert qu'il suit après une redirection lorsque CURLOPT_FOLLOWLOCATION est activé. Cela permet de limiter certains transferts spécifique à utiliser un sous groupe des protocoles lors d'une redirection. Par défaut, libcurl va autoriser tous les protocoles, hormis FILE et SCP. Ceci est différent comparé aux versions antérieurs à 7.19.4 qui suivaient inconditionnellement tous les protocoles supportés. Voir aussi CURLOPT_PROTOCOLS pour les valeurs des constantes de protocoles. Ajoutés en cURL 7.19.4.
CURLOPT_RESUME_FROM La position, en octets, où reprendre un transfert.
CURLOPT_SOCKS5_AUTH

Les méthode(s) d'authentification SOCKS5 à utiliser. Les options sont : CURLAUTH_BASIC, CURLAUTH_GSSAPI, CURLAUTH_NONE.

L'opérateur bit à bit | (ou) peut être combiné pour utiliser plus d'une méthode. Si ceci est fait, cURL interrogera le serveur pour voir quelles méthodes sont prises en charge et choisir la meilleure.

CURLAUTH_BASIC autorise l'authentification utilisateur/mot de passe.

CURLAUTH_GSSAPI autorise l'authentification GSS-API.

CURLAUTH_NONE autorise aucune authentification.

Par défaut CURLAUTH_BASIC|CURLAUTH_GSSAPI. Définir l'utilisateur actuel et mot de passe avec l'option CURLOPT_PROXYUSERPWD.

Disponible à partir de PHP 7.3.0 et curl >= 7.55.0.
CURLOPT_SSL_OPTIONS Définit les options de comportement SSL, qui est un masque de bits des constantes suivantes : CURLSSLOPT_ALLOW_BEAST : n'essaye pas d'utiliser des solutions de contournement pour une faille de sécurité dans les protocoles SSL3 et TLS1.0. CURLSSLOPT_NO_REVOKE : désactiver les vérifications de révocation de certificats pour les serveurs SSL où un tel comportement est présent. CURLSSLOPT_AUTO_CLIENT_CERT : localisation automatique et utilisation d'un certificat client pour l'authentification, lorsque demandé par le serveur. Cette option est uniquement prise en charge pour Schannel (la bibliothèque SSL native de Windows). CURLSSLOPT_NATIVE_CA : utilisation du magasin de certificats natif du système d'exploitation pour la vérification des certificats. Fonctionne uniquement sous Windows lorsqu'il est construit pour utiliser OpenSSL. Cette option est expérimentale et son comportement est susceptible de changer. CURLSSLOPT_NO_PARTIALCHAIN : ne pas accepter les chaînes de certificats "partielles", que cURL accepte par défaut. Cette option est uniquement prise en charge pour OpenSSL et échouera la vérification du certificat si la chaîne se termine par un certificat intermédiaire et non par un certificat racine. CURLSSLOPT_REVOKE_BEST_EFFORT : ignorer les vérifications de révocation de certificat en cas d'absence ou d'indisponibilité des points de distribution pour les bibliothèques SSL où un tel comportement est présent. Cette option est uniquement prise en charge pour Schannel (la bibliothèque SSL native de Windows). Si elle est combinée avec CURLSSLOPT_NO_REVOKE, cette dernière prévaut. Ajouté dans cURL 7.25.0. Disponible à partir de PHP 7.0.7.
CURLOPT_SSL_VERIFYHOST 2 pour vérifier qu'un champ Common Name field ou Subject Alternate Name dans le certificat SSL correspond avec le nom d'hôte fourni. 0 pour ne pas vérifier les noms. 1 ne devrait pas être utilisé. Dans les environnement de production, la valeur de cette option doit être conservée à 2 (valeur par défaut). Support pour la valeur 1 supprimé en cURL 7.28.1
CURLOPT_SSLVERSION Une valeur parmi 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) ou CURL_SSLVERSION_TLSv1_2 (6) ou CURL_SSLVERSION_TLSv1_3 (7). La version TLS maximale peut être définie en utilisant une des constantes CURL_SSLVERSION_MAX_*. Il est aussi possible de OU une des constantes CURL_SSLVERSION_* avec une des constantes CURL_SSLVERSION_MAX_*. CURL_SSLVERSION_MAX_DEFAULT (la version maximale supporté par la bibliothèque), CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, ou CURL_SSLVERSION_MAX_TLSv1_3.

Note:

Dans votre intérêt, il est préférable de ne pas définir cette valeur et utiliser la valeur par défaut. Définir à 2 ou 3 est très dangereux sachant le nombre de vulnérabilité présentes dans SSLv2 et SSLv3.

CURLOPT_PROXY_SSL_OPTIONS Définit les options de comportement proxie SSL, qui est un masque de bits des constantes suivantes : CURLSSLOPT_ALLOW_BEAST : n'essaye pas d'utiliser des solutions de contournement pour une faille de sécurité dans les protocoles SSL3 et TLS1.0. CURLSSLOPT_NO_REVOKE : désactiver les vérifications de révocation de certificats pour les serveurs SSL où un tel comportement est présent. (curl >= 7.44.0) CURLSSLOPT_NO_PARTIALCHAIN : n'accepte pas des chaînes "partielles" de certificats, qui est sinon la valeur par défaut. (curl >= 7.68.0) Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSL_VERIFYHOST Définir à 2 pour vérifier dans le certificats du proxie HTTPS les champs de nom contre le nom du proxie. Quand définie à 0 la connexion succède peut importe des noms utilisés dans le certificat. Utilisez cette fonctionnalité avec précaution! 1 est traité comme une option de debug dans curl 7.28.0 et antérieur. Entre curl 7.28.1 et 7.65.3 CURLE_BAD_FUNCTION_ARGUMENT est retourné. À partir de curl 7.66.0 1 et 2 sont traité comme la même valeur. En environnement de production, la valeur de cette option doit être conservée à 2 (valeur par défaut). Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLVERSION Une de 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 ou CURL_SSLVERSION_SSLv3.

Note:

Dans votre intérêt, il est préférable de ne pas définir ceci et de le laisser utiliser la valeur par défaut CURL_SSLVERSION_DEFAULT qui tentera de comprendre la version du protocole SSL distant.

Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_STREAM_WEIGHT Définit le poid numérique du flux (un nombre entre 1 et 256). Ajouté dans cURL 7.46.0. Disponible à partir de PHP 7.0.7.
CURLOPT_TCP_KEEPALIVE Si définie à 1, Des sondes TCP keepalive seront envoyées. Le délais et fréquence de ces sondes peut être controllé par les options CURLOPT_TCP_KEEPIDLE et CURLOPT_TCP_KEEPINTVL, à condition que le système d'exploitation les supporte. Si définie à 0 (par défaut) les sondes keepalive sont désactivées. Ajouté dans cURL 7.25.0.
CURLOPT_TCP_KEEPIDLE Définie le délais, en secondes, que le système d'exploitation attendra pendent que la connexion est inoccupé, avant d'envoyer des sondes keepalive, si CURLOPT_TCP_KEEPALIVE est activé. Pas tout les systèmes d'exploitations supportent cette option. La valeur par défaut est 60. Ajouté dans cURL 7.25.0.
CURLOPT_TCP_KEEPINTVL Définie l'intervalle, en secondes, que le système d'exploitation attendra entre les envoies des sondes keepalive, si CURLOPT_TCP_KEEPALIVE est activé. Pas tout les systèmes d'exploitations supportent cette option. La valeur par défaut est 60. Ajouté dans cURL 7.25.0.
CURLOPT_TIMECONDITION Comment CURLOPT_TIMEVALUE est traité. Utiliser CURL_TIMECOND_IFMODSINCE pour retourner la page uniquement si elle a été modifiée depuis le temps spécifié dans CURLOPT_TIMEVALUE. Si elle n'a pas été modifiée, un en-tête "304 Not Modified" sera retourné en supposant que CURLOPT_HEADER vaut true. Utiliser CURL_TIMECOND_IFUNMODSINCE pour faire l'inverse. Utiliser CURL_TIMECOND_NONE pour ignorer CURLOPT_TIMEVALUE et toujours retourner la page. La valeur par défaut est CURL_TIMECOND_NONE. Antérieur à cURL 7.46.0 la valeur par défaut était CURL_TIMECOND_IFMODSINCE.
CURLOPT_TIMEOUT Le temps maximum d'exécution de la fonction cURL exprimé en secondes.
CURLOPT_TIMEOUT_MS Le nombre maximal de millisecondes autorisé aux fonctions cURL pour l'exécution. Si libcurl est compilé pour utiliser le système standard de résolution de noms, cette partie de la connexion utilisera toujours la seconde résolution pour le délai d'attente maximal avec un délai d'attente maximal minimum autorisé d'une seconde. Ajouté en cURL 7.16.2.
CURLOPT_TIMEVALUE Le temps en secondes depuis le 1er janvier 1970. Le temps sera utilisée par CURLOPT_TIMECONDITION.
CURLOPT_TIMEVALUE_LARGE Le temps en secondes depuis le 1er Janvier, 1970. Le temps sera utilisé par CURLOPT_TIMECONDITION. Par défaut zéro. La différence entre cette option et CURLOPT_TIMEVALUE est le type d'argument. Sur les systèmes où 'long' est seulement large de 32 bits, cette option doit être utilisé pour définir des dates au delà de l'année 2038. Ajouté dans cURL 7.59.0. Disponible à partir de PHP 7.3.0.
CURLOPT_UPKEEP_INTERVAL_MS Certains protocoles disposent de mécanismes de "maintenance de connexion". Ces mécanismes envoient généralement du trafic sur des connexions existantes pour les maintenir actives. Cette option définit l'intervalle de maintenance de la connexion. Actuellement, le seul protocole avec un mécanisme de maintenance de la connexion est HTTP/2. Lorsque l'intervalle de maintenance de la connexion est dépassé, une trame PING HTTP/2 est envoyée sur la connexion. La valeur par défaut est de 60 secondes.
CURLOPT_UPLOAD_BUFFERSIZE Taille de mémoire tampon préférée en octets pour la mémoire tampon d'envoi cURL. La taille de la mémoire tampon d'envoi est par défaut de 64 kilooctets. La taille maximale de mémoire tampon autorisée est de 2 mégaoctets. La taille minimale de mémoire tampon autorisée est de 16 kilooctets.
CURLOPT_MAX_RECV_SPEED_LARGE Si un téléchargement excède cette vitesse (comptée en octets par seconde) sur une moyenne cumulée durant le transfert, le transfert se mettra en pause pour conserver la moyenne inférieure ou égales à la valeur de ce paramètre. Par défaut, la vitesse est illimitée. Ajouté en cURL 7.15.5.
CURLOPT_MAX_SEND_SPEED_LARGE Si un téléversement excède cette vitesse (comptée en octets par seconde) sur une moyenne cumulée durant le transfert, le transfert se mettra en pause pour conserver la moyenne inférieure ou égales à la valeur de ce paramètre. Par défaut, la vitesse est illimitée. Ajouté en cURL 7.15.5.
CURLOPT_SSH_AUTH_TYPES Un masque de bit constitué d'une ou plusieurs de : CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD. Définir à CURLSSH_AUTH_ANY pour laisser libcurl choisir. Ajouté en cURL 7.16.1.
CURLOPT_IPRESOLVE Autorise une application à sélectionner le type d'adresse IP à utiliser lors de la résolution des noms d'hôtes. Ceci n'est intéressant que lors de l'utilisation des noms d'hôtes qui résolvent les adresses en utilisant plus d'une version d'IP ; les valeurs possibles sont CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6 ; par défaut CURL_IPRESOLVE_WHATEVER. Ajouté en cURL 7.10.8.
CURLOPT_FTP_FILEMETHOD Dit à curl quelle méthode à utiliser pour atteindre un fichier sur un serveur FTP(S). Valeur possible sont CURLFTPMETHOD_DEFAULT, CURLFTPMETHOD_MULTICWD, CURLFTPMETHOD_NOCWD, et CURLFTPMETHOD_SINGLECWD. Ajouté en cURL 7.15.1.

value doit être une chaîne de caractères pour les valeurs suivantes du paramètres option :

Option Définir value à Notes
CURLOPT_ABSTRACT_UNIX_SOCKET Active l'usage d'un socket domaine Unix abstrait au lieu d'établir une connexion TCP à un hôte et définie le chemin à la chaîne de caractères fournie. Cette option partage les mêmes sémantiques que CURLOPT_UNIX_SOCKET_PATH. Ces deux options partagent le même stockage et doc seul un des deux peut être définie par gestionnaire. Disponible à partir de PHP 7.3.0 et cURL 7.53.0
CURLOPT_ALTSVC Indique au fichier que cURL doit utiliser comme cache Alt-Svc pour lire le contenu du cache existant et, éventuellement, pour le réécrire après un transfert, sauf si CURLALTSVC_READONLYFILE est activé via CURLOPT_ALTSVC_CTRL.
CURLOPT_ALTSVC_CTRL Remplit le jeu de bits avec le bon ensemble de fonctionnalités pour indiquer à cURL comment gérer Alt-Svc pour les transferts effectués avec cette poignée. cURL n'accepte que les en-têtes Alt-Svc sur HTTPS. Il achèvera également une requête vers une origine alternative uniquement si cette origine est correctement hébergée sur HTTPS. Le réglage de n'importe quel bit activera le moteur alt-svc. Les options sont : CURLALTSVC_H1, CURLALTSVC_H2, CURLALTSVC_H3, et CURLALTSVC_READONLYFILE.
CURLOPT_AWS_SIGV4

Fournit une authentification de signature AWS V4 dans l'en-tête HTTP(S).

Cette option remplace tout autre type d'authentification qui a été défini dans CURLOPT_HTTPAUTH. Cette méthode ne peut pas être combinée avec d'autres types d'authentification.

CURLOPT_CAINFO Le nom d'un fichier contenant un ou plusieurs certificats pour vérifier la concordance. Cela n'a de sens que si vous l'utilisez en combinaison de l'option CURLOPT_SSL_VERIFYPEER. Peut nécessiter un chemin absolu.
CURLOPT_CAINFO_BLOB Le nom d'un fichier PEM contenant un ou plusieurs certificats pour vérifier le pair. Cette option remplace CURLOPT_CAINFO. Disponible à partir de PHP 8.2.0 et cURL 7.77.0
CURLOPT_CAPATH Un dossier qui contient les certificats. Utilisez cette option avec l'option CURLOPT_SSL_VERIFYPEER.
CURLOPT_COOKIE Le contenu de l'en-tête "Cookie: ", à transmettre dans l'en-tête HTTP. Notez que les cookies sont séparées par des points-virgule, suivi d'un d'espace (e.g., "fruit=pomme; couleur=rouge")
CURLOPT_COOKIEFILE Le nom du fichier contenant les données de cookie. Le fichier de cookie peut être au format Netscape, ou simplement des en-têtes HTTP écrits dans un fichier. Si le nom est une chaîne de caractère vide, aucun cookie n'est chargé, mais le gestionnaire est toujours actif.
CURLOPT_COOKIEJAR Le nom de fichier pour y sauvegarder tous les cookies internes lorsque la connexion se ferme, par exemple après un appel à curl_close.
CURLOPT_COOKIELIST Une chaîne cookie (c.à.d. une seule ligne dans le format Netscape/Mozilla, ou un en-tête de style HTTP régulier Set-Cookie) ajoute cet unique cookie au stockage interne de cookie. "ALL" efface tout les cookies tenu en mémoire. "SESS" efface tout les cookies de session tenu en mémoire. "FLUSH" écrit tout les connues dans le fichier spécifié par CURLOPT_COOKIEJAR. "RELOAD" charge tout les cookies depuis les fichiers spécifié par CURLOPT_COOKIEFILE. Disponible à partir de cURL 7.14.1.
CURLOPT_CUSTOMREQUEST

Une méthode de requête qui sera utilisée à la place de "GET" ou "HEAD" lors des requêtes HTTP. Cette commande est pratique pour effectuer un "DELETE" ou une autre commande HTTP exotique. Les valeurs valides sont "GET", "POST", "CONNECT" et plus ; i.e. n'entrez pas une requête HTTP complète ici. Par exemple, entrer "GET /index.html HTTP/1.0\r\n\r\n" serait incorrect.

Note:

N'utilisez pas cette commande sans vous assurer que le serveur l'accepte.

CURLOPT_DEFAULT_PROTOCOL

Le protocole par défaut à utiliser si l'URL manque un nom de schème.

Ajouté en cURL 7.45.0. Disponible à partir de PHP 7.0.7.
CURLOPT_HSTS

Nom du fichier de cache HSTS (HTTP Strict Transport Security).

CURLOPT_HSTS_CTRL

Contrôle le comportement HSTS (HTTP Strict Transport Security). Remplit le jeu de bits avec le bon ensemble de fonctionnalités pour indiquer à cURL comment gérer HSTS pour les transferts effectués avec cette poignée. CURLHSTS_ENABLE active le cache HSTS en mémoire. Si le fichier de cache HSTS est défini, réglez CURLHSTS_READONLYFILE pour rendre le fichier en lecture seule.

CURLOPT_DNS_INTERFACE

Définit le nom de l'interface réseau à laquelle le résolveur DNS doit se lier. Ceci doit être un nom d'interface (pas une adresse).

Ajouté en cURL 7.33.0. Disponible à partir de PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP4

Définit l'adresse IPv4 locale à laquelle le résolveur DNS doit se lier. L'argument devrait contenir une seule adresse numérique IPv4 sous chaîne de caractères

Ajouté en cURL 7.33.0. Disponible à partir de PHP 7.0.7.
CURLOPT_DNS_LOCAL_IP6

Définit l'adresse IPv6 locale à laquelle le résolveur DNS doit se lier. L'argument devrait contenir une seule adresse numérique IPv6 sous chaîne de caractères

Ajouté en cURL 7.33.0. Disponible à partir de PHP 7.0.7.
CURLOPT_EGDSOCKET Comme CURLOPT_RANDOM_FILE excepté que vous passez une chaîne qui contient un nom de fichier vers le socket Entropy Gathering Daemon.
CURLOPT_ENCODING Le contenu des en-têtes "Accept-Encoding: " et active le décodage de la réponse. Les encodages supportés sont "identity", "deflate" et "gzip". Si une chaîne vide "" est utilisé, un en-tête contenant tous les types d'encodage supportés est envoyé. Ajouté en cURL 7.10.
CURLOPT_FTPPORT La valeur qui sera utilisée pour récupérer l'adresse IP utilisée pour l'instruction FTP "PORT". L'instruction PORT indique au serveur distant de se connecter à cette adresse IP. La chaîne peut être une adresse IP, un nom d'hôte, un nom d'interface réseau (sous UNIX), ou juste '-', pour utiliser les IP par défaut du système.
CURLOPT_INTERFACE Le nom de l'interface à utiliser. Cela peut être le nom d'une interface, une adresse IP ou encore le nom de l'hôte.
CURLOPT_KEYPASSWD Le mot de passé nécessaire pour utiliser la clé privée CURLOPT_SSLKEY ou la clé privée CURLOPT_SSH_PRIVATE_KEYFILE. Added in cURL 7.16.1.
CURLOPT_KRB4LEVEL Le degré de sécurité KRB4 (Kerberos 4). Chacune des valeurs (dans l'ordre du plus petit au plus grand) suivantes sont valides : "clear", "safe", "confidential", "private".. Si la chaîne passée ne correspond pas à une de ces valeurs, la valeur "private" sera définie. Positionner cette valeur à null revient à désactiver la sécurité KRB4. Actuellement, la sécurité KRB4 fonctionne uniquement avec les transaction FTP.
CURLOPT_LOGIN_OPTIONS Peut être utilisé pour définir des options de connexion spécifiques au protocole, telles que le mécanisme d’authentification préféré via "AUTH = NTLM" ou "AUTH = *", et doit être utilisé conjointement avec l'option CURLOPT_USERNAME. Ajouté en cURL 7.34.0. Disponible à partir de PHP 7.0.7.
CURLOPT_PINNEDPUBLICKEY Définit la clé publique épinglée. La chaîne de caractères peut être le nom de fichier de votre clé publique épinglée. Le format de fichier attendu est "PEM" ou "DER". La chaîne de caractères peut également être un nombre quelconque de hachages sha256 codés en base64, précédés de "sha256//" et séparés par ";". Ajouté en cURL 7.39.0. Disponible à partir de PHP 7.0.7.
CURLOPT_POSTFIELDS Toutes les données à passer lors d'une opération de HTTP POST. Ce paramètre peut être passé sous la forme d'une chaîne encodée URL, comme 'para1=val1&para2=val2&...' ou sous la forme d'un tableau dont le nom du champ est la clé, et les données du champ la valeur. Si le paramètre value est un tableau, l'en-tête Content-Type sera définie à multipart/form-data. Des fichiers peuvent être envoyé en utilisant CURLFile ou CURLStringFile, dans quel cas value doit être un tableau.
CURLOPT_PRIVATE Toutes les données devant être associées à ce descripteur cURL. Ces données peuvent ensuite être récupérées avec l'option CURLINFO_PRIVATE de curl_getinfo(). cURL ne fait rien avec ces données. Lors de l'utilisation d'un multidescripteur cURL, ces données privées sont généralement une clé unique pour identifier un descripteur cURL standard. Ajouté en cURL 7.10.3.
CURLOPT_PRE_PROXY Définie une chaîne de caractères contenant le nom d'hôte ou addresse OP sous notation décimale à point à utiliser en tant que pré-proxy que curl se connecte avant qu'il se connecte au proxy HTTP(S) spécifié dans l'option CURLOPT_PROXY pour la requête à venir. Le pré-proxy peut uniquement être un proxy SOCKS et devrait être préfixé avec [scheme]:// pour spécifier quel type de socks est utilisé. Une addresse IPv6 numérique doit être écrit entre [crochet]. Définir le pré-proxy à une chaîne vide désactive explicitement l'utilisation d'un pré-proxy. Pour spécifier le numéro de port dans la chaîne, ajouter :[port] à la fin du nom d'hôte. Le numéro de port du proxy peut être optionellement définie avec l'option distincte CURLOPT_PROXYPORT. Utilise le port 1080 pour les proxies par défaut si aucun port n'a été spécifié. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY Le nom du proxy HTTP au tunnel qui le demande.
CURLOPT_PROXY_SERVICE_NAME Le nom du service d'authentification proxy. Ajouté en cURL 7.43.0 pour les proxys HTTP et en cURL 7.49.0 pour les proxys SOCK5. Disponible à partir de PHP 7.0.7.
CURLOPT_PROXY_CAINFO Le chemin vers le bundle d'autorité de certification (CA) du proxy. Définir le chemin en tant que chaîne de caractères nomant un fichier tenant un ou plusieurs certificats pour vérifier le proxy HTTPS avec. Cette option est pour se connecter à un proxy HTTPS, pas un serveur HTTPS. Par défaut définit au chemin système où le bundle cacert de libcurl est supposé être stocké. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_CAINFO_BLOB Le nom d'un fichier PEM contenant un ou plusieurs certificats pour vérifier le proxy HTTPS. Cette option est destinée à la connexion à un proxy HTTPS, et non à un serveur HTTPS. La valeur par défaut est définie sur le chemin système où le paquet de certificats cacert de libcurl est supposé être stocké. Disponible à partir de PHP 8.2.0 et libcurl >= cURL 7.77.0.
CURLOPT_PROXY_CAPATH Le dossier tenant plusieurs certificats CA pour vérifier le proxy HTTPS avec. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_CRLFILE Définie le nom de fichier avec la concatenation de CRL (Certificate Revocation List) en format PEM pour utiliser lors de la validation de certificat qui se produit lors de l'échange SSL. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_KEYPASSWD Définie la chaîne de caractères a utiliser comme mot de passe nécessaire pour uriliser la clé privée CURLOPT_PROXY_SSLKEY. Vous n'avez jamais besoin d'une passphrase pour charger un certificat mais vous en avez besoin d'un pour charger votre clé privée. Cette option est pour se connecter à un proxy HTTPS, et non un serveur HTTPS. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_PINNEDPUBLICKEY Définie la clé pubique éplinglé pour le proxy HTTPS. La chaîne de caractères peut être le nom de fichier de votre clé publique. Le format de fichier attendue est "PEM" ou "DER". La chaîne de caractères peut également être un nombre quelconque de hachages sha256 encodés en base64 précédés de "sha256//" et séparé de ";" Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLCERT Le nom de fichier de votre certificat client utilisé pour se connecter au proxy HTTPS. Le format par défaut est "P12" sur Secure Transport et "PEM" sur les autres moteurs, et peut être modifié avec CURLOPT_PROXY_SSLCERTTYPE. Avec NSS ou Secure Transport, ceci peut être le surnom du certificat avec lequel vous souhaitez vous authentifier avec tel qu'il est nommée dans la base de donnée sécurité. Si vous voulez utiliser un fichier du dossier courrent, veuillez le précédez avec le préfix "./", de l'ordre à éviter une confusion avec le surnom. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSLCERTTYPE Le format de vos certificats client utilisé lors de la connexion à un proxy HTTPS. Les formats supporté sont "PEM" et "DER", sauf avec Secure Transport. OpenSSL (version 0.9.3 et ultérieur) et Secure Transport (sur iOS 5 ou ultérieur, ou OS X 10.7 ou ultérieur) supportent aussi les fichier encodé PKCS#12. Par défaut "PEM". Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_SSL_CIPHER_LIST La liste des suites de chiffrement à utiliser pour la connexion au proxy HTTPS. La liste doit être syntaxiquement correcte, elle consiste de une ou plusieurs suites de chiffrement séparé par des deux-points. Les virgules ou espaces sont aussi des séparateurs acceptable mais les deux-points sont normalement utilisé, !, - et + peuvent être utilisé comme des opérations. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLS13_CIPHERS La liste des suites de chiffrement à utiliser pour la connexion TLS 1.3 à un proxy. La liste doit être syntaxiquement correcte, elle consiste de une ou plusieurs suites de chiffrement séparé par des deux-points. Cette option est actuellement seulement utilisé quand curl est compilé pour utiliser OpenSSL 1.1.1 ou ultérieur. Si vous utilisé un backend SSL différent vous pouvez essayer de définir les suites de chiffrement TLS 1.3 en utilisant l'option CURLOPT_PROXY_SSL_CIPHER_LIST. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.61.0. Disponible si compilé avec OpenSSL >= 1.1.1.
CURLOPT_PROXY_SSLKEY Le nom de fichier de votre clé privé utilisé pour se connecter au proxy HTTPS. Le format par défaut est "PEM" et peut être modifié avec CURLOPT_PROXY_SSLKEYTYPE. (iOS et Mac OS X uniquement) Cette option est ignoré si curl est compilé contre Secure Transport. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0. Disponible si TLS est activé.
CURLOPT_PROXY_SSLKEYTYPE Le format de votre clé privée. Format supporté sont "PEM", "DER" et "ENG". Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_PASSWORD Le mot de passe à utiliser pour la méthode d'authentification TLS spécifié avec l'option CURLOPT_PROXY_TLSAUTH_TYPE. Nécessite que l'option CURLOPT_PROXY_TLSAUTH_USERNAME soit aussi définie. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_TYPE La méthode d'authentification TLS utilisé pour la connexion HTTPS. Méthode supporté est "SRP".

Note:

L'authentification Secure Remote Password (SRP) pour TLS fournit une authentification mutuelle si les deux côté ont un secret partagé. Pour utiliser TLS-SRP, vous devez aussi définir les options CURLOPT_PROXY_TLSAUTH_USERNAME et CURLOPT_PROXY_TLSAUTH_PASSWORD.

Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXY_TLSAUTH_USERNAME Tusername à utiliser pour la méthode d'autenthification TLS du proxy HTTPS spécifié avec l'option CURLOPT_PROXY_TLSAUTH_TYPE. Nécessite que l'option CURLOPT_PROXY_TLSAUTH_PASSWORD soit aussi définie. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.52.0.
CURLOPT_PROXYUSERPWD Un nom d'utilisateur et un mot de passe formatés sous la forme "[username]:[password]" à utiliser pour la connexion avec le proxy.
CURLOPT_RANDOM_FILE Un nom de fichier à utiliser pour interroger le générateur de nombre aléatoire pour SSL.
CURLOPT_RANGE La plage de valeurs à récupérer sous la forme "X-Y", où les valeurs de X ou Y peuvent être omises. Le transfert HTTP supporte aussi plusieurs intervalles, séparés par des virgules : "X-Y,N-M".
CURLOPT_REFERER Le contenu de l'en-tête "Referer: " à utiliser dans une requête HTTP.
CURLOPT_SASL_AUTHZID L'identité d'autorisation (authzid) pour le transfert. Applicable uniquement au mécanisme d'authentification SASL PLAIN où elle est facultative. Lorsqu'elle n'est pas spécifiée, seule l'identité d'authentification (authcid) telle que spécifiée par le nom d'utilisateur sera envoyée au serveur, accompagnée du mot de passe. Le serveur déduira l'authzid de l'authcid lorsqu'il n'est pas fourni, qu'il utilisera ensuite en interne.
CURLOPT_SERVICE_NAME Le nom du service d'authentification. Ajouté en cURL 7.43.0. Disponible à partir de PHP 7.0.7.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 Une chaîne contenant 32 digits hexédécimaux. La chaîne doit être la somme MD5 de la clé publique de l'hôte distant, et libcurl rejètera la connexion à l'hôte tant que les sommes MD5 ne corresponderont pas. Cette option n'est valable que pour les transferts SCP et SFTP. Ajouté en cURL 7.17.1.
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 Hachage SHA256 encodé en Base64 de la clé publique de l'hôte distant. Le transfert échouera si le hachage fourni ne correspond pas au hachage fourni par l'hôte distant.
CURLOPT_SSH_PUBLIC_KEYFILE Le nom du fichier pour la clé publique. Si non utilisé, libcurl utilisera pas défaut $HOME/.ssh/id_dsa.pub si la variable d'environnement $HOME est définie, et seulement "id_dsa.pub" si HOME n'est pas définie. Ajouté en cURL 7.16.1.
CURLOPT_SSH_PRIVATE_KEYFILE Le nom du fichier pour la clé privée. Si non utilisé, libcurl utilisera pas défaut $HOME/.ssh/id_dsa si la variable d'environnement $HOME est définie, et seulement "id_dsa" si HOME n'est pas définie. Si le fichier est protégé par un mot de passe, définissez le avec la constante CURLOPT_KEYPASSWD. Ajouté en cURL 7.16.1.
CURLOPT_SSL_CIPHER_LIST Une liste de chiffrements à utiliser avec SSL. Par exemple, RC4-SHA et TLSv1 sont des listes valides de chiffrements.
CURLOPT_SSL_EC_CURVES Une liste de courbes elliptiques délimitées par des deux-points. Par exemple, X25519:P-521 est une liste valide de deux courbes elliptiques. Cette option définit les algorithmes d'échange de clés du client dans la poignée SSL, si le backend SSL utilisé par cURL le prend en charge.
CURLOPT_SSLCERT Le nom de fichier du certificat, au format PEM.
CURLOPT_SSLCERTPASSWD Le mot de passe nécessaire pour utiliser le certificat CURLOPT_SSLCERT.
CURLOPT_SSLCERTTYPE Le format de votre certificat. Les formats supportés sont "PEM" (par défaut), "DER", et "ENG". À partir de OpenSSL 0.9.3, "P12" (pour fichiers encodé PKCS#12) et aussi supporté. Ajouté en cURL 7.9.3.
CURLOPT_SSLENGINE L'identifiant pour le moteur de chiffrement de votre clé privée spécifié dans CURLOPT_SSLKEY.
CURLOPT_SSLENGINE_DEFAULT L'identifiant pour le moteur de chiffrement utilisé pour les opérations de chiffrement asymétrique.
CURLOPT_SSLKEY Un nom de fichier contenant votre clé privée SSL.
CURLOPT_SSLKEYPASSWD

Le mot de passe secret utilisé par votre clé SSL privée spécifié dans CURLOPT_SSLKEY.

Note:

Du fait que cette option contient un mot de passe sensible, souvenez-vous de conserver le script PHP qui le contient en toute sécurité.

CURLOPT_SSLKEYTYPE Le type de votre clé SSL privée spécifié dans CURLOPT_SSLKEY. Les types de clé supportés sont "PEM" (par défaut), "DER", et "ENG".
CURLOPT_TLS13_CIPHERS La liste des suites de chiffrement à utiliser pour la connexion TLS 1.3. La liste doit être syntaxiquement correcte, elle consiste de un ou plusieurs chaînes de suites de chiffrement séparé par des deux-points. Cette option est actuellement uniquement quand curl est compilé pour utiliser OpenSSL 1.1.1 ou ultérieur. Si vous utiliser un backend SSL différent vous pouvez essayer de définir les suites de chiffrement TLS 1.3 en utilisant l'option CURLOPT_SSL_CIPHER_LIST. Disponible à partir de PHP 7.3.0 et libcurl >= cURL 7.61.0. Disponible quand compilé avec OpenSSL >= 1.1.1.
CURLOPT_UNIX_SOCKET_PATH Permet l’utilisation de sockets de domaine Unix en tant que point de connexion et définit le chemin à la chaîne de caractères fournit. Ajouté en cURL 7.40.0. Disponible à partir de PHP 7.0.7.
CURLOPT_URL L'URL à récupérer. Vous pouvez aussi choisir cette valeur lors de l'appel à curl_init().
CURLOPT_USERAGENT Le contenu de l'en-tête "User-Agent: " à utiliser dans une requête HTTP.
CURLOPT_USERNAME Le nom d'utilisateur à utiliser lors de l'authentification. Ajouté en cURL 7.19.1.
CURLOPT_PASSWORD Le mot de passe à utiliser lors de l'authentification. Ajouté en cURL 7.19.1.
CURLOPT_USERPWD Un nom d'utilisateur et un mot de passe formatés sous la forme "[username]:[password]" à utiliser pour la connexion.
CURLOPT_XOAUTH2_BEARER Spécifie le jeton d'accès OAuth 2.0. Ajouté en cURL 7.33.0. Disponible à partir de PHP 7.0.7.

value doit être un tableau pour les valeurs suivantes du paramètres option :

Option Définir value à Notes
CURLOPT_CONNECT_TO Connecte à un hôte et à un port spécifiques au lieu de l'hôte et du port de l'URL. Accepte un tableau de chaîne de caractères ave le format HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT. Ajouté en cURL 7.49.0. Disponible à partir de PHP 7.0.7.
CURLOPT_HTTP200ALIASES Un tableau de réponses HTTP 200 qui sera traité comme réponses valides et non comme des erreurs. Ajouté en CURL 7.10.3.
CURLOPT_HTTPHEADER Un tableau de champs d'en-têtes HTTP à définir, au format array('Content-type: text/plain', 'Content-length: 100')
CURLOPT_POSTQUOTE Un tableau de commandes FTP à exécuter sur le serveur après que la requête FTP se soit exécutée.
CURLOPT_PROXYHEADER Un tableau d'en-têtes HTTP personalisé à passer aux proxies. Ajouté en cURL 7.37.0. Disponible à partir de PHP 7.0.7.
CURLOPT_QUOTE Un tableau de commandes FTP à exécuter sur le serveur avant la requête FTP.
CURLOPT_RESOLVE Fournissez une adresse personnalisée pour une paire hôte / port spécifique. Un tableau de chaîne de caractères de nom d'hôte, de port et d'adresse IP, chaque élément étant séparé par deux-points. Dans le format : array("example.com:80:127.0.0.1") Ajouté en cURL 7.21.3.

value doit être une ressource (utilisant fopen(), par exemple) pour les valeurs suivantes du paramètre option :

Option Définissez le paramètre value à
CURLOPT_FILE Le fichier où sera écrit le transfert. Par défaut, STDOUT (la fenêtre du navigateur).
CURLOPT_INFILE Le fichier lu par le transfert lors du chargement.
CURLOPT_STDERR Un chemin alternatif à utiliser pour afficher les erreurs au lieu de STDERR.
CURLOPT_WRITEHEADER Le fichier où sera écrit les parties d'en-tête du transfert.

value doit être le nom d'une fonction ou d'une Closure valide pour les valeurs suivantes du paramètres option :

Option Définir value à Note
CURLOPT_HEADERFUNCTION Une fonction de rappel acceptant deux paramètres. Le premier est la ressource cURL, le second, une chaîne de caractères avec les données d'en-têtes à écrire. Ces données d'en-têtes doivent être écrites par cette fonction de rappel. Le nombre d'octets écrit sera retourné.  
CURLOPT_PASSWDFUNCTION Une fonction de rappel qui prend trois paramètres. Le premier est la ressource CURL, le second, une chaîne contenant un mot de passe de prompt et le troisième, est la longueur maximale du mot de passe. Retourne une chaîne contenant le mot de passe. Supprimée à partir de PHP 7.3.0.
CURLOPT_PROGRESSFUNCTION

Une fonction de rappel qui prend cinq arguments. Le premier est la ressource cURL, le second est le nombre total d'octets attendu à télécharger pendant le transfert, le troisième est le nombre d'octets téléchargés, le quatrième est le total d'octets attendu à uploader pendant le transfert, et le cinquième est le nombre d'octets uploadés.

Note:

The callback is only called when the CURLOPT_NOPROGRESS option is set to false.

Return a non-zero value to abort the transfer. In which case, the transfer will set a CURLE_ABORTED_BY_CALLBACK error.

 
CURLOPT_READFUNCTION Une fonction de rappel qui prend trois paramètres. Le premier est une ressource cURL, le second, une ressource de flux fournie à cURL via l'option CURLOPT_INFILE, et le troisième, la quantité maximale de données à lire. La fonction de rappel doit retourner une chaîne dont la taille est inférieure ou égale à la quantité de données demandées, habituellement en les lisant depuis la ressource de flux passée. Elle doit retourner une chaîne vide pour signaler la fin EOF.  
CURLOPT_WRITEFUNCTION Une fonction de rappel qui prend deux paramètres. Le premier est la ressource CURL et le second, une chaîne contenant les données à écrire. En utilisant cette fonction de rappel, il devient de votre responsabilité d'écrire les données. Doit retourner le nombre exact d'octets écrits ou le transfert échouera avec une erreur.  
CURLOPT_XFERFUNCTION Une fonction de rappel qui prend deux arguments. A un objectif identique à CURLOPT_PROGRESSFUNCTION mais est plus récente et est l'option préféree de cURL. Ajouté en cURL 7.32.0. Disponible à partir de PHP 8.2.0.

Autres valeurs :

Option Définit le paramètre value en
CURLOPT_SHARE Un résultat de la fonction curl_share_init(). Fait que le gestionnaire cURL va utiliser les données depuis le gestionnaire partagé.

Valeurs de retour

Cette fonction retourne true en cas de succès ou false si une erreur survient.

Historique

Version Description
8.0.0 handle attend désormais une instance de CurlHandle; auparavant; une resource était attendue.
7.3.15, 7.4.3 Introduction de la constante CURLOPT_HTTP09_ALLOWED.
7.3.0 Introduit 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 et CURLOPT_TLS13_CIPHERS.
7.0.7 Introduit 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 et CURLSSLOPT_NO_REVOKE.

Exemples

Exemple #1 Initialisation d'une nouvelle session CURL et recherche d'une page Web

<?php
// Création d'une ressource cURL
$ch = curl_init();

// Définition de l'URL et autres options appropriées
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// Récupération de l'URL et passage au navigateur
curl_exec($ch);

// Fermeture de la ressource cURL et libération des ressources systèmes
curl_close($ch);
?>

Notes

Note:

Le fait de passer un tableau à la constante CURLOPT_POSTFIELDS encodera les données comme multipart/form-data, tandis que le fait de passer une chaîne encodée URL encodera les données comme application/x-www-form-urlencoded.

Voir aussi

add a note

User Contributed Notes 68 notes

up
221
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
50
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
13
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
32
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
14
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
3
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
29
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
6
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
37
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
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
26
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
18
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
15
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
16
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
2
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
14
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
9
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
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
32
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
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
21
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
5
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
9
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
3
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
3
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
11
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
7
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
14
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
5
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
12
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
7
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
11
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
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
8
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
3
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
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
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
5
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
7
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
3
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
10
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
8
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
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
8
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
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
6
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
4
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
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
3
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
4
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
3
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
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
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
1
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
1
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
4
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_CAINFO, getcwd().'/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
3
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
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
2
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
2
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
1
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
1
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
2
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
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
alexchexes at gmail dot com
7 months ago
If you want cURL to successfully write cookies to a file specified with CURLOPT_COOKIEJAR, ensure that cURL has the necessary permissions to modify the file if it already exists.

I spent nearly a day trying to understand why cURL wasn't saving cookies to an existing file, even though I could easily modify the exact same file using file_put_contents(). Moreover, cURL itself could create the same file and save cookies, but only if it didn't previously exist.

Ultimately, the issue was related to file ownership. I was working within WSL2, inside a symlinked Windows directory. The [automount]"metadata" in wsl.conf was not set, causing every file created from PHP to have the default owner, which differed from the user running PHP.

Once I configured wsl.conf and then changed the ownership of the entire directory to match the user running PHP, cookies were successfully written to any file without any issues.
up
1
Niki Romagnoli
11 months ago
Set order when using CURLOPT_POST and CURLOPT_POSTFIELDS *matters*.
Setting CURL_POST to true will ERASE any previous CURLOPT_POSTFIELDS using an array. Result is request be a POST with empty body.

CURLOPT_POSTFIELDS will set CURLOPT_POST to true for you, no need for repeat.
If you really need to set both, then either:
- set CURLOPT_POST *before* CURLOPT_POSTFIELDS
- or don't use array and convert CURLOPT_POSTFIELDS to URL-encoded string, it will not be affected this way (ie. <?php curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($yourArray)); ?> )
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'));
?>
To Top