CakeFest 2024: The Official CakePHP Conference

curl_setopt

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

curl_setoptBir cURL aktarım seçeneği tanımlar

Açıklama

curl_setopt(CurlHandle $tanıtıcı, int $seçenek, mixed $değer): bool

Belirtilen cURL oturum tanıtıcısı üzerinde bir seçenek tanımlar.

Bağımsız Değişkenler

tanıtıcı

curl_init() işlevinden dönen bir cURL tanıtıcısı.

seçenek

Atanacak CURLOPT_XXX seçeneği.

değer

Atanacak seçenek değeri.

değer bağımsız değişkenine aşağıdaki seçenek'ler için bir mantıksal (bool) değer atanmalıdır:

Seçenek Atanacak değer Ek bilgi
CURLOPT_AUTOREFERER Bir Location: yönlendirmesini izleyen bir isteğin Referer: başlığının otomatik olarak atanması için true olmalıdır.  
CURLOPT_COOKIESESSION Oturumu yeni bir çerez oturumu olarak imlemek için true olmalıdır. libcurl'un önceki oturumdan yüklenecek oturum çerezlerini yoksaymasına sebep olur. Öntanımlı olarak libcurl, oturum çerezi olup olmadıklarına bakmaksızın tüm çerezleri daima saklar ve yükler. Oturum çerezleri için belli bir zaman aşımı yoktur ve atandıkları oturum boyunca etkindirler.  
CURLOPT_CERTINFO Güvenli aktarımlarda SSL sertifika bilgisini standart hataya çıktılamak için true. cURL 7.19.1'de eklendi. Etkisi oması için CURLOPT_VERBOSE gerekir.
CURLOPT_CONNECT_ONLY Bağlantıyı kurup gerekli tüm vekil kimlik kanıtlamasını yapmasını ama hiçbir veryi aktarmamasını kütüphaneye söylemek için true. Bu seçenek HTTP, SMTP ve POP3 için gerçeklenmiştir. cURL 7.15.2'de eklendi.
CURLOPT_CRLF Aktarım sırasında Unix satırsonlarını CRLF satırsonlarına dönüştürmek için true olmalıdır.  
CURLOPT_DISALLOW_USERNAME_IN_URL Bir kullanıcı adı içeren URL'lere izin vermemek için true. Kullanıcı adlarına öntanımlı olarak izin verilir. cURL 7.61.0'da eklendi. PHP 7.3.0'dan beri kullanılabilir.
CURLOPT_DNS_SHUFFLE_ADDRESSES Bir isim çözümlendiğinde ve birden fazla IP adresi döndürüldüğünde, tüm döndürülen adreslerin sırasını rastgele bir sırayla kullanılacak şekilde karıştırmak için true. Bu, IPv4'ün IPv6'dan önce veya tam tersi şekilde kullanılmasına neden olabilir. cURL 7.60.0'da eklendi. PHP 7.3.0'dan beri kullanılabilir..
CURLOPT_HAPROXYPROTOCOL Bağlantının başlangıcında bir HAProxy PROXY protokolü v1 başlığı göndermek için true. Öntanımlı eylem bu başlığı göndermemektir. cURL 7.60.0'da eklendi. PHP 7.3.0'dan beri kullanılabilir..
CURLOPT_SSH_COMPRESSION Yerleşik SSH sıkıştırmasını etkin kılmak için true. Bu bir istektir, emir değil; sunucu yerine getirmeyebilir. cURL 7.56.0'da eklendi. PHP 7.3.0'dan beri kullanılabilir.
CURLOPT_DNS_USE_GLOBAL_CACHE Küresel DNS önbelleğini kullanmak için true olmalıdır. Bu seçenek evreler bakımından güvenli değildir. PHP evresiz kullanım için derlenmişse şartlı ve öntanımlı olarak etkindir (CLI, FCGI, Apache2-Prefork, vb.).  
CURLOPT_FAILONERROR Dönen HTTP kodunun 400'e eşit veya büyük olması durumunda ayrıntılı olarak başarısız olmak için true olmalıdır. Öntanımlı davranış kodu yok sayıp sayfayı normal olarak döndürmektir.  
CURLOPT_SSL_FALSESTART TLS yanlış başlatmayı etkinleştirmek için true. cURL 7.42.0'da eklendi. PHP 7.0.7'dan beri kullanılabilir.
CURLOPT_FILETIME Uzak belgenin değişiklik tarihi alınmaya çalışılacaksa true olmalıdır. Bu değer, curl_getinfo() ile CURLINFO_FILETIME seçeneği kullanılarak alınabilir.  
CURLOPT_FOLLOWLOCATION HTTP başlığının bir parçası olarak sunucunun gönderdiği "Location: " başlığını izlemek için true olmalıdır. Ayrıca, bkz. CURLOPT_MAXREDIRS  
CURLOPT_FORBID_REUSE İşlem bittiğinde yeniden kullanım için havuzlanmaksızın ve beklemeksizin bağlantının mutlaka kapatılması için true olmalıdır.  
CURLOPT_FRESH_CONNECT Önbellektekini kullanmaksızın yeni bir bağlantı açmak için true olmalıdır.  
CURLOPT_FTP_USE_EPRT Etkin FTP indirmeleri yapılırken EPRT (ve LPRT) kullanmak için true olmalıdır. EPRT ve LPRT'yi iptal edip sadece PORT kullanmak için false kullanın.  
CURLOPT_FTP_USE_EPSV PASV'ye dönmeden önce FTP aktarımı için önce EPSV komutunu denemek için true olmalıdır.  
CURLOPT_FTP_CREATE_MISSING_DIRS Bir FTP işlemi şu anda mevcut olmayan bir dosya yolu ile karşılaştığında eksik dizinleri oluşturmak için true.
CURLOPT_FTPAPPEND Uzak dosyanın üzerine yazmak yerine sonuna ekleme yapmak için true olmalıdır.  
CURLOPT_TCP_NODELAY Ağdaki küçük paketlerin sayısını en aza indirmeye çalışan TCP'nin Nagle algoritmasını devre dışı bırakmak için true. libcurl 7.11.2 ve üstü ile derlenmiş sürümlerde kullanılabilir.
CURLOPT_FTPASCII CURLOPT_TRANSFERTEXT için takma addır; onun yerine bunu kullanın.  
CURLOPT_FTPLISTONLY Sadece FTP dizinindeki isimler listelenecekse true olmalıdır.  
CURLOPT_HEADER Çıktıda başlık bulunması için true olmalıdır.  
CURLINFO_HEADER_OUT Tanıtıcının istek dizesini izlemek için true. CURLINFO_ öneki özellikle konmuştur.
CURLOPT_HTTP09_ALLOWED HTTP/0.9 yanıtlarına izin verilecek mi? libcurl 7.66.0 itibariyle false öncesinde true. libcurl >= 7.64.0 ile derlenmiş PHP 7.3.15 ve 7.4.3 itibariyle kullanılabilir.
CURLOPT_HTTPGET HTTP istek yönteminin GET olması için true olmalıdır. GET öntanımlı olduğundan bu sadece istek yöntemi değiştiğinde işe yarar.  
CURLOPT_HTTPPROXYTUNNEL Belirtilen HTTP vekili üzerinden tünel kullanılacaksa true olmalıdır.  
CURLOPT_HTTP_CONTENT_DECODING Ham HTTP gövdesini almak için false. libcurl >= 7.16.2 ile derlenmiş sürümlerle kullanılabilir.
CURLOPT_KEEP_SENDING_ON_ERROR Döndürülen HTTP kodu 300'e eşit veya daha büyükse istek gövdesini göndermeye devam etmek için true. Öntanımlı eylem göndermeyi durdurmak ve akışı veya bağlantıyı kapatmak olacaktır. Elle NTLM kimlik doğrulaması için uygundur. Çoğu uygulamanın bu seçeneğe ihtiyacı yoktur. libcurl >= 7.51.0 ile derlenmiş PHP 7.3.0 ve üstü ile kullanılabilir.
CURLOPT_MUTE cURL işlevleriyle ilgili olarak tamamen sessiz kalınması için true olmalıdır. cURL 7.15.5'te kaldırıldı. (Yerine CURLOPT_RETURNTRANSFER kullanılabilir)
CURLOPT_NETRC Bağlantı kurulan uzak site için kullanıcı adını ve parolasını bulmak amacıyla ~/.netrc dosyasına bakılmasını sağlamak için true olmalıdır.  
CURLOPT_NOBODY Çıktıdaki gövdeyi dışlamak için true olmalıdır. Ardından istek yöntemi HEAD yapılır. Bunu false olarak değiştirmek yöntemi GET yapmaz.  
CURLOPT_NOPROGRESS

cURL aktarımının gelişim göstergesini kapatmak için true olmalıdır.

Bilginize:

PHP bu seçeneğe öntanımlı olarak true atar. Bu sadece hata ayıklama amacıyla değiştirlmelidir.

 
CURLOPT_NOSIGNAL PHP sürecine bir sinyal gönderilmesine sebep olan cURL işlevlerini yoksaymak için true olmalıdır. Çok evreli SAPI'lerde, öntanımlı olarak böyledir; dolayısıyla zaman aşımı seçenekleri hala kullanılabilir olur. cURL 7.10'da eklendi.
CURLOPT_PATH_AS_IS Nokta nokta dizilerini işlememek için true. cURL 7.42.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_PIPEWAIT Boruhattı ve çoklamaları beklemek için true. cURL 7.43.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_POST Normal bir HTTP POST yapmak için true olmalıdır. Bu, HTML formlarında sıklıkla kullanılan normal application/x-www-form-urlencoded çeşididir.  
CURLOPT_PUT Bir dosyaya HTTP PUT yapmak için true olmalıdır. Bu dosya CURLOPT_INFILE ve CURLOPT_INFILESIZE ile atanmalıdır.  
CURLOPT_RETURNTRANSFER Aktarımı doğrudan çıktılamak yerine bir dizge olarak curl_exec() işlevinden döndürmek için true olmalıdır.  
CURLOPT_SASL_IR İlk yanıtı ilk pakette göndermeyi etkinleştirmek için true. cURL 7.31.10'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_SSL_ENABLE_ALPN HTTP2 ile uzlaşmak için kullanılan SSL anlaşmasında (SSL arka uç libcurl bunu destekliyorsa) ALPN'yi devredışı bırakmak için false cURL 7.36.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_SSL_ENABLE_NPN HTTP2 ile uzlaşmak için kullanılan SSL anlaşmasında (SSL arka uç libcurl bunu destekliyorsa) NPN'yi devredışı bırakmak için false cURL 7.36.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_SSL_VERIFYPEER cURL'un eş sertifikasını doğrulamayı durdurması için false olmalıdır. Doğrulayıcı diğer sertifikalar CURLOPT_CAINFO seçeneği ile belirtilebileceği gibi CURLOPT_CAPATH seçeneği ile bir sertifika dizini de belirtilebilir. cURL 7.10 itibariyle öntanımlı olarak true'dur. Öntanımlı paket cURL 7.10'dan itibaren yüklenmiştir.
CURLOPT_SSL_VERIFYSTATUS Sertifika durumunu doğrulamak için true. cURL 7.41.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_PROXY_SSL_VERIFYPEER cURL'nin eşin sertifikasını doğrulamasını durdurmak için false Doğrulamak için alternatif sertifikalar CURLOPT_CAINFO seçeneğiyle veya sertifika dizini CURLOPT_CAPATH seçeneğiyle belirtilebilir. false olarak ayarlandığında, eş sertifika doğrulaması ne olursa olsun başarılı olur. Öntanımlı olarak true. libcurl >= cURL 7.52.0 ve PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_SAFE_UPLOAD Daima true, CURLOPT_POSTFIELDS içindeki dosyaları karşıya yüklemek için @ öneki desteğini devre dışı bırakır, böylece @ ile başlayan değerler güvenle alan olarak aktarılabilir. Bunun yerine karşıya yükleme yaparken CURLFile kullanılabilir.
CURLOPT_SUPPRESS_CONNECT_HEADERS CURLOPT_HTTPPROXYTUNNEL kullanıldığında ve bir bağlantı isteği yapıldığında, CURLOPT_HEADERFUNCTION ve CURLOPT_WRITEFUNCTION kullanıcı geri arama işlevlerinden vekil bağlantı yanıtı üstbilgilerini bastırmak için true. cURL 7.54.0'da eklendi. PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_TCP_FASTOPEN TCP Hızlı Açmayı etkinleştirmek için true. cURL 7.49.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_TFTP_NO_OPTIONS TFTP seçenekleri isteklerini göndermemek için true. cURL 7.48.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_TRANSFERTEXT FTP aktarımlarında ASCII kip kullanmak için true olmalıdır. LDAP için veri, HTML yerine salt metin olarak alınır. Windows sistemlerinde, STDOUT'a ikil kip atanmaz.  
CURLOPT_UNRESTRICTED_AUTH (CURLOPT_FOLLOWLOCATION kullanarak) Location: yönlendirmelerini izlerken konut ismi değişse bile, kullanıcı ve parola gönderimini sağlamak için true olmalıdır.  
CURLOPT_UPLOAD Karşıya yüklemeye hazır olmak için true olmalıdır.  
CURLOPT_VERBOSE Ayrıntılı bilgi çıktılanması için true olmalıdır. Çıktıyı standart hataya veya CURLOPT_STDERR kullanarak belirtilen dosyaya yazar.  

değer bağımsız değişkenine aşağıdaki seçenek'ler için bir tamsayı atanmalıdır:

Seçenek Atanacak değer Ek bilgi
CURLOPT_BUFFERSIZE Okuma için kullanılacak tamponun boyutu. Ancak, bu isteğin yerine getirileceğinin bir garantisi yoktur. cURL 7.10'da eklendi.
CURLOPT_CONNECTTIMEOUT Saniye cinsinden bağlantının deneneceği süre. Bağlantının sonsuza kadar beklenmesi için 0 kullanın.  
CURLOPT_CONNECTTIMEOUT_MS Milisaniye cinsinden bağlantının deneneceği süre. Bağlantının sonsuza kadar beklenmesi için 0 kullanın. Libcurl, standart sistem adı çözümleyicisini kullanmak üzere derlenmişse, bağlantının bu bölümü, izin verilen bir saniyelik minimum zaman aşımı ile tam saniyelik çözünürlüğü kullanmaya devam edecektir. cURL 7.16.2'de eklendi.
CURLOPT_DNS_CACHE_TIMEOUT Saniye cinsinden DNS girdilerinin bellekte kalma süresi. Bu seçeneğin öntanımlı değeri 120 saniyedir.  
CURLOPT_EXPECT_100_TIMEOUT_MS Milisaniye cinsinden Expect: cinsinden 100 devam yanıtları için zaman aşımı. Öntanımlı 1000 milisaniyedir. cURL 7.36.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS Mutlu gözler algoritması için ipv6'yı kullanmaya başlayın. Mutlu gözler, milisaniyeler için önce IPv6'yı tercih ederek, çift yığıtlı sunucular için hem IPv4 hem de IPv6 adreslerine bağlanmaya çalışır. Şu anda 200 milisaniye olan CURL_HET_DEFAULT öntanımlıdır. cURL 7.59.0'da eklendi. PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_FTPSSLAUTH FTP kimlik doğrulama yöntemi (etkinse): CURLFTPAUTH_SSL (önce SSL denenir), CURLFTPAUTH_TLS (önce TLS denenir) veya CURLFTPAUTH_DEFAULT (cURL karar verir). cURL 7.12.2'de eklendi.
CURLOPT_HEADEROPT Başlıklar ile başa çıkmak için aşağıdaki sabitlerden biri: CURLHEADER_UNIFIED: CURLOPT_HTTPHEADER içinde belirtilen başlıklar hem sunuculara hem de vekillere yapılan isteklerde kullanılacaktır. Bu seçenek etkinleştirildiğinde, CURLOPT_PROXYHEADER herhangi bir etkiye sahip olmayacaktır. CURLHEADER_SEPARATE: CURLOPT_HTTPHEADER başlıklarının bir vekile değil, yalnızca bir sunucuya gönderilmesini sağlar. Vekil başlıklarının kullanılabilmesi için CURLOPT_PROXYHEADER ile ayarlanması gerekir. Bir vekile CONNECT olmayan bir istek gönderilirse, libcurl'un hem sunucu başlıklarını hem de vekil başlıklarını göndereceğini unutmayın. CONNECT yapılırken, libcurl CURLOPT_PROXYHEADER başlıklarını yalnızca vekile ve ardından CURLOPT_HTTPHEADER başlıklarını yalnızca sunucuya gönderir. cURL 7.42.1 itibariyle CURLHEADER_SEPARATE ve öncesinde CURLHEADER_UNIFIED öntanımlıdır. cURL 7.37.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (öntanımlı olup hangi sürümün kullanılacağına CURL karar verir). CURL_HTTP_VERSION_1_0 (HTTP/1.0 zorlanır), CURL_HTTP_VERSION_1_1 (HTTP/1.1 zorlanır), CURL_HTTP_VERSION_2_0 (HTTP 2 için çabalar), CURL_HTTP_VERSION_2 (CURL_HTTP_VERSION_2_0 için takma ad), CURL_HTTP_VERSION_2TLS (sadece TLS (HTTPS) üzerinden HTTP 2 için çabalar) veya CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (HTTP/1.1 yükseltmesi olmadan HTTP/2 kullanarak TLS dışı HTTP istekleri yapar).  
CURLOPT_HTTPAUTH

HTTP kimlik doğrulama yöntem(ler)i: CURLAUTH_BASIC, CURLAUTH_DIGEST, CURLAUTH_GSSNEGOTIATE, CURLAUTH_NTLM, CURLAUTH_AWS_SIGV4, CURLAUTH_ANY ve CURLAUTH_ANYSAFE.

Birden fazla yöntem belirtilecekse sabitler arasında bitsel VEYA işleci kullanılabilir. Bu takdirde, cURL belirtilen yöntemlerden hangisinin sunucu tarafından en iyi desteklendiğini saptamaya çalışır ve onu kullanır.

CURLAUTH_ANY tüm bitleri etkin kılar. cURL otomatik olarak en güvenlisini seçer.

CURLAUTH_ANYSAFE sabiti CURLAUTH_BASIC dışında tüm bitleri etkin kılar. cURL otomatik olarak en güvenlisini seçer.

 
CURLOPT_INFILESIZE Dosya karşıya yüklenirken dosyanın bayt cinsinden tahmini boyutu. Tam olarak neyin gönderileceği CURLOPT_READFUNCTION'a bağlı olduğundan, bu seçeneğin kullanılmasının libcurl'nin daha fazla veri göndermesini durdurmayacağını unutmayın.  
CURLOPT_LOW_SPEED_LIMIT PHP'nin aktarımın çok yavaş olduğunu varsayarak çıkmasından önce, CURLOPT_LOW_SPEED_TIME süresince aktarımda kalacağı, saniyedeki bayt sayısı olarak aktarım hızı.  
CURLOPT_LOW_SPEED_TIME PHP'nin aktarımın çok yavaş olduğunu varsayarak çıkması için, aktarım hızının CURLOPT_LOW_SPEED_LIMIT'in altında kalacağı, saniye cinsinden aktarım süresi.  
CURLOPT_MAIL_RCPT_ALLLOWFAILS Bazı alıcılar için RCPT TO komutunun başarısız olmasına izin verir. Birden fazla alıcıya veri gönderirken, alıcılardan en az biri RCPT TO komutunun hata döndürmesine neden olursa cURL varsayılan olarak SMTP görüşmesini iptal eder. Bu seçenek, cURL'ye hataları yok saymasını ve kalan geçerli alıcılarla devam etmesini söyler. Tüm alıcılar RCPT TO hatalarını tetiklerse ve bu seçenek etkinse, cURL SMTP görüşmesini iptal eder ve son RCPT TO komutundan alınan hatayı döndürür.
CURLOPT_MAXAGE_CONN Mevcut bir bağlantının yeniden kullanım için değerlendirilmesi için izin verilen azami boşta kalma süresi. Varsayılan azami değer, 118 saniyedir.
CURLOPT_MAXFILESIZE_LARGE İndirilmesine izin verilen dosya için azami bayt miktarı. İstenen dosya bu değerden büyükse aktarım başlamaz ve CURLE_FILESIZE_EXCEEDED döner. İndirme öncesi dosya boyutları her zaman bilinmez ve dosya aktarımı bittiğinde dosya boyutu bu değerden büyük olacak olsa bile böyle dosyalarda bu seçenek etkisizdir.
CURLOPT_MAXLIFETIME_CONN Bağlantının oluşturulmasından bu yana, mevcut bir bağlantının yeniden kullanım için değerlendirilmesine izin verilen, saniye cinsinden azami süre. Önbellekte bu değerden daha eski bir bağlantı bulunursa devam eden aktarımlar tamamlandıktan sonra bağlantı kapatılır. Varsayılan 0 saniye olup seçeneğin devre dışı bırakıldığı ve tüm bağlantıların yeniden kullanılmaya uygun olduğu anlamına gelir.
CURLOPT_MAXCONNECTS İzin verilen kalıcı bağlantıların azami sayısı. Bu sınıra ulaşıldığında açık bağlantı sayısı artışını engellemek için önbellektekilerden en eski olanı kapatılır.  
CURLOPT_MAXREDIRS İzlenecek HTTP yönlendirmelerinin azami sayısı. CURLOPT_FOLLOWLOCATION ile birlikte kullanılır. Sonsuz yönlendirmeyi engellemek için atanan öntanımlı değer 20'dir. 1 atamak sonsuz yönlendirmeye izin verir, 0 ise tüm yönlendirmeleri reddeder.  
CURLOPT_PORT Bağlantı için kullanılacak ikincil port numarası.  
CURLOPT_POSTREDIR CURLOPT_FOLLOWLOCATION ayarlandığında ve belirli bir yönlendirme türü gerçekleştiğinde HTTP POST yönteminin korunması gerekiyorsa 1 (301 Kalıcı Olarak Taşındı), 2 (302 Bulundu) ve 4 (Diğerine Bakın) için bit maskesi. cURL 7.19.1'de eklendi.
CURLOPT_PROTOCOLS

CURLPROTO_* değerlerinden oluşan bir bit maskesi. libcurl'un aktarımda kullanabileceği protokolleri belirler. Bu seçenek, kurulu libcurl'un geniş bir protokol çeşidini desteklemesini gerektirir. Seçenekle bu protokollerin bir alt kümesi belirtilebilir. libcurl öntanımlı olarak, desteklediği tüm protokolleri kabul edecektir. Ayrıca, CURLOPT_REDIR_PROTOCOLS seçeneğine de bakınız.

Olası protokol seçenekleri: 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

cURL 7.19.4'te eklendi.
CURLOPT_PROXYAUTH Vekil bağlantı için kullanılacak HTTP kimlik doğrulama yöntem(ler)i. CURLOPT_HTTPAUTH seçeneğindeki bit maskesi kullanılır. Vekil kimlik doğrulaması için şimdilik sadece CURLAUTH_BASIC ve CURLAUTH_NTLM desteklenmektedir. cURL 7.10.7'de eklendi.
CURLOPT_PROXYPORT Bağlanılacak vekil port numarası. Port numarası CURLOPT_PROXY ile de atanabilir.  
CURLOPT_PROXYTYPE CURLPROXY_HTTP (öntanımlı), CURLPROXY_SOCKS4, CURLPROXY_SOCKS5, CURLPROXY_SOCKS4A veya CURLPROXY_SOCKS5_HOSTNAME olabilir. cURL 7.10'da eklendi.
CURLOPT_REDIR_PROTOCOLS CURLPROTO_* değerlerinden oluşan bir bit maskesi. CURLOPT_FOLLOWLOCATION etkin olduğu takdirde, bir yönlendirme izlenirken libcurl'un aktarımda kullanacağı protokoller belirtilir. Bu seçenek, yönlendirmelerde aktarımın belli protokollerle sınırlanmasına imkan verir. libcurl öntanımlı olarak FILE ve SCP haricinde tüm protokollere izin verir. Bu davranış, izlemelerde tüm protokollerin koşulsuz olarak desteklendiği 7.19.4 öncesi sürümlerden farklıdır. Protokol sabitleri için CURLOPT_PROTOCOLS seçeneğine de bakınız. cURL 7.19.4'te eklendi.
CURLOPT_RESUME_FROM Bayt cinsinden aktarımın devam ettirileceği konum.
CURLOPT_SOCKS5_AUTH

Kullanılacak SOCKS5 kimlik kanıtlama yöntemleri. Seçenekler: CURLAUTH_BASIC, CURLAUTH_GSSAPI, CURLAUTH_NONE.

Birden fazla yntem belirtmek için bitsel VEYA | işleci kullanılabilir. Bu yapılırsa, cURL hangi yöntemleri desteklediğini görmek için sunucuyu yoklar ve en iyisini seçer.

CURLAUTH_BASIC kullanıcı/parola kimlik kanıtlamasına izin verir.

CURLAUTH_GSSAPI GSS-API kimlik kanıtlamasına izin verir.

CURLAUTH_NONE hiçbir kimlik kanıtlamasına izin vermez.

CURLAUTH_BASIC|CURLAUTH_GSSAPI öntanımlıdır. Güncel kullanıcı ismini ve parolayı CURLOPT_PROXYUSERPWDseçeneği ile atayın.

curl >= 7.55.0 ve PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_SSL_OPTIONS SSL davranış seçeneklerini, aşağıdaki sabitlerden herhangi birinin bit maskesidir: CURLSSLOPT_ALLOW_BEAST: SSL3 ve TLS1.0 protokollerinde bir güvenlik açığı için herhangi bir geçici çözüm kullanmaya çalışmaz. CURLSSLOPT_NO_REVOKE: Bu tür bir davranışın mevcut olduğu SSL arka uçları için sertifika iptal denetimlerini devre dışı bırakır. CURLSSLOPT_AUTO_CLIENT_CERT: Sunucu tarafından istendiğinde, kimlik doğrulama için istemci sertifikası otomatik olarak bulunup kullanılır. Bu seçenek yalnızca Schannel (yerel Windows SSL kitaplığı) için desteklenir. CURLSSLOPT_NATIVE_CA: Sertifika doğrulaması için işletim sisteminin yerel CA deposunu kullanılır. OpenSSL kullanmak üzere oluşturulduğunda yalnızca Windows üzerinde çalışır. Bu seçenek deneyseldir ve davranış değişebilir. CURLSSLOPT_NO_PARTIALCHAIN: cURL'nin varsayılan olarak kabul ettiği "kısmi" sertifika zincirleri kabul edilmez. Bu seçenek yalnızca OpenSSL için desteklenir ve zincir bir kök sertifikayla değil de bir ara sertifikayla biterse sertifika doğrulamasında başarısız olur. CURLSSLOPT_REVOKE_BEST_EFFORT: Bu tür davranışların mevcut olduğu SSL arka uçları için eksik veya çevrimdışı dağıtım noktaları olması durumunda sertifika iptal denetimleri yok sayılır. Bu seçenek yalnızca Schannel (yerel Windows SSL kitaplığı) için desteklenir. CURLSSLOPT_NO_REVOKE ile birleştirilirse ikincisi önceliklidir. cURL 7.25.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_SSL_VERIFYHOST Common Name veya Subject Alternate Name alanının varlığının yanında sağlanan konak ismi ile eşleşmenin de aranması için 2, isimlere bakmak için 0 olmalıdır. 1 kullanılmamalıdır. Üretim ortamlarında bu seçeneğin değeri 2 (öntanımlıdır) olarak tutulmalıdır. 1 değeri için destek cURL 7.28.1'de kaldırıldı.
CURLOPT_SSLVERSION CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5), CURL_SSLVERSION_TLSv1_2 (6) veya CURL_SSLVERSION_TLSv1_3 (7) sabitlerinden biri. Azami TLS sürümü CURL_SSLVERSION_MAX_* sabitlerinden biri kullanarak atanabilir. CURL_SSLVERSION_* sabitlerinden biri ile CURL_SSLVERSION_MAX_* sabitlerinden birini VEYAlamak da mümkündür. CURL_SSLVERSION_MAX_DEFAULT (kütüphane tarafından desteklenen en büyük sürüm), CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2 veya CURL_SSLVERSION_MAX_TLSv1_3.

Bilginize:

En iyi seçiminiz, bunu ayarlamamak ve öntanımlıyı kullanmasına izin vermektir. Bunu 2 veya 3 olarak ayarlamak, SSLv2 ve SSLv3'teki bilinen güvenlik açıkları göz önüne alındığında çok tehlikelidir.

 
CURLOPT_PROXY_SSL_OPTIONS SSL davranış seçeneklerini, aşağıdaki sabitlerden herhangi birinin bit maskesidir: CURLSSLOPT_ALLOW_BEAST: SSL3 ve TLS1.0 protokollerinde bir güvenlik açığı için herhangi bir geçici çözüm kullanmaya çalışmaz. CURLSSLOPT_NO_REVOKE: Bu tür bir davranışın mevcut olduğu SSL arka uçları için sertifika iptal denetimlerini devre dışı bırakır. (curl >= 7.44.0) CURLSSLOPT_NO_PARTIALCHAIN: Belirtilmediğinde öntanımlı olan "kısmi" sertifika zincirlerini kabul etmez. (curl >= 7.68.0) libcurl >= cURL 7.52.0 ve PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_PROXY_SSL_VERIFYHOST HTTPS vekilinin sertifika adı alanlarını vekil adına göre doğrulamak için 2'ye ayarlayın. 0 olarak ayarlandığında, sertifikada kullanılan adlardan bağımsız olarak bağlantı başarılı olur. Bu özelliği dikkatli kullanın! 1 curl 7.28.0 ve öncesinde bir hata ayıklama seçeneği olarak ele alındı. Curl 7.28.1'den 7.65.3'e CURLE_BAD_FUNCTION_ARGUMENT döndürülür. 7.66.0'dan itibaren 1 ve 2 aynı kabul edilir. Üretim ortamlarında bu seçeneğin değeri 2'de (öntanımlı değer) tutulmalıdır. libcurl >= cURL 7.52.0 ve PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_PROXY_SSLVERSION 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 veya CURL_SSLVERSION_SSLv3 sabitlerinden biri.

Bilginize:

En iyi seçim, bunu ayarlamamak ve uzak SSL protokol sürümünü bulmaya çalışacak olan öntanımlı CURL_SSLVERSION_DEFAULT'un kullanımına izin vermektir.

libcurl >= cURL 7.52.0 ve PHP 7.3.0 ve sonrasında kullanılabilir.
CURLOPT_STREAM_WEIGHT Sayısal akım ağırlığını ayaralar (1 ile 256 arasında bir sayı). cURL 7.46.0'da eklendi. PHP 7.0.7 ve sonrasında kullanılabilir.
CURLOPT_TCP_KEEPALIVE 1 değerine ayarlanırsa, TCP canlı tutma yoklamaları gönderilir. Bu yoklamaların gecikmesi ve sıklığı, işletim sisteminin desteklemesi koşuluyla, CURLOPT_TCP_KEEPIDLE ve CURLOPT_TCP_KEEPINTVL seçenekleri ile denetlenebilir. 0 (öntanımlı) olarak ayarlanırsa, canlı tutma yoklamaları devre dışı bırakılır. cURL 7.25.0'da eklendi.
CURLOPT_TCP_KEEPIDLE CURLOPT_TCP_KEEPALIVE etkinleştirilmişse, canlı tutma yoklamaları gönderilmeden önce bağlantı boşta iken işletim sisteminin bekleyeceği süreyi saniye cinsinden ayarlar. Tüm işletim sistemleri bu seçeneği desteklemez. Öntanımlı değer 60'tır. cURL 7.25.0'da eklendi.
CURLOPT_TCP_KEEPINTVL CURLOPT_TCP_KEEPALIVE etkinleştirilmişse, işletim sisteminin canlı tutma yoklamaları arasında bekleyeceği süreyi saniye cinsinden ayarlar. Tüm işletim sistemleri bu seçeneği desteklemez. Öntanımlı değer 60'tır. cURL 7.25.0'da eklendi.
CURLOPT_TIMECONDITION CURLOPT_TIMEVALUE değerinin nasıl ele alınacağı belirtilir. Sayfayı sadece, CURLOPT_TIMEVALUE ile belirtilen süre içinde değiştirilmediği takdirde döndürmek için CURL_TIMECOND_IFMODSINCE kullanılır. Sayfa değişmişse, CURLOPT_HEADER seçeneğinin true olduğu varsayımıyla "304 Not Modified" (304 değişiklik yok) başlığı döndürülür. Bu davranışı ters çevirmek için CURL_TIMECOND_IFUNMODSINCE kullanılır. CURLOPT_TIMEVALUE değerini yoksayıp sayfayı daima döndürmek için CURL_TIMECOND_NONE kulllanılır. CURL_TIMECOND_NONE öntanımlıdır. cURL 7.46.0 öncesinde CURL_TIMECOND_IFMODSINCE öntanımlıydı.
CURLOPT_TIMEOUT cURL işlevlerinin çalışmasına izin verilecek azami saniye sayısı.  
CURLOPT_TIMEOUT_MS cURL işlevlerinin çalışmasına izin verilecek azami milisaniye sayısı. Libcurl, standart sistem adı çözümleyicisini kullanmak üzere derlenmişse, bağlantının bu kısmı, bir saniyelik asgari zaman aşımına izin verilerek, zaman aşımları için tam saniyelik çözünürlüğü kullanmaya devam edecektir. cURL 7.16.2'de eklendi.
CURLOPT_TIMEVALUE 1 Ocak 1970'den beri geçen saniye sayısı. Bu değer CURLOPT_TIMECONDITION tarafından kullanılır.  
CURLOPT_TIMEVALUE_LARGE 1 Ocak 1970'den bu yana saniye cinsinden süre. CURLOPT_TIMECONDITION tarafından kullanılacak zaman. Öntanımlı sıfırdır. Bu seçenek ile CURLOPT_TIMEVALUE arasındaki fark, bağımsız değişkenin türüdür. "long" un yalnızca 32 bit genişliğinde olduğu sistemlerde, bu seçeneğin 2038 yılından sonraki tarihleri ayarlamak için kullanılması gerekir. cURL 7.59.0'de eklendi. PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_UPKEEP_INTERVAL_MS Bazı protokollerin "bağlantı bakım" düzenekleri vardır. Bu düzenekler, bağlantıyı canlı tutmak için genellikle mevcut bağlantılara bir miktar trafik gönderir. Bu seçenek, bağlantı bakım aralığını tanımlar. Şu anda, bağlantı bakım düzeneğine sahip tek protokol HTTP/2'dir. Bağlantı bakım aralığı aşıldığında, bağlantıya HTTP/2 PING tertibi gönderilir. 60 saniye varsayılan değerdir.
CURLOPT_UPLOAD_BUFFERSIZE CURL yükleme tamponu için bayt cinsinden tercih edilen boyut. Yükleme tamponunun boyutu varsayılan olarak 64 kilobayttır. Tahsis edilebilecek tampon boyutunun azamisi 2 megabayt, asgarisi 16 kilobayttır.
CURLOPT_MAX_RECV_SPEED_LARGE Bir indirme, aktarım sırasında birikimli ortalama olarak bu hızı (saniyede bayt olarak sayılır) aşarsa, ortalama hızı belirtilen değerden düşük veya ona eşit tutmak için aktarım durur. Sınırsız hız öntanımlıdır. cURL 7.15.5'de eklendi.
CURLOPT_MAX_SEND_SPEED_LARGE Bir yükleme, aktarım sırasında birikimli ortalama olarak bu hızı (saniyede bayt olarak sayılır) aşarsa, ortalama hızı belirtilen değerden düşük veya ona eşit tutmak için aktarım durur. Sınırsız hız öntanımlıdır. cURL 7.15.5'de eklendi.
CURLOPT_SSH_AUTH_TYPES CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD sabitleri VEYAlanarak oluşturulan bit maskesi. libcurl'un kendi seçmesi için CURLSSH_AUTH_ANY sabitini atayın. cURL 7.16.1'de eklendi.
CURLOPT_IPRESOLVE Uygulamaya, konak adlarını çözümlerken ne tür IP adreslerinin kullanılacağını seçme izni verir. Bu, yalnızca birden fazla IP sürümünü kullanarak adresleri çözen konak adları kullanıldığında ilginçtir. Olası değerler: CURL_IPRESOLVE_WHATEVER, CURL_IPRESOLVE_V4, CURL_IPRESOLVE_V6 CURL_IPRESOLVE_WHATEVER öntanımlıdır. cURL 7.10.8'de eklendi.
CURLOPT_FTP_FILEMETHOD Curl'e FTP(S) sunucusundaki bir dosyaya ulaşmak için hangi yöntemin kullanacağını söyler. Olası değerler: CURLFTPMETHOD_DEFAULT, CURLFTPMETHOD_MULTICWD, CURLFTPMETHOD_NOCWD, and CURLFTPMETHOD_SINGLECWD. cURL 7.15.1'de eklendi.

değer bağımsız değişkenine aşağıdaki seçenek'ler için bir dizge atanmalıdır:

Seçenek Atanacak değer Ek bilgi
CURLOPT_ABSTRACT_UNIX_SOCKET Bir sunucunun TCP bağlantısı kurmak yerine soyut bir Unix bağlamı soketinin kullanılmasını sağlar ve yolu belirtilen dizeye atar. Bu seçenek, CURLOPT_UNIX_SOCKET_PATH ile aynı sözdizimini paylaşır. Bu iki seçenek aynı depolamayı paylaşır ve bu nedenle her tanıtıcıya bunlardan yalnızca biri atanabilir. cURL 7.53.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_ALTSVC CURLOPT_ALTSVC_CTRL üzerinden CURLALTSVC_READONLYFILE etkin kılınmadıkça, mevcut önbellek içeriğini okumak ve muhtemelen bir aktarımdan sonra geri yazmak için Alt-Svc önbellek dosyası olarak kullanmak üzere cURL'ye dosya adını aktarır.
CURLOPT_ALTSVC_CTRL cURL'ye bu tanıtıcıyı kullanarak aktarımlar için Alt-Svc'yi nasıl işleyeceğini bildirmek üzere bit maskesini doğru özellik grubuyla doldurur. cURL, HTTPS üzerinden yalnızca Alt-Svc başlıklarını kabul eder. Ayrıca, kaynak yalnızca HTTPS üzerinden uygun şekilde sunuluyorsa, başka bir kaynağa yönelik isteği tamamlayacaktır. Herhangi bir bitin etkinleştirilmesi Alt-Svc motorunu etkinleştirir. Seçenekler: CURLALTSVC_H1, CURLALTSVC_H2, CURLALTSVC_H3 ve CURLALTSVC_READONLYFILE.
CURLOPT_AWS_SIGV4

HTTP(S) başlığında AWS V4 imza kimlik doğrulaması sağlar.

Bu seçenek, CURLOPT_HTTPAUTH ile atanan diğer tüm kimlik doğrulama türlerini geçersiz kılar. Bu yöntem, diğer kimlik doğrulama türleriyle birleştirilemez.

CURLOPT_CAINFO Eşle doğrulanacak bir veya daha fazla sertifikanın tutulduğu dosyanın ismi. Bu sadece CURLOPT_SSL_VERIFYPEER ile birlikte kullanıldığında anlamlıdır. Mutlak bir yol gerektirebilir.
CURLOPT_CAINFO_BLOB Eşi doğrulamak için bir veya daha fazla sertifika tutan bir PEM dosyasının adı. CURLOPT_CAINFO seçeneğini geçersiz kılar. PHP 8.2.0 ve cURL 7.77.0 itibariyle kullanılabilmektedir.
CURLOPT_CAPATH Çok sayıda CA sertifikasının tutulduğu dizinin yolu. CURLOPT_SSL_VERIFYPEER seçeneğiyle birlikte kullanılır.
CURLOPT_COOKIE HTTP isteğinde kullanılacak "Cookie: " başlığının içeriği. Bir noktalı virgülden sonra gelen bir boşlukla ayrılarak çok sayıda çerez belirtilebilir ("meyve=elma; renk=turkuaz" gibi).
CURLOPT_COOKIEFILE Çerez verisini içeren dosyanın adı. Çerez dosyası Netscape biçeminde veya bir dosyaya dökümlenmiş salt HTTP tarzı başlıklar olabilir. Ad boş bir dizeyse, hiçbir çerez yüklenmez, ancak çerez işleme yine de etkindir.
CURLOPT_COOKIEJAR Tanıtıcı kapatıldığında (ör. curl_close çağrısından sonra) tüm dahili çerezlerin kaydedileceği dosyanın adı.
CURLOPT_COOKIELIST Bir çerez dizesi (yani Netscape/Mozilla biçiminde tek bir satır veya normal bir HTTP tarzı Set-Cookie başlığı); bu tek çerez dahili çerez deposuna eklenir. "ALL", bellekte tutulan tüm çerezleri siler. "SESS" bellekte tutulan tüm oturum çerezlerini siler. "FLUSH" bilinen çerezleri CURLOPT_COOKIEJAR ile belirtilen dosyaya yazar. "RELOAD" tüm çerezleri CURLOPT_COOKIEFILE ile belirtilen dosyalardan yükler. cURL 7.14.1'den beri kullanılabilmektedir.
CURLOPT_CUSTOMREQUEST

Bir HTTP isteği yaparken "GET" veya "HEAD" yerine kullanılacak özel istek yöntemi. "DELETE" veya biraz daha çapraşık HTTP istekleri yapmak için kullanışlıdır. Geçerli değerlerin bazıları: "GET", "POST", "CONNECT"; yani, istek satırının tamamını buraya girmeyin. Örneğin, "GET /index.html HTTP/1.0\r\n\r\n" girdisi yanlış olacaktır.

Bilginize:

Belirteceğiniz istek yöntemini sunucunun desteklediğinden emin olmadan bir şey belirtmeyin.

CURLOPT_DEFAULT_PROTOCOL

URL'de şema adı eksikse kullanılacak öntanımlı protokol.

cURL 7.45.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_HSTS

HSTS (HTTP Strict Transport Security - Sıkı Taşıma Güvenliği) önbellek dosya adı.

CURLOPT_HSTS_CTRL

HSTS (HTTP Strict Transport Security- Sıkı Taşıma Güvenliği) davranışını denetler. cURL'ye bu tanıtıcıyı kullanarak aktarımlar için HSTS'yi nasıl işleyeceğini öğretmek için bit maskesini doğru özellik kümesiyle doldurur. HSTS önbellek dosyası tanımlıysa dosyayı salt okunur yapmak için CURLHSTS_READONLYFILE atanır.

CURLOPT_DNS_INTERFACE

DNS çözümleyicinin bağlanması gereken ağ arabiriminin adını atayın. Bu bir arabirim adı olmalı, bir adres değil.

cURL 7.33.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_DNS_LOCAL_IP4

Çözümleyicinin bağlanması gereken yerel IPv4 adresini atayın. Bağımsız değişken, dizge olarak tek bir sayısal IPv4 adresi içermelidir.

cURL 7.33.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_DNS_LOCAL_IP6

Çözümleyicinin bağlanması gereken yerel IPv6 adresini atayın. Bağımsız değişken, dizge olarak tek bir sayısal IPv6 adresi içermelidir.

cURL 7.33.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_EGDSOCKET Bozunum değerlerini toplama uygulamasına bir dosya ismi belirtmesi dışında CURLOPT_RANDOM_FILE gibidir.
CURLOPT_ENCODING "Accept-Encoding: " başlığının içeriği. Yanıtın kodlanmasını sağlar. Desteklenen kodlamalar: "identity", "deflate" ve "gzip". Boş bir dizge "" belirtilirse desteklenen tüm kodlamaları içeren bir başlık gönderilir. cURL 7.10'da eklendi.
CURLOPT_FTPPORT FTP "PORT" komutu için kullanılacak IP adresini almakta kullanılacak değer. "PORT" komutu, uzak sunucunun bizim belirttiğimiz IP adresine bağlanmasını söyler. Dizge bir IP adresi içerebileceği gibi bir konakismi, (Unix altında) bir ağ arayüzü adı veya sistemin öntanımlı IP adresinin kullanılacağı anlamında '-' olabilir.
CURLOPT_INTERFACE Kullanılacak giden ağ arayüzünün ismi. Bir ağ arabirimi ismi, bir IP adresi veya bir konak ismi olabilir.
CURLOPT_KEYPASSWD CURLOPT_SSLKEY veya CURLOPT_SSH_PRIVATE_KEYFILE özel anahtarını kullanmak için parola gerekir. cURL 7.16.1'de eklendi.
CURLOPT_KRB4LEVEL KRB4 (Kerberos 4) güvenlik seviyesi. Geçerli değerler (en güçsüzden en güçlüye doğru): "clear", "safe", "confidential", "private".. Dizge bunlardan biri değilse "private" kullanılır. Bu seçeneğe null atanması KRB4 güvenliğini iptal eder. Şimdilik KRB4 güvenliği sadece FTP aktarımlarında çalışmaktadır.
CURLOPT_LOGIN_OPTIONS "AUTH=NTLM" veya "AUTH=*" aracılığıyla tercih edilen kimlik doğrulama mekanizması gibi protokole özgü oturum açma seçeneklerini ayarlamak için kullanılabilir ve CURLOPT_USERNAME seçeneğiyle birlikte kullanılmalıdır. cURL 7.34.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_PINNEDPUBLICKEY Sabitlenmiş genel anahtarı atayın. Dize, sabitlenmiş genel anahtarınızın dosya adı olabilir. Beklenen dosya biçimi "PEM" veya "DER" dir. Dize, başında "sha256//" bulunan ve ";" ile ayrılmış çok sayıda base64 kodlu sha256 karması olabilir. cURL 7.39.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_POSTFIELDS Bir HTTP "POST" işleminde gönderilecek verinin tamamı. 'para1=val1&para2=val2&...' benzeri kodlanmış bir dizge veya alan isimlerinin anahtar, değerlerinin değer olarak yer aldığı bir dizi belirtilebilir. değer bir dizi ise Content-Type başlığına multipart/form-data atanır. value bir dizi olduğu takdirde, dosyalar CURLFile veya CURLStringFile kullanılarak gönderilebilir.
CURLOPT_PRIVATE Bu cURL tanıtıcısı ile ilişkilendirilmesi gereken herhangi bir veri. Bu veriler daha sonra curl_getinfo() işlevinin CURLINFO_PRIVATE seçeneği ile alınabilir. cURL bu verilerle hiçbir şey yapmaz. Bir cURL çoklu tanıtıcısı kullanılırken, bu özel veriler tipik olarak standart bir cURL tanıtıcısını tanımlamak için benzersiz bir anahtardır. cURL 7.10.3'da eklendi.
CURLOPT_PRE_PROXY Bir sonraki istek için CURLOPT_PROXY seçeneğinde belirtilen HTTP(S) vekiline bağlanmadan önce curl'nin bağlanacağı ön vekil olarak kullanılacak konak adını veya noktalı sayısal IP adresini tutan bir dize atayın. Ön vekil yalnızca bir SOCKS vekili olabilir ve kullanılan soket türünü belirtmek için [şema]:// önekini almalıdır. Sayısal bir IPv6 adresi köşeli [parantez] içinde yazılmalıdır. Önvekilin boş bir dizeye ayarlanması, önvekil kullanımını açıkça devre dışı bırakır. Bu dizede port numarasını belirtmek için, konak adının ardına :[port] ekleyin. Vekil port numarası isteğe bağlı olarak ayrı bir seçenek olan CURLOPT_PROXYPORT ile belirtilebilir. Bir port belirtilmezse, vekiller için port 1080 öntanımlıdır. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY İstekleri tünelleyecek HTTP vekili.
CURLOPT_PROXY_SERVICE_NAME Vekil kimlik kanıtlama hizmetinin ismi. cURL 7.34.0'da HTTP vekiller için, cURL 7.49.0'da SOCK5 vekilleri için eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_PROXY_CAINFO Sertifika Yetkilisi (CA) paketini vekile götüren yol. Yolu, HTTPS vekilini doğrulamak için bir veya daha fazla sertifika içeren bir dosyayı adlandıran bir dize olarak ayarlayın. Bu seçenek bir HTTPS sunucusuna değil, bir HTTPS vekiline bağlanmak içindir. libcurl'un cacert paketinin saklandığı varsayılan sistem yolu öntanımlıdır. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_CAINFO_BLOB HTTPS vekilini doğrulamak için bir veya daha fazla sertifika tutan PEM dosyasının adı. Bu seçenek, bir HTTPS sunucusuna değil, bir HTTPS vekiline bağlanmak içindir. Varsayılanlar, libcurl'ün cacert paketinin bulunduğu varsayılan sistem yoluna ayarlanmıştır. PHP 8.2.0 ve libcurl >= cURL 7.77.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_CAPATH HTTPS vekilini doğrulamak için birden çok CA sertifikası bulunan dizin. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_CRLFILE Dosya adını, SSL değiş tokuşu sırasında gerçekleşen sertifika doğrulamasında kullanmak için PEM biçiminde CRL (Sertifika İptal Listesi) birleştirmesiyle ayarlayın. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_KEYPASSWD CURLOPT_PROXY_SSLKEY özel anahtarını kullanmak için gereken şifre olarak kullanılacak dizeyi ayarlayın. Bir sertifikayı yüklemek için hiçbir zaman bir parola gerekmez, ancak özel anahtarınızı yüklemek için bir parolaya ihtiyacınız vardır. Bu seçenek bir HTTPS sunucusuna değil, bir HTTPS vekiline bağlanmak içindir. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_PINNEDPUBLICKEY HTTPS vekili için sabitlenmiş genel anahtarı ayarlayın. Dize, sabitlenmiş genel anahtarınızın dosya adı olabilir. Beklenen dosya biçimi "PEM" veya "DER" dir. Dize, başında "sha256 //" bulunan ve ";" ile ayrılmış herhangi bir sayıda base64 kodlu sha256 karması olabilir libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_SSLCERT HTTPS vekiline bağlanmak için kullanılan istemci sertifikanızın dosya adı. Öntanımlı biçem, Güvenli Aktarımda "P12" ve diğer motorlarda "PEM" dir ve CURLOPT_PROXY_SSLCERTTYPE ile bu değiştirilebilir. NSS veya Güvenli Aktarım ile bu, güvenlik veritabanında adı verildiği şekilde kimlik doğrulaması yapmak istediğiniz sertifikanın takma adı da olabilir. Mevcut dizinden bir dosya kullanmak istiyorsanız, bir takma adla karışıklığı önlemek için lütfen "./" ön ekini kullanın. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_SSLCERTTYPE Bir HTTPS vekiline bağlanırken kullanılan istemci sertifikanızın biçimi. Güvenli Aktarım dışında desteklenen biçimler "PEM" ve "DER" dir. OpenSSL (0.9.3 ve üstü sürümler) ve Secure Transport (iOS 5 veya üstü veya OS X 10.7 veya üstü), PKCS#12 ile kodlanmış dosyalar için "P12" yi de destekler. "PEM" öntanımlıdır. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_SSL_CIPHER_LIST HTTPS vekiline bağlantı için kullanılacak şifrelerin listesi. Liste sözdizimsel olarak doğru olmalıdır, iki nokta üst üste ile ayrılmış bir veya daha fazla şifre dizesinden oluşur. Virgüller veya boşluklar da kabul edilebilir ayırıcılardır ancak normalde iki nokta üst üste kullanılır, !, - ve + işleç olarak kullanılabilir. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_TLS13_CIPHERS Bir vekile TLS 1.3 bağlantısı için kullanılacak şifre paketlerinin listesi. Liste sözdizimsel olarak doğru olmalıdır, iki nokta üst üste ile ayrılmış bir veya daha fazla şifre paketi dizesinden oluşur. Bu seçenek şu anda yalnızca curl OpenSSL 1.1.1 veya sonrasını kullanmak üzere oluşturulduğunda kullanılmaktadır. Farklı bir SSL arka ucu kullanıyorsanız, CURLOPT_PROXY_SSL_CIPHER_LIST seçeneğini kullanarak TLS 1.3 şifre paketlerini ayarlamayı deneyebilirsiniz. libcurl >= cURL 7.61.0 ve PHP 7.3.0'dan beri OpenSSL >= 1.1.1 ile derlendiğinde kullanılabilmektedir.
CURLOPT_PROXY_SSLKEY HTTPS vekiline bağlanmak için kullanılan özel anahtarınızın dosya adı. Öntanımlı biçim "PEM" dir ve CURLOPT_PROXY_SSLKEYTYPE ile değiştirilebilir. (Yalnızca iOS ve Mac OS X) Curl, Secure Transport'a göre oluşturulmuşsa bu seçenek yok sayılır. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri TLS etkin derlendiğinde kullanılabilmektedir.
CURLOPT_PROXY_SSLKEYTYPE Özel anahtarınızın biçemi. Desteklenen biçemler: "PEM", "DER" ve "ENG". libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_TLSAUTH_PASSWORD CURLOPT_PROXY_TLSAUTH_TYPE seçeneğiyle belirtilen TLS kimlik doğrulama yöntemi için kullanılacak parola. CURLOPT_PROXY_TLSAUTH_USERNAME seçeneğinin de ayarlanmasını gerektirir. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_TLSAUTH_TYPE HTTPS bağlantısı için kullanılan TLS kimlik doğrulama yöntemi. Desteklenen yöntem "SRP" dir.

Bilginize:

TLS için Güvenli Uzak Parola (SRP) kimlik doğrulaması, her iki tarafın da paylaşılan bir sırrı varsa karşılıklı kimlik doğrulama sağlar. TLS-SRP'yi kullanmak için ayrıca CURLOPT_PROXY_TLSAUTH_USERNAME ve CURLOPT_PROXY_TLSAUTH_PASSWORD seçeneklerini de ayarlamanız gerekir.

libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXY_TLSAUTH_USERNAME CURLOPT_PROXY_TLSAUTH_TYPE seçeneğiyle belirtilen HTTPS vekili TLS kimlik doğrulama yöntemi için kullanılacak kullanıcı adı. CURLOPT_PROXY_TLSAUTH_PASSWORD seçeneğinin de ayarlanmasını gerektirir. libcurl >= cURL 7.52.0 ve PHP 7.3.0'dan beri kullanılabilmektedir.
CURLOPT_PROXYUSERPWD Vekil bağlantısı için kullanılacak kullanıcı adı ve parola; "[kullanıcı]:[parola]" biçeminde belirtilir.
CURLOPT_RANDOM_FILE SSL için rasgele sayı üretecini tohumlamakta kullanılacak dosya ismi.
CURLOPT_RANGE X ve Y isteğe bağlı olmak üzere "X-Y" biçeminde alınacak veri aralığı. HTTP aktarımları, "X-Y,N-M" biçeminde virgüllerle ayrılmış olarak çok sayıda aralığı destekler.
CURLOPT_REFERER Bir HTTP isteğinde kullanılacak "Referer: " başlığının içeriği.
CURLOPT_SASL_AUTHZID Aktarım için yetkilendirme kimliği (authzid). Yalnızca isteğe bağlı olduğu durumlarda salt metin SASL kimlik doğrulama düzeneği için geçerlidir. Belirtilmediğinde, yalnızca kullanıcı adıyla belirtilen kimlik doğrulama kimliği (authcid), parolayla birlikte sunucuya gönderilir. Sunucu, sağlanmadığında authzid'i authcid'den türetecek ve bunu daha sonra dahili olarak kullanacaktır.
CURLOPT_SERVICE_NAME Kimlik kanıtlama hizmetini adı. cURL 7.43.0'da eklendi. PHP 7.0.7'dan beri kullanılabilmektedir.
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 32 onaltılık basamak içeren bir dize. Dize, uzak ana bilgisayarın genel anahtarının MD5 sağlama toplamı olmalıdır; libcurl, md5sums eşleşmediği sürece konağa bağlantıyı reddedecektir. Bu seçenek yalnızca SCP ve SFTP aktarımları içindir.. cURL 7.17.1'da eklendi.
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 Uzak konağın genel anahtarının Base64 kodlu SHA256 aşı. Verilen aş, uzak konağın sağladığı aş ile eşleşmezse aktarım başarısız olur.
CURLOPT_SSH_PUBLIC_KEYFILE Genel anahtarınızın dosya adı. Kullanılmazsa, libcurl öntanımlı olarak HOME ortam değişkeni ayarlanmışsa $HOME/.ssh/id_dsa.pub dosyasını ve HOME ayarlanmamışsa geçerli dizinde bir "id_dsa.pub" dosyası arar. cURL 7.16.1'da eklendi.
CURLOPT_SSH_PRIVATE_KEYFILE Özel anahtarınızın dosya adı. Kullanılmazsa, libcurl öntanımlı olarak HOME ortam değişkeni ayarlanmışsa $HOME/.ssh/id_dsa dosyasını ve HOME ayarlanmamışsa geçerli dizinde bir "id_dsa" dosyası arar. Dosya parola korumalıysa, parolayı CURLOPT_KEYPASSWD ile ayarlayın. cURL 7.16.1'da eklendi.
CURLOPT_SSL_CIPHER_LIST SSL için kullanılacak şifrelerin listesi. Örneğin, RC4-SHA ve TLSv1 geçerli şifre listeleridir.
CURLOPT_SSL_EC_CURVES Eliptik eğri algoritmalarının iki nokta üst üstelerle ayrılmış listesi. Örneğin, X25519:P-521, iki eliptik eğrinin geçerli listesidir. Bu seçenek, cURL SSL arka ucu olarak bunu desteklemek için derlenmişse, istemcinin SSL el sıkışmasındaki anahtar değişim algoritmalarını tanımlar.
CURLOPT_SSLCERT PEM biçemli sertifikayı içeren dosyanın ismi.
CURLOPT_SSLCERTPASSWD CURLOPT_SSLCERT sertifikasını kullanmak için gereken parola.
CURLOPT_SSLCERTTYPE Sertifika biçemi. Desteklenen biçemler: "PEM" (öntanımlı), "DER" ve "ENG". OpenSSL 0.9.3 itibariyle ayrıca, "P12" (PKCS#12 kodlu dosyalar) desteklenmiştir. cURL 7.9.3'te eklendi.
CURLOPT_SSLENGINE CURLOPT_SSLKEY ile belirtilmiş gizli SSL anahtarının şifreleme motoru için betimleyici.
CURLOPT_SSLENGINE_DEFAULT Bakışımsız şifreleme işlemleri için kullanılan şifreleme motoru için betimleyici.
CURLOPT_SSLKEY Gizli SSL anahtarını içeren dosyanın ismi.
CURLOPT_SSLKEYPASSWD

CURLOPT_SSLKEY ile belirtilen gizli SSL anahtarını kullanmak için gereken gizli parola.

Bilginize:

Bu seçenekle belirtilen parolayı yetkisiz kişilerin okumaması için PHP betiğini güvenilir bir yerde tutmaya çalışın.

CURLOPT_SSLKEYTYPE CURLOPT_SSLKEYile belirtilen gizli SSL anahtarının anahtar türü. Desteklenen anahtar türleri: "PEM" (öntanımlı), "DER", ve "ENG".
CURLOPT_TLS13_CIPHERS TLS 1.3 bağlantısı için kullanılacak şifre paketlerinin listesi. Liste sözdizimsel olarak doğru olmalıdır, iki nokta üst üste ile ayrılmış bir veya daha fazla şifre paketi dizesinden oluşur. Bu seçenek şu anda yalnızca curl, OpenSSL 1.1.1 veya sonrasını kullanmak üzere derlendiğinde kullanılmaktadır. Farklı bir SSL arka ucu kullanıyorsanız, CURLOPT_SSL_CIPHER_LIST seçeneğini kullanarak TLS 1.3 şifre paketlerini ayarlamayı deneyebilirsiniz. libcurl >= cURL 7.61.0 ve PHP 7.3.0'den beri kullanılabilmektedir. OpenSSL >= 1.1.1 ile derlendiğinde kullanılabilir.
CURLOPT_UNIX_SOCKET_PATH Unix etki alanı soketlerinin bağlantı uç noktası olarak kullanılmasını sağlar ve verilen dizeye yolu ayarlar. cURL 7.40.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_URL İçeriği alınacak URL. Oturumu curl_init() ile ilklendirirken de belirtilebilir.
CURLOPT_USERAGENT HTTP isteğinde kullanılacak "User-Agent: "başlığının içeriği.
CURLOPT_USERNAME Kimlik kanıtlamada kullanılacak kullanıcı adı. cURL 7.19.1'de eklendi.
CURLOPT_PASSWORD Kimlik kanıtlamada kullanılacak parola. cURL 7.19.1'de eklendi.
CURLOPT_USERPWD Bağlantı için kullanılmak üzere "[kullanıcı]:[parola]" biçeminde kullanıcı adı ve parola.
CURLOPT_XOAUTH2_BEARER OAuth 2.0 erişim jetonunu belirtir. cURL 7.33.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.

değer bağımsız değişkenine aşağıdaki seçenek'ler için bir dizi atanmalıdır:

Seçenek Atanacak değer Ek bilgi
CURLOPT_CONNECT_TO URL'nin konak ve portu yerine belirli bir konak ve porta bağlanır. KONAK:PORT:BAĞLANILACAK-KONAK:BAĞLANILACAK-PORT biçimindeki dizeleri kabul eder. cURL 7.49.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_HTTP200ALIASES Hata değil geçerli yanıtlar olarak ele alınmak üzere HTTP 200 yanıtlarını içeren bir dizi. cURL 7.10.3'te eklendi.
CURLOPT_HTTPHEADER array('Content-type: text/plain', 'Content-length: 100') biçiminde, atanacak HTTP başlık alanları dizisi.
CURLOPT_POSTQUOTE FTP isteği yapıldıktan sonra sunucu üzerinde çalıştırılacak komutları içeren bir dizi.
CURLOPT_PROXYHEADER Vekillere iletilecek özel HTTP başlıkları dizisi. cURL 7.37.0'da eklendi. PHP 7.0.7'den beri kullanılabilmektedir.
CURLOPT_QUOTE FTP isteği yapılmadan önce sunucu üzerinde çalıştırılacak komutları içeren bir dizi.
CURLOPT_RESOLVE Belirli bir konak ve port çifti için özel bir adres sağlar. array("example.com:80:127.0.0.1") biçiminde, iki nokta üst üsteler ile ayrılmış konak adı, port ve IP adresi dizeleri dizisi. cURL 7.21.3'te eklendi.

değer bağımsız değişkenine aşağıdaki seçenek'ler için (örneğin fopen() kullanarak) bir akım özkaynağı atanmalıdır:

Seçenek Atanacak değer Ek bilgi
CURLOPT_FILE Aktarımın yazılacağı dosya. STDOUT (tarayıcı penceresi) öntanımlıdır.
CURLOPT_INFILE Karşıya yükleme sırasında aktarımın okuyacağı dosya.
CURLOPT_STDERR Çıktı hatalarının gönderileceği STDERR yerine kullanılacak dosya.
CURLOPT_WRITEHEADER Aktarımın başlık bölümünün yazılacağı dosya.
CURLOPT_XFERINFOFUNCTION İki bağımsız değişkenli bir geri çağırım işlev. CURLOPT_PROGRESSFUNCTION ile benzer bir amacı vardır ama cURL'deki en güncel ve tercih edilen işlevdir. 7.32.0 sürümünde eklendi. PHP 8.2.0 ve sonrasında kullanılabilmektedir.

değer, aşağıdaki Seçenek değerleri için bir Closure nesnesi veya geçerli bir işlev ismi olmalıdır:

Seçenek Atanacak değer Ek Bilgi
CURLOPT_HEADERFUNCTION İki bağımsız değişkenli bir geriçağırım işlevinin ismi. Bağımsız değişkenlerin ilki bir cURL özkaynağı, ikincisi ise başlık verisinin yazılacağı bir dizge olmalıdır. Başlık verisi bu geriçağırım işlevi kullanılırken yazılmalıdır. İşlevin dönüş değeri yazılan bayt sayısı olmalıdır.  
CURLOPT_PASSWDFUNCTION Üç bağımsız değişkenli bir geriçağırım işlevinin ismi. Bağımsız değişkenlerin ilki bir cURL özkaynağı, ikincisi parola istemi belirten bir dizge, üçüncüsü ise parolanın azami uzunluğu olmalıdır. İşlevin dönüş değeri parolayı içeren bir dizge olmalıdır. PHP 7.3.0'da kaldırıldı.
CURLOPT_PROGRESSFUNCTION

Beş bağımsız değişkenli bir geriçağırım işlevinin ismi. Bağımsız değişkenlerin ilki bir cURL özkaynağı, ikincisi bu aktarımda indirilmesi beklenen toplam bayt sayısı, üçüncüsü şu ana kadar indirilen bayt sayısı, dördüncüsü bu aktarımda yüklenmesi beklenen toplam bayt sayısı ve beşincisi, şimdiye kadar yüklenen bayt sayısıdır.

Bilginize:

Geriçağırım işlevi sadece CURLOPT_NOPROGRESS seçeneğinin değeri false ise çağrılır.

Aktarımdan çıkmak için sıfırdan farklı bir değer döndürün. Bu durumda aktarım bir CURLE_ABORTED_BY_CALLBACK hatası verir. error.

 
CURLOPT_READFUNCTION Üç bağımsız değişkenli bir geriçağırım işlevinin ismi. Bağımsız değişkenlerin ilki bir cURL özkaynağı, ikincisi CURLOPT_INFILE seçeneği aracılığıyla cURL'ye sağlanan bir akım özkaynağı ve üçüncüsü okunacak azami veri miktarıdır. İşlev, genellikle aktarılan akım özkaynağından okuyarak, istenen veri miktarına eşit veya daha kısa uzunlukta bir dize döndürmelidir. EOF sinyali vermek için boş bir dizi döndürülmelidir.  
CURLOPT_WRITEFUNCTION İki bağımsız değişkenli bir geriçağırım işlevinin ismi. Bağımsız değişkenlerin ilki bir cURL özkaynağı, ikincisi ise yazılacak veriyi içeren bir dizge olmalıdır. Veri bu geriçağırım işlevi kullanılarak kaydedilmelidir. İşlevin dönüş değeri yazılan bayt sayısı olmalıdır, aksi takdirde bir hata vererek aktarımdan çıkılmalıdır.  

Other values:

Seçenek Atanacak değer
CURLOPT_SHARE curl_share_init() işlevinden dönen değer. cURL tanıtıcısının paylaşılan tanıtıcıdaki verileri kullanmasını sağlar.

Dönen Değerler

Başarı durumunda true, başarısızlık durumunda false döner.

Sürüm Bilgisi

Sürüm: Açıklama
8.0.0tanıtıcı için artık bir CurlHandle örneği bekleniyor; evvelce, resource türünde bir değer beklenirdi.
7.3.15, 7.4.3 CURLOPT_HTTP09_ALLOWED eklendi.
7.3.0 CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPT_PRE_PROXY, CURLOPT_PROXY_CAINFO, CURLOPT_PROXY_CAPATH, CURLOPT_PROXY_CRLFILE, CURLOPT_PROXY_KEYPASSWD, CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPT_PROXY_SSLCERT, CURLOPT_PROXY_SSLCERTTYPE, CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPT_PROXY_SSLKEY, CURLOPT_PROXY_SSLKEYTYPE, CURLOPT_PROXY_SSL_OPTIONS, CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPT_PROXY_SSLVERSION, CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPT_SOCKS5_AUTH, CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPT_HAPROXYPROTOCOL, CURLOPT_PROXY_TLS13_CIPHERS, CURLOPT_SSH_COMPRESSION, CURLOPT_TIMEVALUE_LARGE ve CURLOPT_TLS13_CIPHERS eklendi.
7.0.7 CURL_HTTP_VERSION_2, CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, CURL_HTTP_VERSION_2TLS, CURL_REDIR_POST_301, CURL_REDIR_POST_302, CURL_REDIR_POST_303, CURL_REDIR_POST_ALL, CURL_VERSION_KERBEROS5, CURL_VERSION_PSL, CURL_VERSION_UNIX_SOCKETS, CURLAUTH_NEGOTIATE, CURLAUTH_NTLM_WB, CURLFTP_CREATE_DIR, CURLFTP_CREATE_DIR_NONE, CURLFTP_CREATE_DIR_RETRY, CURLHEADER_SEPARATE, CURLHEADER_UNIFIED, CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLMOPT_MAX_HOST_CONNECTIONS, CURLMOPT_MAX_PIPELINE_LENGTH, CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPT_CONNECT_TO, CURLOPT_DEFAULT_PROTOCOL, CURLOPT_DNS_INTERFACE, CURLOPT_DNS_LOCAL_IP4, CURLOPT_DNS_LOCAL_IP6, CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPT_HEADEROPT, CURLOPT_LOGIN_OPTIONS, CURLOPT_PATH_AS_IS, CURLOPT_PINNEDPUBLICKEY, CURLOPT_PIPEWAIT, CURLOPT_PROXY_SERVICE_NAME, CURLOPT_PROXYHEADER, CURLOPT_SASL_IR, CURLOPT_SERVICE_NAME, CURLOPT_SSL_ENABLE_ALPN, CURLOPT_SSL_ENABLE_NPN, CURLOPT_SSL_FALSESTART, CURLOPT_SSL_VERIFYSTATUS, CURLOPT_STREAM_WEIGHT, CURLOPT_TCP_FASTOPEN, CURLOPT_TFTP_NO_OPTIONS, CURLOPT_UNIX_SOCKET_PATH, CURLOPT_XOAUTH2_BEARER, CURLPROTO_SMB, CURLPROTO_SMBS, CURLPROXY_HTTP_1_0, CURLSSH_AUTH_AGENT ve CURLSSLOPT_NO_REVOKE eklendi.

Örnekler

Örnek 1 - Yeni bir cURL oturumunun ilklendirilmesi ve bir HTML sayfasının alınması

<?php
// Yeni bir cURL özkaynağı oluşturalım
$ct = curl_init();

// URL'yi ve ilgili seçenekleri belirtelim
curl_setopt($ct, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ct, CURLOPT_HEADER, false);

// URL'yi tarayıcıya aktaralım
curl_exec($ct);

// cURL özkaynağını kapatıp sistem özkaynaklarını serbest bırakalım
curl_close($ct);
?>

Notlar

Bilginize:

CURLOPT_POSTFIELDS seçeneğine bir dizinin aktarılması verinin multipart/form-data olarak kodlanmasına, bir URL kodlu dizge atanması ise verinin application/x-www-form-urlencoded olarak kodlanmasına sebep olur.

Ayrıca Bakınız

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
14 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