PHP 8.3.4 Released!

curl_setopt

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

curl_setoptcURL 転送用オプションを設定する

説明

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

指定した cURL セッションハンドルのオプションを設定します。

パラメータ

handle

curl_init() が返す cURL ハンドル。

option

設定したい CURLOPT_XXX オプション。

value

option に設定する値。

value には、 option の以下の値に関して bool 値を指定する必要があります。

オプション value への設定値 注記
CURLOPT_AUTOREFERER true を設定すると、Location: によるリダイレクトを たどる際には自動的に Referer: フィールドをリクエストに 追加します。
CURLOPT_COOKIESESSION true を設定すると、クッキーの "セッション" を新しく開始します。 以前のセッションで読み込まれていた "セッションクッキー" は無視するよう、 libcurl に指示します。デフォルトでは、それがセッションクッキーであるか どうかにかかわらず libcurl はすべてのクッキーを読み込んで保存します。 セッションクッキーとは、有効期限が指定されておらず "セッション" の間のみ 有効であるクッキーのことです。
CURLOPT_CERTINFO true を設定すると、セキュアな転送時に SSL 証明書の情報を STDERR に出力します。 cURL 7.19.1 で追加されました。 これを使うには、CURLOPT_VERBOSE を on にしておかなければなりません。
CURLOPT_CONNECT_ONLY true を設定すると、プロキシの認証や接続の確立などをすべて行いますが、データは転送しません。 このオプションは、HTTP や SMTP そして POP3 用に実装されています。 cURL 7.15.2 で追加されました。
CURLOPT_CRLF true を設定すると、転送時に Unix 形式の改行を CRLF 形式に変換します。
CURLOPT_DISALLOW_USERNAME_IN_URL ユーザー名をURLに含めてはいけない場合に true にします。 デフォルトは 0 で、ユーザー名は許可されています。 cURL 7.61.0 で追加されました。 PHP 7.3.0 以降で利用可能です。
CURLOPT_DNS_SHUFFLE_ADDRESSES 名前が解決され、ひとつ以上のIPアドレスが返された際、 ランダムな順番でそれらを利用するために、 返されたアドレスの順番をシャッフルする場合に true にします。 これによって、IPv6 アドレスの前に IPv4 アドレスが使われるなどの事象が起こるかもしれません。 cURL 7.60.0 で追加されました。 PHP 7.3.0 以降で利用可能です。
CURLOPT_HAPROXYPROTOCOL HAProxy Proxy プロトコル v1 ヘッダを接続の開始時に送信する場合に true にします。 デフォルトではこのヘッダは送信されません。 cURL 7.60.0 で追加されました。 PHP 7.3.0 以降で利用可能です。
CURLOPT_SSH_COMPRESSION ビルトインの SSH 圧縮を有効にする場合に true にします。 これはリクエストであり、命令ではありません。 つまり、圧縮されるかどうかはサーバー次第です。 cURL 7.56.0 で追加されました。 PHP 7.3.0 以降で利用可能です。
CURLOPT_DNS_USE_GLOBAL_CACHE true を設定すると、グローバル DNS キャッシュを利用します。 このオプションはスレッドセーフではありません。 また、PHP がスレッドセーフでない用途でビルドされている場合 (CLI, FCGI, Apache2-Prefork など) には、デフォルトで有効になっています。
CURLOPT_FAILONERROR true を設定すると、HTTP で 400 以上のコードが返ってきた際に 処理失敗と判断します。デフォルトでは、コードの値を無視して ページの内容を取得します。
CURLOPT_SSL_FALSESTART true にすると、TLS false start を有効にします。 cURL 7.42.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_FILETIME true を設定すると、ドキュメントの更新日時を取得しようと試みます。 この値を取得するには、curl_getinfo()CURLINFO_FILETIME オプションを用います。
CURLOPT_FOLLOWLOCATION true を設定すると、サーバーが HTTP ヘッダの一部として送ってくる "Location: " ヘッダの内容をたどります。 CURLOPT_MAXREDIRS も参照ください。
CURLOPT_FORBID_REUSE true を設定すると、処理が終了した際に明示的に接続を切断します。 接続を再利用しません。
CURLOPT_FRESH_CONNECT true を設定すると、キャッシュされている接続を利用せずに 新しい接続を確立します。
CURLOPT_FTP_USE_EPRT true を設定すると、FTP のダウンロードに EPRT(および LPRT) を利用します。false の場合は EPRT・LPRT を無効にして PORT を利用します。
CURLOPT_FTP_USE_EPSV true を設定すると、FTP 転送の際にまず EPSV コマンドの利用を 試みます。失敗した場合は PASV を利用します。false を設定すると、 EPSV を無効にします。
CURLOPT_FTP_CREATE_MISSING_DIRS true を設定すると、FTP の操作中にパスが存在しなかったときに ディレクトリを作成します。
CURLOPT_FTPAPPEND true を設定すると、リモートファイルを上書きせずに追記します。
CURLOPT_TCP_NODELAY true にすると、TCP の Nagle アルゴリズムを解除します。解除すると、小さなパケットがネットワーク上を流れる回数をできるだけ減らそうと試みます。 libcurl 7.11.2 以降と組み合わせてコンパイルしたときに利用可能です。
CURLOPT_FTPASCII CURLOPT_TRANSFERTEXT のエイリアスです。
CURLOPT_FTPLISTONLY true を設定すると、FTP でディレクトリ名のみ表示します。
CURLOPT_HEADER true を設定すると、ヘッダの内容も出力します。
CURLINFO_HEADER_OUT true を設定すると、リクエスト文字列を追跡します。 プレフィックスが CURLINFO_ となっているのは意図的なものです。
CURLOPT_HTTP09_ALLOWED HTTP/0.9 形式のレスポンスを許可するかどうか。libcurl 7.66.0 以降のデフォルトは false です。 それより前のバージョンのデフォルトは true でした。 PHP 7.3.15 と 7.4.3 以降 および cURL >= 7.64.0 をビルドした場合に使用可能です。
CURLOPT_HTTPGET true を設定すると、HTTP のリクエスト形式を GET に戻します。 GET はデフォルト設定なので、リクエスト形式が変更されている 場合にのみ必要となります。
CURLOPT_HTTPPROXYTUNNEL true にすると、指定された HTTP プロキシを介してトンネルします。
CURLOPT_HTTP_CONTENT_DECODING false を設定すると、生の HTTP レスポンスボディを取得します。 libcurl >= 7.16.2 とビルドした場合に利用可能です。
CURLOPT_KEEP_SENDING_ON_ERROR 返されたHTTPコードが300以上であっても、リクエストボディを送信し続ける場合は true にします。 デフォルトのアクションはリクエストボディの送信を止め、 ストリームまたは接続を閉じます。 手動でNTLM認証を行う場合に、このオプションは適切です。 ほとんどのアプリケーションは、このオプションは不要です。 PHP 7.3.0 以降で、libcurl >= 7.51.0 とビルドした場合に利用可能です。
CURLOPT_MUTE true を設定すると、cURL 関数に関連する出力を完全に抑えます。 cURL 7.15.5 で削除されました (かわりに CURLOPT_RETURNTRANSFER が使えます)
CURLOPT_NETRC true を設定すると、リモートサイトと接続を確立する際に用いる ユーザー名やパスワードを、~/.netrc から取得します。
CURLOPT_NOBODY true を設定すると、出力から本文を削除します。 リクエストメソッドは HEAD となります。これを false に変更してもリクエストメソッドは GET には変わりません。
CURLOPT_NOPROGRESS true を設定すると、cURL 転送の進捗状況表示を無効にします。

注意:

PHP は、このオプションを自動的に true に設定します。 これを変更するのは、デバッグ時のみにすべきです。

CURLOPT_NOSIGNAL true を設定すると、cURL 関数が PHP プロセスに送信するシグナルを 無視します。マルチスレッド SAPI ではデフォルトで on となっており、 そのためタイムアウトオプションもまだ利用されています。 cURL 7.10 で追加されました。
CURLOPT_PATH_AS_IS true にすると、ドットの連続を処理しません。 cURL 7.42.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_PIPEWAIT true にすると、パイプライン化/多重化を待ちます。 cURL 7.42.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_POST true を設定すると、HTTP POST を行います。POST は、 application/x-www-form-urlencoded 形式で 行われます。これは一般的な HTML のフォームと同じ形式です。
CURLOPT_PUT true を設定すると、HTTP PUT を行います。PUT するファイルは CURLOPT_INFILE および CURLOPT_INFILESIZE で指定されている必要があります。
CURLOPT_RETURNTRANSFER true を設定すると、curl_exec() の戻り値を 文字列で返します。通常はデータを直接出力します。
CURLOPT_SASL_IR true にすると、最初のパケット内の最初のレスポンスの送信を有効にします。 cURL 7.31.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_SSL_ENABLE_ALPN false にすると、SSL ハンドシェイクの際の ALPN を無効にします (SSL バックエンドの libcurl がそれに対応するビルドである場合)。 これは、http2 ネゴシエーションに使えます。 cURL 7.36.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_SSL_ENABLE_NPN false にすると、SSL ハンドシェイクの際の NPN を無効にします (SSL バックエンドの libcurl がそれに対応するビルドである場合)。 これは、http2 ネゴシエーションに使えます。 cURL 7.36.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_SSL_VERIFYPEER false を設定すると、cURL はサーバー証明書の検証を行いません。 別の証明書を CURLOPT_CAINFO オプションで 指定するか、CURLOPT_CAPATH オプションで 証明ディレクトリを指定します。 cURL 7.10 以降、デフォルト値は true です。また、 cURL 7.10 以降、デフォルトでインストールされています。
CURLOPT_SSL_VERIFYSTATUS true にすると、証明書のステータスを検証します。 cURL 7.41.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_PROXY_SSL_VERIFYPEER false を設定すると、cURL がピアの証明書の検証を行わなくなります。 別の証明書を検証するには、CURLOPT_CAINFO オプションで指定するか、 CURLOPT_CAPATH を使って証明書のディレクトリを指定するやり方が使えます。 false を指定すると、ピアの証明書の検証はオプションに関係なく成功します。 true がデフォルトです。 PHP 7.3.0 以降で、libcurl >= 7.52.0 とビルドした場合に利用可能です。
CURLOPT_SAFE_UPLOAD この値は常に true になります。 CURLOPT_POSTFIELDS を使ってファイルをアップロードする際に、 プレフィックス @ のサポートを無効にします。 これは、@ で始まる値を安全にフィールドに渡せるということです。 CURLFile も代わりに使えます。
CURLOPT_SUPPRESS_CONNECT_HEADERS true を設定すると、 CURLOPT_HTTPPROXYTUNNEL を使って CONNECT リクエストが生成された場合に、 ユーザーのコールバック関数 CURLOPT_HEADERFUNCTION および CURLOPT_WRITEFUNCTION では proxy CONNECT のレスポンスヘッダを抑制します。 cURL 7.54.0 で追加されました。PHP 7.3.0 以降で使用可能です。
CURLOPT_TCP_FASTOPEN true にすると、TCP Fast Open を有効にします。 cURL 7.49.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_TFTP_NO_OPTIONS true にすると、TFTP オプションリクエストを送信しません。 cURL 7.48.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_TRANSFERTEXT true を設定すると、FTP 転送を ASCII モードで行います。 LDAP の場合は、データを HTML ではなくプレーンテキストで取得します。 Windows システムでは STDOUT に対してバイナリモードを設定しないでください。
CURLOPT_UNRESTRICTED_AUTH true を設定すると、(CURLOPT_FOLLOWLOCATION を利用して)場所をたどっていく際にユーザー名とパスワードを送信し続けます。 これは、たとえホスト名が変わっても続けられます。
CURLOPT_UPLOAD true を設定すると、アップロードの準備をします。
CURLOPT_VERBOSE true を設定すると、詳細な情報を出力します。情報は STDERR か、または CURLOPT_STDERR で指定したファイルに出力されます。

value には、 option の以下の値に関して 整数値を指定する必要があります。

オプション value への設定値 注記
CURLOPT_BUFFERSIZE 1 回の読み込みに用いるバッファのサイズ。しかしながら、必ず このバッファいっぱいまで読み込まれることを保証するものではありません。 cURL 7.10 で追加されました。
CURLOPT_CONNECTTIMEOUT 接続の試行を待ち続ける秒数。0 は永遠に待ち続けることを意味します。
CURLOPT_CONNECTTIMEOUT_MS 接続の試行を待ち続けるミリ秒数。0 は永遠に待ち続けることを意味します。 システムの標準の名前解決を使うように libcurl をビルドしている場合は、 接続のタイムアウトは秒単位の精度となり、最小のタイムアウトは 1 秒となります。 cURL 7.16.2 で追加されました。
CURLOPT_DNS_CACHE_TIMEOUT DNS エントリをメモリ内に保持し続ける秒数。デフォルトでは 120(2 分)に設定されています。
CURLOPT_EXPECT_100_TIMEOUT_MS Expect: 100-continue のレスポンスを待つタイムアウト。 ミリ秒で指定します。 デフォルトは1000ミリ秒です。 cURL 7.36.0 で追加されました。PHP 7.0.7 以降で使用可能です。
CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS Happy Eyeballs アルゴリズムで IPv6 接続を優先して開始します。 Happy Eyeballs アルゴリズムは、 デュアルスタックホストのために IPv4 と IPv6アドレス両方に接続を試みますが、 IPv6 を優先して扱い、そのタイムアウトをミリ秒単位で指定します。 デフォルトは CURL_HET_DEFAULT であり、現状は200ミリ秒です。 cURL 7.59.0 で追加されました。PHP 7.3.0 以降で使用可能です。
CURLOPT_FTPSSLAUTH (使用可能な場合の)FTP 認証方法。 CURLFTPAUTH_SSL(まず SSL を試す)、 CURLFTPAUTH_TLS(まず TLS を試す)あるいは CURLFTPAUTH_DEFAULT(cURL が決める)のいずれかです。 cURL 7.12.2 で追加されました。
CURLOPT_HEADEROPT ヘッダをどう扱うかを指定します。 次の定数のうち、一つを指定できます: CURLHEADER_UNIFIED: CURLOPT_HTTPHEADER で指定されたヘッダが、 サーバーとプロキシ双方のリクエストに対して使われます。 このオプションが有効な場合、 CURLOPT_PROXYHEADER は効果がありません。 CURLHEADER_SEPARATE: CURLOPT_HTTPHEADER で指定されたヘッダは、 プロキシには送られず、サーバーにのみ送られます。 プロキシに送るヘッダは、 CURLOPT_PROXYHEADER を設定しなければなりません。 CONNECT でないリクエストがプロキシに送信された場合、 libcurl はサーバーとプロキシ両方にヘッダを送信することに注意してください。 CONNECT リクエストを送信する場合、 libcurl は CURLOPT_PROXYHEADER をプロキシのみに送り、 CURLOPT_HTTPHEADER をサーバーにのみ送信します。 cURL 7.42.1 以降は CURLHEADER_SEPARATE がデフォルトで、 それより前では、 CURLHEADER_UNIFIED がデフォルトでした。 cURL 7.37.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (デフォルト。 使用するバージョンを決めるのは cURL にまかせる)、 CURL_HTTP_VERSION_1_0 (HTTP/1.0 を使用する)、 あるいは CURL_HTTP_VERSION_1_1 (HTTP/1.1 を使用する) CURL_HTTP_VERSION_2_0 (HTTP 2 の使用を試みる), CURL_HTTP_VERSION_2 (CURL_HTTP_VERSION_2_0 のエイリアス), CURL_HTTP_VERSION_2TLS (TLS (https) の場合のみ HTTP 2 の使用を試みる) または CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE (HTTP 1.1 へのアップグレードを行わず、HTTP/2 を使って TLS でないリクエストを発行する) のいずれかです。
CURLOPT_HTTPAUTH

使用する HTTP 認証方法。以下の中から選びます。 CURLAUTH_BASICCURLAUTH_DIGESTCURLAUTH_GSSNEGOTIATECURLAUTH_NTLMCURLAUTH_AWS_SIGV4CURLAUTH_ANY および CURLAUTH_ANYSAFE

2 つ以上の方法を組み合わせるには、ビット演算子 |(or) を使用します。このような場合、cURL はサーバーがサポートしている方法を 問い合わせたうえで最適な方法を選択します。

CURLAUTH_ANY は、全てのビットを設定します。 この場合 cURL は、もっともセキュアなものを自動で選択します。

CURLAUTH_ANYSAFE は、 CURLAUTH_BASIC 以外の全てのビットを設定します。 この場合 cURL は、もっともセキュアなものを自動で選択します。

CURLOPT_INFILESIZE ファイルをリモートサイトにアップロードする際のファイルサイズ。 このオプションを指定しても、libcurl がそれ以上のデータを送信するのは止められないことに注意しましょう。 実際に何が送信されるのかは CURLOPT_READFUNCTION に依存します。
CURLOPT_LOW_SPEED_LIMIT 1 秒あたりのバイト数で、転送速度がこれより遅い期間が CURLOPT_LOW_SPEED_TIME 秒以上続いた場合に PHP は転送を終了します。
CURLOPT_LOW_SPEED_TIME 転送速度が CURLOPT_LOW_SPEED_LIMIT より遅い期間がどれだけ続いた場合に転送を異常終了させるかを、 秒単位で指定します。
CURLOPT_MAIL_RCPT_ALLLOWFAILS 送信先によっては、RCPT TO コマンドが失敗することを許可します。 複数の送信先にデータを送る場合、 デフォルトで cURL は RCPT TO コマンドが送信先のうちひとつでも失敗すると、SMTP の通信を中止します。 このオプションは cURL にエラーを無視し、 有効な送信先の処理は続行するように指示します。 すべての送信先の RCPT TO コマンドが失敗した場合にこのフラグが設定されていた場合は、cURL は SMTP の通信を中止し、最後に実行された RCPT TO コマンドから受け取ったエラーを返します。
CURLOPT_MAXAGE_CONN 既存の接続を再利用して良いとみなす、アイドル時間の最大値。 デフォルトは 118 秒に設定されています。
CURLOPT_MAXFILESIZE_LARGE ダウンロードできるファイルの最大サイズをバイト単位で設定します。 この値より大きなファイルがリクエストされた場合、 通信は開始されず、CURLE_FILESIZE_EXCEEDED が返されます。 ダウンロードが始まる前にファイルサイズが常にわかっているわけではないので、ファイルの転送量が指定された最大サイズよりも結局大きかった場合は、このオプションは意味がありません。
CURLOPT_MAXLIFETIME_CONN 接続が作成されてから、 既存の接続を再利用してもよいと見なすまでの時間の最大値。 秒単位で指定します。 接続がキャッシュに存在し、この値より古いことがわかった場合、 転送中の通信が完了した場合に接続は一度クローズされます。 デフォルトは0です。つまり、 このオプションは無効になっており、 あらゆる接続が再利用の対象になります。
CURLOPT_MAXCONNECTS 許可される持続的接続の最大数。もしこの値に達した場合、 オープンされている接続数が増えるのを避けるため、 キャッシュされている接続のうち一番古いものを閉じます。
CURLOPT_MAXREDIRS HTTP のリダイレクト先を追いかける最大値。 CURLOPT_FOLLOWLOCATION とあわせて使用します。 リダイレクトループを避けるため、 デフォルト値として 20 が設定されています。 -1 を設定すると、リダイレクトループを許可します。 0 を指定すると、全てのリダイレクトを拒否します。
CURLOPT_PORT 接続先のポート番号。
CURLOPT_POSTREDIR CURLOPT_FOLLOWLOCATION が設定されているときに、 どの形式のリダイレクトの場合に HTTP POST メソッドを維持するのかを、 1 (301 Moved Permanently)、2 (302 Found)、4 (303 See Other) のビットマスクで指定します。 cURL 7.19.1 で追加されました。
CURLOPT_PROTOCOLS

CURLPROTO_* の値のビットマスク。使用すると、 転送時に libcurl がどのプロトコルを使用するのかに制約を加えます。 さまざまなプロトコルに対応するよう libcurl をビルドしていた場合でも、 これによって特定の転送プロトコルのみを使用するように制限することができます。 デフォルトでは、libcurl がサポートしているすべてのプロトコルの使用を許可します。 CURLOPT_REDIR_PROTOCOLS も参照ください。

使用できるプロトコルオプションは次のとおりです。 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 で追加されました。
CURLOPT_PROXYAUTH プロキシ接続に使用する HTTP 認証の方法。 CURLOPT_HTTPAUTH で説明したのと同じオプションを 指定可能です。プロキシ認証でサポートされているのは、今のところ CURLAUTH_BASIC および CURLAUTH_NTLM のみです。 cURL 7.10.7 で追加されました。
CURLOPT_PROXYPORT プロキシ接続のポート番号。このポート番号は、 CURLOPT_PROXY で指定することも可能です。
CURLOPT_PROXYTYPE CURLPROXY_HTTP(デフォルト)、 CURLPROXY_SOCKS4CURLPROXY_SOCKS5CURLPROXY_SOCKS4A あるいは CURLPROXY_SOCKS5_HOSTNAME cURL 7.10 で追加されました。
CURLOPT_REDIR_PROTOCOLS CURLPROTO_* の値のビットマスク。使用すると、 CURLOPT_FOLLOWLOCATION が有効な場合のリダイレクト時の転送に libcurl がどのプロトコルを使用するのかに制約を加えます。これによって、 リダイレクト時に特定の転送プロトコルのみを使用するように制限することができます。 デフォルトでは、libcurl がサポートしているすべてのプロトコルのうち FILE と SCP 以外のすべての使用を許可します。この挙動は 7.19.4 より前のバージョンとは異なります。7.19.4 より前のバージョンでは、 サポートするすべてのプロトコルを無条件に許可していました。 プロトコル定数の値は CURLOPT_PROTOCOLS を参照ください。 cURL 7.19.4 で追加されました。
CURLOPT_RESUME_FROM 転送を途中から再開する場合のバイトオフセット。
CURLOPT_SOCKS5_AUTH

利用する SOCKS5 認証方法。以下が指定できます: CURLAUTH_BASIC, CURLAUTH_GSSAPI, CURLAUTH_NONE

一つ以上の認証方法を組み合わせるために ビット演算子 | (or) が使えます。 これを使うと、cURL がどの方法をサポートしているかをポーリングし、もっとも良いものを選択します。

CURLAUTH_BASIC を指定すると、ユーザー名/パスワード による認証ができます。

CURLAUTH_GSSAPI を指定すると、GSS-API 認証ができます。

CURLAUTH_NONE を指定すると、認証は行われません。

デフォルトは CURLAUTH_BASIC|CURLAUTH_GSSAPI です。 実際のユーザー名とパスワードは CURLOPT_PROXYUSERPWD オプションを使って設定してください。

PHP 7.3.0 以降 および curl >= 7.55.0 で利用可能です。
CURLOPT_SSL_OPTIONS SSL 関連の振る舞いのオプションを設定します。 以下に示す定数のビットマスクの組み合わせです: CURLSSLOPT_ALLOW_BEAST: SSL3 や TLS1.0 プロトコルのセキュリティ上の欠陥を回避するあらゆる手段を使わない。 CURLSSLOPT_NO_REVOKE: 証明書の失効チェックを行うSSLバックエンドについて、それを無効にする。 CURLSSLOPT_AUTO_CLIENT_CERT: クライアント証明書を認証のために自動で配置し、 サーバーからリクエストがあったときは利用します。 このオプションは Schannel (native Windows SSL library) でのみサポートされています。 CURLSSLOPT_NATIVE_CA: オペレーティングシステムのネイティブなCAストアを、 証明書の検証に用います。これは OpenSSL を Windows でビルドしたときにのみ使えます。このオプションは実験的なものであり、振る舞いが変更される可能性があります。 CURLSSLOPT_NO_PARTIALCHAIN: "部分的な" 証明書チェインを許可しません。 この点以外は、cURL のデフォルトの振る舞いをします。 このオプションは、OpenSSL でのみサポートされています。 証明書チェインがルート証明書ではなく、 中間証明書で終わっていた場合は、証明書の検証が失敗します。 CURLSSLOPT_REVOKE_BEST_EFFORT: 配布ポイントがオフラインであったり、存在しない場合に、証明書の失効チェックを無視します。 このオプションは Schannel (native Windows SSL library) でのみサポートされています。 CURLSSLOPT_NO_REVOKE と組み合わせて使った場合、後に設定した方が優先されます。 cURL 7.25.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_SSL_VERIFYHOST 2 は、SSL ピア証明書の Subject Alternate Name フィールド、 または Common Name フィールドの値が、指定されたホスト名にマッチするかを調べます。 0 は、名前をチェックしません。 1 は、使うべきではありません。 本番環境では、このオプションの値は常に 2 (デフォルト値) にしておかなければなりません。 1 は、cURL 7.28.1 以降では使えなくなりました。
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)、 CURL_SSLVERSION_TLSv1_3 (7) のいずれかの値。 TLSバージョンの最大値は、定数 CURL_SSLVERSION_MAX_* で設定できます。 定数 CURL_SSLVERSION_MAX_* のうちのひとつと、 定数 CURL_SSLVERSION_* のうちのひとつを OR で設定することもできます。 CURL_SSLVERSION_MAX_DEFAULT (ライブラリがサポートする最大のバージョン), CURL_SSLVERSION_MAX_TLSv1_0, CURL_SSLVERSION_MAX_TLSv1_1, CURL_SSLVERSION_MAX_TLSv1_2, または CURL_SSLVERSION_MAX_TLSv1_3.

注意:

この値は何も設定せず、デフォルトに任せるのが最適です。 2 や 3 を設定すると、SSLv2 および SSLv3 の既知の脆弱性の影響を受けるため、非常に危険です。

CURLOPT_PROXY_SSL_OPTIONS HTTPSプロキシの振る舞いを設定するオプションです。 これは以下の定数のうち、任意のものを組み合わせたビットマスクです: CURLSSLOPT_ALLOW_BEAST: SSL3 と TLS1.0 プロトコルに存在する脆弱性を回避するための回避策を使いません。 CURLSSLOPT_NO_REVOKE: SSLバックエンドの証明書の失効チェックを無効にします。 但し、そうした振る舞いが存在した場合に限ります(curl >= 7.44.0) CURLSSLOPT_NO_PARTIALCHAIN: "部分的な"証明書チェインを許可しません。 デフォルトでは許可されています(curl >= 7.68.0) PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_SSL_VERIFYHOST HTTPSプロキシの証明書の名前フィールドをプロキシ名と突き合わせて検証する場合 2 を設定します。 0 を設定すると、証明書でどのような名前が使われていようと、接続は成功します。 注意して使用してください! 1 は curl 7.28.0 以前ではデバッグオプションとして扱われていました。 curl 7.28.1 から 7.65.3 までは CURLE_BAD_FUNCTION_ARGUMENT が返されていました。 curl 7.66.0 以降では 12 は同じ値として扱われます。 本番環境では、このオプションの値は (デフォルトの) 2 であるべきです。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
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, CURL_SSLVERSION_SSLv3

注意:

最も良い選択は、このオプションを設定せず、 デフォルトの CURL_SSLVERSION_DEFAULT を使うことです。 このオプションは、リモートのSSLプロトコルのバージョンを見つけようとします。

PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_STREAM_WEIGHT ストリームの重みを数値で設定します(1 から 256 までの数値) cURL 7.46.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_TCP_KEEPALIVE この値を 1 に設定すると、TCP keepalive のプローブが送信されます。 これらのプローブを送信する頻度と遅延時間は オペレーティングシステムがサポートしていれば CURLOPT_TCP_KEEPIDLECURLOPT_TCP_KEEPINTVL で制御可能です。 0 に設定すると(デフォルト)、keepalive のプローブは送信されません。 cURL 7.25.0 で追加されました。
CURLOPT_TCP_KEEPIDLE CURLOPT_TCP_KEEPALIVE が有効になっている場合に、 keepalive のプローブを送信する前に、接続をアイドルなままにしてオペレーティングシステムを待たせる 遅延時間を秒単位で設定します。 全てのオペレーティングシステムがこのオプションをサポートしているわけではありません。 デフォルトは 60 です。 cURL 7.25.0 で追加されました。
CURLOPT_TCP_KEEPINTVL CURLOPT_TCP_KEEPALIVE が有効になっている場合に、 keepalive のプローブを送信する前に、オペレーティングシステムが待つ間隔を秒単位で設定します。 全てのオペレーティングシステムがこのオプションをサポートしているわけではありません。 デフォルトは 60 です。 cURL 7.25.0 で追加されました。
CURLOPT_TIMECONDITION CURLOPT_TIMEVALUE の扱いを決定します。 CURLOPT_TIMEVALUE で指定した時刻以降に 変更されたページのみを返す場合は CURL_TIMECOND_IFMODSINCE を使用します。 CURLOPT_HEADERtrue だと仮定すると、 ページが変更されていない場合は "304 Not Modified" ヘッダが返されます。 CURL_TIMECOND_IFUNMODSINCE は反対の意味です。 cURL 7.46.0 より前のバージョンでは、 CURL_TIMECOND_IFMODSINCE がデフォルトでした。
CURLOPT_TIMEOUT cURL 関数の実行にかけられる時間の最大値。
CURLOPT_TIMEOUT_MS cURL 関数の実行にかけられる最大のミリ秒数。 システムの標準の名前解決を使うように libcurl をビルドしている場合は、 接続のタイムアウトは秒単位の精度となり、最小のタイムアウトは 1 秒となります。 cURL 7.16.2 で追加されました。
CURLOPT_TIMEVALUE 1970 年 1 月 1 日からの経過秒数。この値は CURLOPT_TIMECONDITION で使用されます。
CURLOPT_TIMEVALUE_LARGE 1970年1月1日からの経過時刻を秒単位で示します。 この値は CURLOPT_TIMECONDITION によって使われます。 デフォルトは0です。 このオプションと CURLOPT_TIMEVALUE の違いは引数の型です。 'long' が 32ビット長しかないシステムでは、 2038年以降の日付を設定するためにこのオプションを使わなければいけません。 cURL 7.59.0 で追加されました。PHP 7.3.0 以降で使用可能です。
CURLOPT_UPKEEP_INTERVAL_MS プロトコルによっては、 "connection upkeep" (接続を維持する) 仕組みを備えているものがあります。 通常、この仕組みは接続を維持するため、既存の接続に対して少量のトラフィックを送信します。 このオプションは、接続を維持するためのトラフィックを送信する間隔を指定します。 こうした接続を維持する仕組みは、現状 HTTP/2 の接続でのみ利用できます。 この接続を維持するための間隔を超えた場合、HTTP/2 PING フレームが送信されます。デフォルトは 60 秒です。
CURLOPT_UPLOAD_BUFFERSIZE cURL のアップロードバッファの好ましいサイズを、 バイト単位で指定します。 アップロードのバッファサイズは、デフォルトでは 64キロバイトです。 バッファサイズの最大値は、2メガバイトになっています。 バッファサイズの最小値は、16キロバイトになっています。
CURLOPT_MAX_RECV_SPEED_LARGE ダウンロード速度 (単位は「バイト/秒」) の転送中累加平均がこの値を超えると、 転送を一時停止して、平均速度がこのパラメータの値以下に落ちるまで待ちます。 デフォルトは無制限です。 cURL 7.15.5 で追加されました。
CURLOPT_MAX_SEND_SPEED_LARGE アップロード速度 (単位は「バイト/秒」) の転送中累加平均がこの値を超えると、 転送を一時停止して、平均速度がこのパラメータの値以下に落ちるまで待ちます。 デフォルトは無制限です。 cURL 7.15.5 で追加されました。
CURLOPT_SSH_AUTH_TYPES CURLSSH_AUTH_PUBLICKEY, CURLSSH_AUTH_PASSWORD, CURLSSH_AUTH_HOST, CURLSSH_AUTH_KEYBOARD のビットマスク。 CURLSSH_AUTH_ANY にすると libcurl がいずれかひとつを選択します。 cURL 7.16.1 で追加されました。
CURLOPT_IPRESOLVE ホスト名の解決にどの形式の IP アドレスを使うのかを、アプリケーションが選べるようにします。 複数のバージョンの IP アドレスで解決できるホスト名のときに使うもので、指定できる値は CURL_IPRESOLVE_WHATEVERCURL_IPRESOLVE_V4 そして CURL_IPRESOLVE_V6 です。 デフォルトは CURL_IPRESOLVE_WHATEVER です。 cURL 7.10.8 で追加されました。
CURLOPT_FTP_FILEMETHOD FTP(S) サーバー上のファイルに到達するために使う方法を curl に伝えます。利用可能な値は CURLFTPMETHOD_DEFAULTCURLFTPMETHOD_MULTICWDCURLFTPMETHOD_NOCWD および CURLFTPMETHOD_SINGLECWD です。 cURL 7.15.1 で追加されました。

value は、 option パラメータの 以下の値に関して文字列である必要があります。

オプション value への設定値 注記
CURLOPT_ABSTRACT_UNIX_SOCKET ホストにTCP接続する代わりに、抽象化されたUnixドメインソケットの使用を有効にし、 パスを指定された string に設定します。 このオプションは CURLOPT_UNIX_SOCKET_PATH と同じセマンティクスを共有しています。 これらのふたつのオプションは同じストレージを共有するので、 ハンドルごとにそれらのうちのひとつだけを設定できます。 cURL 7.53.0 で追加されました。PHP 7.3.0 以降で利用可能です。
CURLOPT_ALTSVC Alt-Svc キャッシュとして使うファイル名を cURL に指定します。 これは既存のキャッシュコンテンツを読み取る目的で使います。 また、通信が完了した後に書き込む可能性があります。 書き込むのは、CURLALTSVC_READONLYFILECURLOPT_ALTSVC_CTRL 経由で設定されていない場合に限ります。
CURLOPT_ALTSVC_CTRL このハンドルを使って転送する際に、Alt-Svc をどう扱うかを cURL に指示するために、有効な機能をまとめてビットマスクで指定します。 cURL は Alt-Svc ヘッダを HTTPS の場合にのみ受け入れます。 origin が HTTPS で適切にホストされている場合にのみ、cURL は別のオリジンへのリクエストも完了できます。 以下のいずれかのビットを設定すると、Alt-Svc エンジンは有効になります。 オプションは以下のとおりです: CURLALTSVC_H1, CURLALTSVC_H2, CURLALTSVC_H3 および CURLALTSVC_READONLYFILE
CURLOPT_AWS_SIGV4

AWS V4 signature authentication を、HTTP(S) ヘッダで指定します。

このオプションは、CURLOPT_HTTPAUTH で設定されている他のあらゆる認証タイプを上書きします。 このメソッドは、他の認証タイプと組み合わせることができません。

CURLOPT_CAINFO 接続先を検証するための証明書を保持するファイル名。 これは CURLOPT_SSL_VERIFYPEER を使用する場合に のみ意味を持ちます。 絶対パスで指定しなければならないでしょう。
CURLOPT_CAINFO_BLOB 接続先を検証するための、ひとつ以上の証明書保持するPEMファイルの名前。 このオプションは、CURLOPT_CAINFO を上書きします。 PHP 8.2.0 と、cURL 7.77.0 以降で利用可能です。
CURLOPT_CAPATH 複数の証明書ファイルを保持するディレクトリ。このオプションは CURLOPT_SSL_VERIFYPEER とともに使用します。
CURLOPT_COOKIE HTTP リクエストにおける "Cookie: " ヘッダの内容。 クッキーが複数ある場合は、セミコロンとスペースで区切られる (例 "fruit=apple; colour=red") ことに注意しましょう。
CURLOPT_COOKIEFILE クッキーのデータを保持するファイルの名前。クッキーファイルは、 Netscape フォーマットあるいは HTTP ヘッダを単純にファイルにダンプしたものが使用可能です。 名前が空文字列の場合はクッキーを読み込みませんが、クッキーの処理は有効なままです。
CURLOPT_COOKIEJAR ハンドルを閉じる際 (curl_close のコール後など) に、 すべての内部クッキーを保存するファイルの名前。
CURLOPT_COOKIELIST 内部的な Cookie ストアに追加するCookie文字列(つまり、NetScape/Mozilla フォーマット または HTTP形式の Set-Cookieヘッダ)。 "ALL" の場合、メモリに保持している全てのクッキーを削除します。 "SESS" の場合、メモリに保持している全てのセッションクッキーを削除します。 "FLUSH" の場合、CURLOPT_COOKIEJAR で指定されたファイルに全ての既知の Cooie を書き込みます。 "RELOAD" の場合、CURLOPT_COOKIEFILE で指定されたファイルから全てのクッキーを読み込みます。 cURL 7.14.1 以降で利用可能です。
CURLOPT_CUSTOMREQUEST HTTP リクエストで "GET" あるいは "HEAD" 以外に 使用するカスタムメソッド。これが有用なのは、"DELETE" やその他のあまり知られていない HTTP リクエストを実行する場合です。 使用可能な値は "GET""POST""CONNECT" などです。 HTTP リクエストの内容をすべて指定するわけではありません。つまり、 "GET /index.html HTTP/1.0\r\n\r\n" のような 記述は間違いだということです。

注意:

使用しようとしているメソッドをサーバーがサポートしていることを 確かめるまで、これを使用しないでください。

CURLOPT_DEFAULT_PROTOCOL

URL にスキーム名がなかった場合のデフォルトのプロトコル

cURL 7.45.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_DNS_INTERFACE

DNS リゾルバがバインドするべきネットワークインターフェイス名を設定します。 これは、(アドレスではなく)インターフェイス名でなければなりません。

cURL 7.33.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_DNS_LOCAL_IP4

リゾルバがバインドするべきローカルの IPv4 アドレスを設定します。 この値は、数値の IPv4 アドレスを文字列で含めるべきです。

cURL 7.33.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_DNS_LOCAL_IP6

リゾルバがバインドするべきローカルの IPv6 アドレスを設定します。 この値は、数値の IPv6 アドレスを文字列で含めるべきです。

cURL 7.33.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_EGDSOCKET CURLOPT_RANDOM_FILE と似ていますが、 Entropy Gathering Daemon ソケットを使用してファイル名を生成する点が 違います。
CURLOPT_ENCODING "Accept-Encoding: " ヘッダの内容。 これにより、応答のデコードを可能にします。サポートされる エンコーディングは "identity""deflate" および "gzip" です。もし空文字列 "" が指定された場合、 サポートされるエンコーディングをすべて含むヘッダが送信されます。 cURL 7.10 で追加されました。
CURLOPT_FTPPORT FTP で "PORT" を使用するための IP アドレスを取得する際に使用される値。 "PORT" は、リモートサーバーに対してこちらが指定した IP アドレスに 接続するよう指示します。この値に設定できる内容は IP アドレス、ホスト名、 ネットワークインターフェイス名(Unix)、あるいは単に '-' を指定する ことでシステムのデフォルト IP アドレスを指定します。
CURLOPT_HSTS

HSTS (HTTP Strict Transport Security) が用いるキャッシュファイル名

CURLOPT_HSTS_CTRL

HSTS (HTTP Strict Transport Security) の振る舞いを制御します。 このハンドルを使って転送する際に、HSTS をどう扱うかを cURL に指示するために、有効な機能をまとめてビットマスクで指定します。 CURLHSTS_ENABLE を使うと、インメモリのキャッシュが有効になります。 HSTS のキャッシュファイルが指定されると、 CURLHSTS_READONLYFILE を使うことで、ファイルを読み取り専用にできます。

CURLOPT_INTERFACE 使用するネットワークインターフェイスの名前。 インターフェイス名、IP アドレスあるいはホスト名が指定可能です。
CURLOPT_KEYPASSWD CURLOPT_SSLKEY あるいは CURLOPT_SSH_PRIVATE_KEYFILE 秘密鍵を使うときに必須となるパスワード。 cURL 7.16.1 で追加されました。
CURLOPT_KRB4LEVEL KRB4(Kerberos 4)セキュリティレベル。以下の値のいずれか (セキュリティの低い順です)が指定可能です。 "clear""safe""confidential""private"。 文字列がこれらのどれでもなかった場合は、 "private" が使用されます。このオプションを null にすると KRB4 セキュリティを無効にします。現時点では、KRB4 セキュリティは FTP 転送にのみ使用可能です。
CURLOPT_LOGIN_OPTIONS プロトコル特有のログインオプションを設定するために使えます。 たとえば好ましい認証メカニズムが "AUTH=NTLM" とか "AUTH=*" の場合で、 CURLOPT_USERNAME オプションと組み合わせて使うべき場合です。 cURL 7.34.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_PINNEDPUBLICKEY ピン止めされた公開鍵を設定します。 ピン止めされた公開鍵のファイル名ファイル名を文字列として指定できます。 期待されているファイルフォーマットは "PEM" または "DER" 形式です。 文字列は、 base64 エンコードされた sha256 ハッシュで、 "sha256//" が先頭に付いたものです。これを任意の数だけ指定でき、 ";" で区切られます。 cURL 7.39.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_POSTFIELDS HTTP "POST" で送信するすべてのデータ。 このパラメータは 'para1=val1&para2=val2&...' のように url エンコードされた文字列形式で渡すこともできますし、 フィールド名をキー、データを値とする配列で渡すこともできます。 value が配列の場合、 Content-Type ヘッダには multipart/form-data を設定します。 ファイルは CURLFile または CURLStringFile を使って送信することが出来ます。 この場合、value は配列でなければなりません。
CURLOPT_PRIVATE この cURL ハンドルに関連づけるデータ。ここで関連づけたデータは、 curl_getinfo()CURLINFO_PRIVATE オプションで取得できます。 cURL はデータを一切加工しません。 cURL マルチハンドルを使う場合は一般的に、この値が cURL ハンドルを特定する一意なキーとなります。 cURL 7.10.3 で追加されました。
CURLOPT_PRE_PROXY CURLOPT_PROXY で指定された HTTP(S) プロキシにcurlが接続する前に、 事前に接続する preproxy を設定します。 この値には、ホスト名またはドットで区切られた数値のIPアドレスを設定します。 preproxy は SOCKS プロキシだけがなることができ、 どの socks を使うかを指定するために [scheme]:// を先頭に付けます。 数値の IPv6 アドレスは 角括弧 "[]" 内に書かなければいけません。 preproxy にから文字列を設定すると、明示的に preproxy を無効にできます。 この文字列にポート番号を設定するには、 ホスト名の最後に :[port] を追加します。 プロキシのポート番号は別のオプション CURLOPT_PROXYPORT で指定しても構いません。ポート番号を指定しない場合は、 デフォルトでは 1080 を使います。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY リクエストを経由させる HTTP プロキシ。
CURLOPT_PROXY_SERVICE_NAME プロキシ認証サービス名 HTTP プロキシについては、cURL 7.43.0 で追加されました。 SOCKS5 プロキシについては、cURL 7.49.0 で追加されました。 PHP 7.0.7 以降で利用可能です。
CURLOPT_PROXY_CAINFO プロキシの Certificate Authority (CA) バンドルのパスを指定します。 HTTPS プロキシを検証するための証明書をひとつ以上持つ、ファイルの名前を文字列で設定します。 このオプションは HTTPS プロキシに接続するためのものであって、 HTTPS サーバーに接続するためのものではありません。 デフォルトは、libcurl が cacert バンドルを保存していると想定しているシステムパスに設定されています。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_CAINFO_BLOB HTTPS プロキシを検証するための証明書をひとつ以上持つ、PEMファイルの名前を設定します。 このオプションは HTTPS プロキシに接続するためのものであって、 HTTPS サーバーに接続するためのものではありません。 デフォルトは、libcurl が cacert バンドルを保存していると想定しているシステムパスに設定されています。 PHP 8.2.0 以降および、cURL >= 7.77.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_CAPATH HTTPSプロキシを検証するための複数のCA証明書が置かれたディレクトリ。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_CRLFILE PEMフォーマットの CRL (Certificate Revocation List, 証明書失効リスト) を連結したファイル名を設定します。 これはSSL通信の際に行われる証明書の検証に使います。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_KEYPASSWD CURLOPT_PROXY_SSLKEY で設定する秘密鍵で使う、 必須のパスワードを設定します。 証明書を読み込むのにパスフレーズは不要ですが、 秘密鍵を読み込むにはパスフレーズが必要です。 このオプションはHTTPSプロキシに接続するために必要です。 HTTPSサーバーに接続するためのものではありません。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_PINNEDPUBLICKEY HTTPSプロキシ向けの pinned public key を設定します。 pinned public key のファイル名を文字列で設定できます。 ファイルフォーマットは "PEM" または "DER" です。 base64 エンコードされた sha256 ハッシュ を任意の数だけ "sha256//" の後に続けることもできます。このハッシュは ";" で区切ります。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_SSLCERT HTTPSプロキシに接続する時に使うクライアント証明書のフォーマット。 デフォルトは Secure Transport の場合 "P12" で、 それ以外のエンジンでは "PEM" ですが、 CURLOPT_PROXY_SSLCERTTYPE でも変更できます。 NSS や Secure transport では、 セキュリティデータベースで名付けられた証明書のニックネームも設定できます。 現在のディレクトリにあるファイルを使いたい場合は、 ニックネームとの混乱を避けるため "./" をプレフィックスとして付けてください。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_SSLCERTTYPE HTTPSプロキシに接続する時に使うクライアント証明書のフォーマット。 サポートされているのは "PEM" と "DER" ですが、 Secure Transport はこれらをサポートしていません。 OpenSSL (0.9.3 以降) と Secure Transport (iOS 5 以降, または OS X 10.7 以降) では PKCS#12-encoded ファイル向けに "P12" もサポートしています。デフォルトは "PEM" です。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_SSL_CIPHER_LIST HTTPSプロキシと接続を確立するために使う暗号スイートの一覧。 この一覧はひとつ以上の暗号スイートの文字列がコロンで区切られており、 構文的に正しくなければなりません。 コンマやスペースも区切り文字としては有効ですが、通常はコロンが使われます。 !, - および + が演算子として使えます。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_TLS13_CIPHERS TLS 1.3 接続をプロキシと確立するために使う暗号スイートの一覧。 この一覧はひとつ以上の暗号スイートの文字列がコロンで区切られており、 構文的に正しくなければなりません。 現状、このオプションはcurlが OpenSSL 1.1.1 以降とビルドされた時にだけ使われています。 OpenSSL 以外のSSLバックエンドを使っている場合は、 CURLOPT_PROXY_SSL_CIPHER_LIST オプションを使って TLS 1.3 の暗号スイートを設定できます。 PHP 7.3.0 以降 および cURL >= 7.61.0 と OpenSSL >= 1.1.1 をビルドした場合に使用可能です。
CURLOPT_PROXY_SSLKEY HTTPSプロキシに接続するのに使う秘密鍵のファイル名。 デフォルトのフォーマットは "PEM" で、 そのフォーマットは CURLOPT_PROXY_SSLKEYTYPE で変更できます。 (iOS と Mac OS X のみ) Secure Transport を使って curl がビルドされている場合、 このオプションは無視されます。 PHP 7.3.0 以降 および cURL >= 7.61.0 をビルドした場合、 かつ TLS が有効な場合にのみ使用可能です。
CURLOPT_PROXY_SSLKEYTYPE 秘密鍵のフォーマット。"PEM", "DER" および "ENG" がサポートされています。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_TLSAUTH_PASSWORD CURLOPT_PROXY_TLSAUTH_TYPE オプションで指定したTLS認証メソッド で使うパスワード。 CURLOPT_PROXY_TLSAUTH_USERNAME オプションも設定する必要があります。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_TLSAUTH_TYPE HTTPS接続で使うTLS認証メソッド。 "SRP" がサポートされています。

注意:

TLS の Secure Remote Password (SRP) 認証は、 ローカルとリモートの双方が共通のシークレットを持っている場合に、 お互いを認証する方法を提供します。 TLS-SRP を使うためには、 CURLOPT_PROXY_TLSAUTH_USERNAMECURLOPT_PROXY_TLSAUTH_PASSWORD オプションも設定する必要があります。

PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXY_TLSAUTH_USERNAME CURLOPT_PROXY_TLSAUTH_TYPE オプションで指定された HTTPSプロキシのTLS認証メソッドで使うユーザー名。 CURLOPT_PROXY_TLSAUTH_PASSWORD オプションも設定する必要があります。 PHP 7.3.0 以降 および cURL >= 7.52.0 をビルドした場合に使用可能です。
CURLOPT_PROXYUSERPWD プロキシに接続するためのユーザー名とパスワード。 "[username]:[password]" 形式で指定します。
CURLOPT_RANDOM_FILE 使用するファイル名を、SSL の乱数生成器を使用して作成します。
CURLOPT_RANGE 取得するデータの範囲を "X-Y" 形式で指定します。X あるいは Y は省略可能です。 HTTP 転送では、いくつかの範囲をカンマで区切った "X-Y,N-M" のような形式もサポートしています。
CURLOPT_REFERER HTTP リクエストで使用される "Referer: " ヘッダの内容。
CURLOPT_SASL_AUTHZID 通信に用いる authorization identity (authzid) を指定します。 PLAIN SASL 認証メカニズムの場合にのみ適用できますが、これはオプションです。 指定されない場合は、 ユーザー名のみを指定した authentication identity(authcid) のみを、パスワードと一緒にサーバーに送信します。 サーバーは authzid が指定されない場合、authcid から authzid を導出し、内部的に用います。
CURLOPT_SERVICE_NAME 認証サービス名 cURL 7.43.0 で追加されました。PHP 7.0.7 以降で利用可能です。
CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 32 桁の十六進文字列。この文字列は、リモートホストの公開鍵の MD5 チェックサムでなければなりません。 md5sum がマッチしない限り、libcurl はホストとの接続を拒否します。 このオプションは、SCP および SFTP でのみ有効です。 cURL 7.17.1 で追加されました。
CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 リモートホストの公開鍵を、Base64 エンコードされた SHA256 ハッシュ形式で指定します。 指定されたハッシュがリモートホストが提供するそれと一致しない場合、 通信は失敗します。
CURLOPT_SSH_PUBLIC_KEYFILE 公開鍵のファイル名。指定しなかった場合、libcurl はデフォルトの場所を探します。デフォルトは、 環境変数 HOME が設定されていれば $HOME/.ssh/id_dsa.pub、設定されていなければ カレントディレクトリの "id_dsa.pub" です。 cURL 7.16.1 で追加されました。
CURLOPT_SSH_PRIVATE_KEYFILE 秘密鍵のファイル名。指定しなかった場合、libcurl はデフォルトの場所を探します。デフォルトは、 環境変数 HOME が設定されていれば $HOME/.ssh/id_dsa、設定されていなければ カレントディレクトリの "id_dsa" です。 ファイルがパスワードで保護されている場合は、パスワードを CURLOPT_KEYPASSWD に設定します。 cURL 7.16.1 で追加されました。
CURLOPT_SSL_CIPHER_LIST SSL で使用する暗号のリスト。例えば RC4-SHA および TLSv1 が 使用可能です。
CURLOPT_SSL_EC_CURVES 楕円曲線暗号のアルゴリズムの一覧を、コロンで区切って指定します。 たとえば、X25519:P-521 は、 有効な楕円曲線暗号の一覧です。 このオプションは、 cURL のSSLバックエンドがそのサポートを用いるようにビルドされている場合に、 SSL ハンドシェイクで使われるクライアントの鍵交換アルゴリズムを定義します。
CURLOPT_SSLCERT PEM フォーマットの証明書を含むファイルの名前。
CURLOPT_SSLCERTPASSWD CURLOPT_SSLCERT 証明書を使用する際に必要なパスワード。
CURLOPT_SSLCERTTYPE 証明書の形式。サポートされるフォーマットは "PEM"(デフォルト)、"DER" および "ENG" です。 OpenSSL 0.9.3 以降では、 "P12" (PKCS#12 でエンコードされたファイル) もサポートしています。 cURL 7.9.3 で追加されました。
CURLOPT_SSLENGINE CURLOPT_SSLKEY で指定した SSL 秘密鍵の 暗号化エンジンの ID 。
CURLOPT_SSLENGINE_DEFAULT 非対称暗号化で使用する暗号化エンジンの ID 。
CURLOPT_SSLKEY SSL 秘密鍵を含むファイルの名前。
CURLOPT_SSLKEYPASSWD CURLOPT_SSLKEY で指定した SSL 秘密鍵を 使用するために必要なパスワード。

注意:

このオプションには重要なパスワードが含まれます。PHP スクリプトを 安全な状態におくことを忘れないでください。

CURLOPT_SSLKEYTYPE CURLOPT_SSLKEY で指定した SSL 秘密鍵の 形式。サポートされる型は以下のとおりです。 "PEM"(デフォルト)、"DER" および "ENG"
CURLOPT_TLS13_CIPHERS TLS 1.3 接続を確立するために使う暗号スイートの一覧。 この一覧はひとつ以上の暗号スイートの文字列がコロンで区切られており、 構文的に正しくなければなりません。 このオプションは現状、OpenSSL 1.1.1 以降でcurlがビルドされている場合にだけ使われています。 他のSSLバックエンドを使っている場合、 CURLOPT_SSL_CIPHER_LIST を使うと TLS 1.3 の暗号スイートを設定できます。 PHP 7.3.0 以降 および cURL >= 7.61.0 と OpenSSL >= 1.1.1 をビルドした場合に使用可能です。
CURLOPT_UNIX_SOCKET_PATH 接続のエンドポイントとして Unixドメインソケットの利用を有効にし、 ドメインソケットのパスを与えられた string として設定します。 cURL 7.40.0 で追加されました。 PHP 7.0.7 以降で利用可能です。
CURLOPT_URL 取得する URL 。curl_init() でセッションを 初期化する際に指定することも可能です。
CURLOPT_USERAGENT HTTP リクエストで使用される "User-Agent: " ヘッダの内容。
CURLOPT_USERNAME 認証に使うユーザー名 cURL 7.19.1 で追加されました。
CURLOPT_PASSWORD 認証に使うパスワード cURL 7.19.1 で追加されました。
CURLOPT_USERPWD 接続に使用するユーザー名とパスワード。 "[username]:[password]" 形式で指定します。
CURLOPT_XOAUTH2_BEARER OAuth 2.0 のアクセストークンを指定します。 cURL 7.33.0 で追加されました。PHP 7.0.7 以降で利用可能です。

value には、 option の以下の値に関して 配列を指定する必要があります。

オプション value への設定値 注記
CURLOPT_CONNECT_TO URL で指定されたホストとポートのかわりに接続する、 特定のホストとポート。 HOST:PORT:CONNECT-TO-HOST:CONNECT-TO-PORT というフォーマット文字列の配列を受け入れます。 cURL 7.49.0 で追加されました。 PHP 7.0.7 以降で利用可能です。
CURLOPT_HTTP200ALIASES エラーではなく正常な応答として扱われる、HTTP 200 レスポンスの配列。 cURL 7.10.3 で追加されました。
CURLOPT_HTTPHEADER 設定する HTTP ヘッダフィールドの配列。 array('Content-type: text/plain', 'Content-length: 100') 形式。
CURLOPT_POSTQUOTE FTP リクエストの実行後に、サーバー上で実行する FTP コマンドの配列。
CURLOPT_PROXYHEADER プロキシに渡すカスタムHTTPヘッダの配列 cURL 7.37.0 で追加されました。 PHP 7.0.7 以降で利用可能です。
CURLOPT_QUOTE FTP リクエストの前にサーバー上で実行する FTP コマンドの配列。
CURLOPT_RESOLVE 特定のホストとポートのペアのための、カスタムアドレスを指定します。 ホスト名、ポート、そして IP アドレスの文字列の配列です。 それぞれの要素はコロンで区切る必要があります。 以下のようなフォーマットになります: array("example.com:80:127.0.0.1") cURL 7.21.3 で追加されました。

value はストリームリソース(例えば fopen() が作成するもの)であり、以下の option パラメータに設定します。

オプション value に設定する内容
CURLOPT_FILE 転送内容が書き込まれるファイル。デフォルトは STDOUT (ブラウザウィンドウ)。
CURLOPT_INFILE アップロード時に転送内容を読み込むファイル。
CURLOPT_STDERR STDERR の代わりにエラーを出力する場所。
CURLOPT_WRITEHEADER 転送のヘッダ部分が書き込まれるファイル。  

value には、 option の以下の値に関して 有効な関数あるいはクロージャの名前を指定する必要があります。

オプション value への設定値 備考
CURLOPT_HEADERFUNCTION 二つのパラメータをとるコールバック。 最初のパラメータは CURL リソースで、2 番目は書き込む ヘッダデータの文字列です。このコールバック関数を使用するにあたり、 ヘッダデータを書き込む処理を実装するのはあなたの役目となります。 書き込んだデータのバイト数を返します。
CURLOPT_PASSWDFUNCTION 三つのパラメータをとるコールバック。 最初のパラメータは CURL リソースで、2 番目はパスワード プロンプトの文字列、そして 3 番目はパスワードの最大長です。 入力されたパスワードを文字列で返します。 PHP 7.3.0 で削除されました。
CURLOPT_PROGRESSFUNCTION

五つのパラメータをとるコールバック。 最初のパラメータは cURL 利ソールで、2 番目はこの転送でダウンロードしようとしている総バイト数、 3 番目はこれまでにダウンロードしたバイト数、4 番目はこの転送でアップロードしようとしている総バイト数、 そして 5 番目はこれまでにアップロードしたバイト数です。

注意:

このコールバックが呼ばれるのは、CURLOPT_NOPROGRESSfalse の場合だけです。

ゼロ以外の値を返すと、転送を強制終了できます。このとき、この転送にはエラー CURLE_ABORTED_BY_CALLBACK が設定されます。

 
CURLOPT_READFUNCTION 三つのパラメータをとるコールバック。 最初のパラメータは CURL リソースで、2 番目は CURLOPT_INFILE で cURL に渡したストリームリソース、 そして最後が読み込むデータの最大量です。 コールバックは、要求したデータ量以下の長さの文字列を返さなければなりません。 一般的には、渡されたストリームリソースから読み込んだデータを返します。 EOF を伝えるには空文字列を返さなければなりません。  
CURLOPT_WRITEFUNCTION 二つのパラメータをとるコールバック。 最初のパラメータは CURL リソースで、2 番目は書き込む データの文字列です。データの保存には、 このコールバック関数を使わなければなりません。 書き込んだデータの正確なバイト数を返す必要があります。 返さなければ、エラーで転送が異常終了します。  
CURLOPT_XFERINFOFUNCTION 二つのパラメータをとるコールバック。 CURLOPT_PROGRESSFUNCTION と目的は似ていますが、 cURL の観点からはこちらの方がモダンで、好ましいオプションです。 cURL 7.32.0 で追加されました。 PHP 8.2.0 以降で利用可能です。

その他の値

オプション value への設定値
CURLOPT_SHARE curl_share_init() の結果。 この cURL ハンドルに、共有ハンドルからのデータを使わせるようにします。

戻り値

成功した場合に true を、失敗した場合に false を返します。

変更履歴

バージョン 説明
8.0.0 handleCurlHandle クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、resource を期待していました。
7.3.15, 7.4.3 CURLOPT_HTTP09_ALLOWED が追加されました。
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 および CURLOPT_TLS13_CIPHERS が追加されました。
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, CURLSSLOPT_NO_REVOKE が追加されました。

例1 新規に cURL セッションを初期化、ウェブページを取得する

<?php
// 新しい cURL リソースを作成します
$ch = curl_init();

// URL その他のオプションを適切に設定します
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);

// URL の内容を取得し、ブラウザに渡します
curl_exec($ch);

// cURL リソースを閉じ、システムリソースを開放します
curl_close($ch);
?>

注意

注意:

配列を CURLOPT_POSTFIELDS に渡すと、データを multipart/form-data でエンコードします。 一方 URL エンコードされた文字列を渡すと、データを application/x-www-form-urlencoded でエンコードします。

参考

add a note

User Contributed Notes 68 notes

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

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

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

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

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

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

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

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

curl_setopt($curl, CURLOPT_COOKIEFILE, "");

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

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

curl_getinfo($curl, CURLINFO_COOKIELIST);

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

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

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

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

For copying cookies I recommend using curl_share_init.

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

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

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

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

A the absolute minimum for validation I would suggest:

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

Here is the format:

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

char *my_cookie =
"example.com" /* Hostname */
SEP "FALSE" /* Include subdomains */
SEP "/" /* Path */
SEP "FALSE" /* Secure */
SEP "0" /* Expiry in epoch time format. 0 == Session */
SEP "foo" /* Name */
SEP "bar"; /* Value */
up
13
ashw1 - at - no spam - post - dot - cz
16 years ago
In case you wonder how come, that cookies don't work under Windows, I've googled for some answers, and here is the result: Under WIN you need to input absolute path of the cookie file.

This piece of code solves it:

<?php

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

?>
up
32
Steve Kamerman
12 years ago
If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:

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

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

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

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

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

if (
$curl_errno > 0) {
echo
"cURL Error ($curl_errno): $curl_error\n";
} else {
echo
"Data received: $data\n";
}
} else {
// Server
sleep(10);
echo
"Done.";
}
?>
up
14
JScott jscott401 at gmail dot com
13 years ago
Some additional notes for curlopt_writefunction. I struggled with this at first because it really isn't documented very well.

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

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

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

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

}
?>

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

CURL calls your script MULTIPLE times because the data will not always be sent all at once. Were talking internet here so its broken up into packets. You need to take your data and concatenate it all together until it is all written. I was about to pull my damn hair out because I would get broken chunks of XML back from the server and at random lengths. I finally figured out what was going on. Hope this helps
up
3
cmatiasvillanueva at gmail dot com
6 years ago
What is not mentioned in the documentation is that if you want to set a local-port or local-port-range to establish a connection is possible by adding CURLOPT_LOCALPORT and CURLOPT_LOCALPORTRANGE options.

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

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

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

Interface can be also configured using CURLOPT_INTERFACE:

Ex:

curl_setopt($conn, CURLOPT_INTERFACE, "eth1");
up
29
Philippe dot Jausions at 11abacus dot com
17 years ago
Clarification on the callback methods:

- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.

The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.

-Philippe
up
6
mw+php dot net at lw-systems dot de
11 years ago
The description of the use of the CURLOPT_POSTFIELDS option should be emphasize, that using POST with HTTP/1.1 with cURL implies the use of a "Expect: 100-continue" header. Some web servers will not understand the handling of chunked transfer of post data.

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

curl_setopt($ch, CURLOPT_HTTPHEADER,array("Expect:"));
up
37
Ed Cradock
14 years ago
PUT requests are very simple, just make sure to specify a content-length header and set post fields as a string.

Example:

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

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

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

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

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

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

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

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

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

DELETE can be done in exactly the same way.
up
6
Victor Jerlin
14 years ago
Seems like some options not mentioned on this page, but listed on http://curl.haxx.se/libcurl/c/curl_easy_setopt.html is actually supported.

I was happy to see that I could actually use CURLOPT_FTP_CREATE_MISSING_DIRS even from PHP.
up
26
sgamon at yahoo dot com
15 years ago
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content

Not all web servers support this though. Various errors are returned depending on the server. If this happens to you, suppress the "Expect" header with this command:

<?php
curl_setopt
($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>

See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
up
14
dweingart at pobox dot com
20 years ago
If you want to Curl to follow redirects and you would also like Curl to echo back any cookies that are set in the process, use this:

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

'-' means stdout

-dw
up
18
Chris at PureFormSolutions dot com
14 years ago
I've found that setting CURLOPT_HTTPHEADER more than once will clear out any headers you've set previously with CURLOPT_HTTPHEADER.

Consider the following:
<?php
# ...

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

# ... do some other stuff ...

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

# ...
?>

Both the Content-Type and Expect I set will not be in the outgoing headers, but Accept will.
up
15
joelhy
8 years ago
Please notice that CURLINFO_HEADER_OUT and CURLOPT_VERBOSE option does not work together:
"When CURLINFO_HEADER_OUT is set to TRUE than CURLOPT_VERBOSE does not work."(from https://bugs.php.net/bug.php?id=65348).
This took me an hour or two to figure it out.
up
16
luca dot manzo at bbsitalia dot com
18 years ago
If you're getting trouble with cookie handling in curl:

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

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

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

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

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

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

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

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

I hope this can help someone
Luca
up
2
qwertz182
3 years ago
As the "example #2 Uploading file" says it is deprecated as of PHP 5.5.0 but doesn't tell you how it's done right,
here is a really easy example using the CURLFile class:

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

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

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

$response = curl_exec($ch);
?>

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

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

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

)
?>

Since the request is an array (and not a string), curl will automatically encode the data as "multipart/form-data".
Please be aware that if you pass an invalid file path to CURLFile, setting the CURLOPT_POSTFIELDS option will fail.
So if you are using curl_setopt_array for setting the options at once, according to the manual, "If an option could not be successfully set, FALSE is immediately returned, ignoring any future options in the options array.".
So you should make sure that the file exists or set CURLOPT_POSTFIELDS with curl_setopt() and check if it returns false and act accordingly.
up
14
yann dot corno at free dot fr
21 years ago
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:

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

Yann
up
9
anderseta at gmail dot com
13 years ago
If you wish to find the size of the file you are streaming and use it as your header this is how:

<?php

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

print
$string;

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

?>

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

write_function must return the exact number of bytes of the string, so you can return a value with mb_strlen.
up
14
badman
10 years ago
Many hosters use PHP safe_mode or/and open_basedir, so you can't use CURLOPT_FOLLOWLOCATION. If you try, you see message like this:
CURLOPT_FOLLOWLOCATION cannot be activated when safe_mode is enabled or an open_basedir is set in [you script name & path] on line XXX

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

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

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

$ch = curl_init();
if (!empty($curlOptions)) curl_setopt_array($ch, $curlOptions);
if (!empty($curlHeaders)) curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders);
if (!empty($postFields))
{
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
}

if (!empty($newUrl)) curl_setopt($ch, CURLOPT_URL, $newUrl); // redirect needed

$curlResult = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

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

$maxRedirection--;
continue;
}
else // no more redirection
{
$code = 0;
curl_close($ch);
}
}
while($code);
return $curlResult;
}
up
32
jade dot skaggs at gmail dot com
16 years ago
After much struggling, I managed to get a SOAP request requiring HTTP authentication to work. Here's some source that will hopefully be useful to others.

<?php

$credentials
= "username:password";

// Read the XML to send to the Web Service
$request_file = "./SampleRequest.xml";
$fh = fopen($request_file, 'r');
$xml_data = fread($fh, filesize($request_file));
fclose($fh);

$url = "http://www.example.com/services/calculation";
$page = "/services/calculation";
$headers = array(
"POST ".$page." HTTP/1.0",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: \"run\"",
"Content-length: ".strlen($xml_data),
"Authorization: Basic " . base64_encode($credentials)
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $defined_vars['HTTP_USER_AGENT']);

// Apply the XML to our curl call
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

$data = curl_exec($ch);

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

?>
up
8
jancister at gmail dot com
9 years ago
Please note that if you want to handle progress using CURLOPT_PROGRESSFUNCTION option, you need to take into consideration what version of PHP are you using. Since version 5.5.0, compatibility-breaking change was introduced in number/order of the arguments passed to the callback function, and cURL resource is now passed as first argument.

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

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

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

// Handle progress
}
?>
up
21
joeterranova at gmail dot com
13 years ago
It appears that setting CURLOPT_FILE before setting CURLOPT_RETURNTRANSFER doesn't work, presumably because CURLOPT_FILE depends on CURLOPT_RETURNTRANSFER being set.

So do this:

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

not this:

<?php
curl_setopt
($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
?>
up
5
skyogre __at__ yandex __dot__ ru
18 years ago
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.

<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
assert( is_array($data) );
$vars=null;
foreach(
$data as $key=>$value) {
if(
is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
else
$vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
}
return
$vars;
}

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

?>
up
9
fnjordy at gmail dot com
15 years ago
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.

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

Note that CURLOPT_HEADERFUNCTION callbacks are always called.
up
3
juozaspo at gmail dot com
11 years ago
I've created an example that gets the file on url passed to script and outputs it to the browser.

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

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

Source: http://publib.boulder.ibm.com/tividd/td/ITIM/SC32-1493-00/en_US/HTML/im451_config09.htm
up
11
PHP at RHaworth dot net
12 years ago
When CURLOPT_FOLLOWLOCATION and CURLOPT_HEADER are both true and redirect/s have happened then the header returned by curl_exec() will contain all the headers in the redirect chain in the order they were encountered.
up
7
Dustin Hawkins
18 years ago
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...

In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)

You can then use a command simiar to this to translate your apache certificate into one that curl likes.

$ openssl x509 -in server.crt -out outcert.pem -text

Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.

If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.

If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
up
14
saidk at phirebranding dot com
15 years ago
Passing in PHP's $_SESSION into your cURL call:

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

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

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

Enjoy!
up
5
Martin K.
10 years ago
If you only want to enable cookie handling and you don't need to save the cookies for a separate session, just set CURLOPT_COOKIEFILE to an empty string. I was given the advice to use php://memory but that did not seem to have the same effect.

Although this is stated in the documentation I thought it was worth reiterating since it cause me so much trouble.
up
12
Ojas Ojasvi
16 years ago
<?php
/*
* Author: Ojas Ojasvi
* Released: September 25, 2007
* Description: An example of the disguise_curl() function in order to grab contents from a website while remaining fully camouflaged by using a fake user agent and fake headers.
*/

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

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

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

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

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

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

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

Ojas Ojasvi
up
7
Aaron Wells
9 years ago
If you use cURL to fetch user-supplied URLs (for instance, in a web-based RSS aggregator), be aware of the risk of server-side request forgery (SSRF). This is an attack where the user takes advantage of the fact that cURL requests are sent from the web server itself, to reach network locations they wouldn't be able to reach from outside the network.

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

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

So if you're using cURL with user-supplied URLs, at the very least use CURLOPT_PROTOCOLS (which also sets CURLOPT_REDIR_PROTOCOLS), and either disable CURLOPT_FOLLOWLOCATION or use the "SafeCurl" library to safely follow redirects.
up
11
mr at coder dot tv
17 years ago
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE, $cookies);

Good Luck, Yevgen
up
2
eric dot van dot eldik at peercode dot nl
5 years ago
When you get this error using a PUT request: "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104")

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

Instead try:
<?php
curl_setopt
($ch, CURLOPT_CUSTOMREQUEST, "PUT");
?>
up
8
S\
13 years ago
When using CURLOPT_POSTFIELDS with an array as parameter, you have to pay high attention to user input. Unvalidated user input will lead to serious security issues.

<?php

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

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

curl_exec($ch);

?>

Requesting "test.php?bar=@/home/user/test.png" will send "test.png" to example.com.
Make sure you remove the leading "@" from user input.
up
3
clint at fewbar dot com
13 years ago
If you have turned on conditional gets on a curl handle, and then for a subsequent request, you don't have a good setting for CURLOPT_TIMEVALUE , you can disable If-Modified-Since checking with:

<?php

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

?>
up
2
gskluzacek at gmail dot com
13 years ago
FYI... unless you specifically set the user agent, no user agent will be sent in your request as there is no default value like some of the other options.

As others have said, not sending a user agent may cause you to not get the results that you expected, e.g., 0 byte length content, different content, etc.
up
4
rob at infoglobe dot net
16 years ago
Options not included in the above, but that work (Taken from the libcurl.a C documentation)

CURLOPT_FTP_SSL

Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)

CURLFTPSSL_NONE

Don't attempt to use SSL.

CURLFTPSSL_TRY

Try using SSL, proceed as normal otherwise.

CURLFTPSSL_CONTROL

Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.

CURLFTPSSL_ALL

Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
up
5
ohcc at 163 dot com
6 years ago
This is howto upload an existing file to an FTP server with cURL in PHP.

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

<?php
$ch
= curl_init();
$filepath = 'D:\Web\www\wuxiancheng.cn\hello.txt';
$basename = pathInfo($filepath, PATHINFO_BASENAME);
$filesize = fileSize($filepath);
curl_setopt_array(
$ch,
array(
CURLOPT_URL => 'ftp://www.wuxiancheng.cn/text/' . $basename,
CURLOPT_USERPWD => 'USERNAME:PASSWORD',
CURLOPT_PROTOCOLS => CURLPROTO_FTP,
CURLOPT_UPLOAD => true,
CURLOPT_INFILE => $filepath,
CURLOPT_INFILESIZE => $filesize,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
)
);
curl_exec($ch);
$message = curl_errno($ch) === CURLE_OK ? 'success' : 'failure';
echo
$message;
?>
up
7
Pawel Antczak
14 years ago
Hello.
During problems with "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set"
I was looking for solution.
I've found few methods on this page, but none of them was good enough, so I made one.
<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (
$http_code == 301 || $http_code == 302) {
list(
$header) = explode("\r\n\r\n", $data, 2);
$matches = array();
preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
$url = trim(array_pop($matches));
$url_parsed = parse_url($url);
if (isset(
$url_parsed)) {
curl_setopt($ch, CURLOPT_URL, $url);
$redirects++;
return
curl_redirect_exec($ch, $redirects);
}
}
if (
$curlopt_header)
return
$data;
else {
list(,
$body) = explode("\r\n\r\n", $data, 2);
return
$body;
}
}
?>

Main issue in existing functions was lack of information, how many redirects was done.
This one will count it.
First parameter as usual.
Second should be already initialized integer, it will be incremented by number of done redirects.
You can set CURLOPT_HEADER if You need it.
up
3
michaeledwards.com
18 years ago
Problems can occur if you mix CURLOPT_URL with a 'Host:' header in CURLOPT_HEADERS on redirects because cURL will combine the host you explicitly stated in the 'Host:' header with the host from the Location: header of the redirect response.

In short, don't do this:

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

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

$ch = curl_init();

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

Do
this instead:

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

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
?>
up
10
regan dot corey at gmail dot com
11 years ago
I spent a couple of days trying to POST a multi-dimensional array of form fields, including a file upload, to a remote server to update a product. Here are the breakthroughs that FINALLY allowed the script to run as desired.

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

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

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

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

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

This, without the use of http_build_query, solved all of my problems. Now the receiving host outputs both $_POST and $_FILES vars correctly.
up
8
zsalab
13 years ago
Handling redirections with curl if safe_mode or open_basedir is enabled. The function working transparent, no problem with header and returntransfer options. You can handle the max redirection with the optional second argument (the function is set the variable to zero if max redirection exceeded).
Second parameter values:
- maxredirect is null or not set: redirect maximum five time, after raise PHP warning
- maxredirect is greather then zero: no raiser error, but parameter variable set to zero
- maxredirect is less or equal zero: no follow redirections

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

$rch = curl_copy_handle($ch);
curl_setopt($rch, CURLOPT_HEADER, true);
curl_setopt($rch, CURLOPT_NOBODY, true);
curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
do {
curl_setopt($rch, CURLOPT_URL, $newurl);
$header = curl_exec($rch);
if (
curl_errno($rch)) {
$code = 0;
} else {
$code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
if (
$code == 301 || $code == 302) {
preg_match('/Location:(.*?)\n/', $header, $matches);
$newurl = trim(array_pop($matches));
} else {
$code = 0;
}
}
} while (
$code && --$mr);
curl_close($rch);
if (!
$mr) {
if (
$maxredirect === null) {
trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
} else {
$maxredirect = 0;
}
return
false;
}
curl_setopt($ch, CURLOPT_URL, $newurl);
}
}
return
curl_exec($ch);
}
?>
up
9
Adam Monsen
12 years ago
CURLOPT_POST must be left unset if you want the Content-Type header set to "multipart/form-data" (e.g., when CURLOPT_POSTFIELDS is an array). If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to TRUE, Content-Length will be -1 and most sane servers will reject the request. If you set CURLOPT_POSTFIELDS to an array and have CURLOPT_POST set to FALSE, cURL will send a GET request.
up
8
c00lways at gmail dot com
16 years ago
if you would like to send xml request to a server (lets say, making a soap proxy),
you have to set

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

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

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

hope it helps ;)
up
4
scy-phpmanual at scytale dot name
13 years ago
In order to reset CURLOPT_HTTPHEADER, set it to array(). The cURL C API says you should set it to NULL, but that doesn’t work in the PHP wrapper.
up
6
rob
14 years ago
Whats not mentioned in the documentation is that you have to set CURLOPT_COOKIEJAR to a file for the CURL handle to actually use cookies, if it is not set then cookies will not be parsed.
up
4
markandrewslade at gmail dot com
7 years ago
Contrary to the documentation, CURLOPT_STDERR should be set to a handle to the file you want to write to, not the file's location.
up
4
fred at themancan dot com
15 years ago
To find what encoding a given HTTP POST request uses is easy -- passing an array to CURLOPT_POSTFIELDS results in multipart/form-data:

<?php
curl_setopt
(CURLOPT_POSTFIELDS, array('field1' => 'value'));
?>

Passing a URL-encoded string will result in application/x-www-form-urlencoded:

<?php
curl_setopt
(CURLOPT_POSTFIELDS, array('field1=value&field2=value2'));
?>

I ran across this when integrating with both a warehouse system and an email system; neither would accept multipart/form-data, but both happily accepted application/x-www-form-urlencoded.
up
3
ROXORT at TGNOOB dot FR
18 years ago
<?php
/*
Here is a script that is usefull to :
- login to a POST form,
- store a session cookie,
- download a file once logged in.
*/

// INIT CURL
$ch = curl_init();

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

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

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

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

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

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

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

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

// CLOSE CURL
curl_close ($ch);

/*
At this point you can do do whatever you want
with the downloaded file stored in $content :
display it, save it as file, and so on.
*/
?>
up
4
eion at bigfoot dot com
17 years ago
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...

then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5. This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.

Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.

Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use. As it is here, it returns the body of the response and not the header. It also doesn't deal with redirection urls with username and passwords in them.

<?php
function curl_redir_exec($ch)
{
static
$curl_loops = 0;
static
$curl_max_loops = 20;
if (
$curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return
FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
list(
$header, $data) = explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (
$http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
if (!
$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return
$data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!
$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!
$url['host'])
$url['host'] = $last_url['host'];
if (!
$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
curl_setopt($ch, CURLOPT_URL, $new_url);
debug('Redirecting to', $new_url);
return
curl_redir_exec($ch);
} else {
$curl_loops=0;
return
$data;
}
}
?>
up
3
shiplu at programmer dot net
10 years ago
CURLOPT_POST should be set before CURLOPT_POSTFIELDS. Otherwise you might encounter 411 Length required error.

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

But this one works.

<?php
curl_setopt
($ch, CURLOPT_POST, 1);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $postfields);
?>
up
1
Tyranoweb
14 years ago
There is a function to send POST data in page with five parameters :

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

<?php
function curl_data_post($post, $page, $n, $session, $referer)
{
if(!
is_array($post))
{
return
false;
}

$DATA_POST = curl_init();
curl_setopt($DATA_POST, CURLOPT_RETURNTRANSFER, true);
curl_setopt($DATA_POST, CURLOPT_URL, $page);
curl_setopt($DATA_POST, CURLOPT_POST, true);
if(
$n)
{
curl_setopt($DATA_POST, CURLOPT_FOLLOWLOCATION, true);
}
if(
$session)
{
curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
}

if(
$referer)
{
curl_setopt($DATA_POST, CURLOPT_REFERER, $referer);
}

curl_setopt($DATA_POST, CURLOPT_POSTFIELDS, $post);
$data = curl_exec($DATA_POST);
if(
$data == false)
{
echo
'Warning : ' . curl_error($DATA_POST);
curl_close($DATA_POST);
return
false;
}
else
{
curl_close($DATA_POST);
return
$data;
}
}
?>
up
3
ron at ttvavanti dot nl
19 years ago
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
up
1
php at miggy dot org
17 years ago
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:

<?php curl_setopt($ch, CURLOPT_HTTPHEADER, array("Pragma: ")); ?>

else by default Curl puts a "Pragma: no-cache" header in and thus force cache misses for all requests.
up
1
joel at mojamail dot com
6 years ago
In the long documentation, it's easy to miss the fact that CURLOPT_POSTFIELDS will set the Content-Type to "multipart/form-data" (instead of the usual "application/x-www-form-urlencoded") IFF you supply an array (instead of a query string)!

Some servers will return weird errors (like "SSL read: error:00000000:lib(0):func(0):reason(0), errno 104") for the wrong Content-Type, and you may waste many hours of time trying to figure out why!
up
4
ac at an dot y-co dot de
15 years ago
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.

<?php
curl_setopt
($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '2');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_CAINFO, getcwd().'/cert/ca.crt');
curl_setopt($ch, CURLOPT_SSLCERT, getcwd().'/cert/mycert.pem');
curl_setopt($ch, CURLOPT_SSLCERTPASSWD, 'password');
?>

If your original certificate is in .pfx format, you have to convert it to .pem using following commands
# openssl pkcs12 -in mycert.pfx -out mycert.key
# openssl rsa -in mycert.key -out mycert.pem
# openssl x509 -in mycert.key >> mycert.pem
up
3
qeremy [atta] gmail [dotta] com
11 years ago
If you are trying to update something on your server and you need to handle this update operation by PUT;

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

are "useless" without;

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

Example;

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

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

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

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

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

---Keywords--
rest, restfull api, restfull put, curl put, curl customrequest put
up
1
Andrew
14 years ago
I noticed that if you want to get current cookie file after curl_exec() - you need to close current curl handle (like it said in manual), but if you want cookies to be dumped to file after any curl_exec (without curl_close) you can:

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

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

Only this way, if you close $ch_temp - cookies wont be dumped.
up
2
anonymous
11 years ago
This may be not obvious, but if you specify the CURLOPT_POSTFIELDS and don't specify the CURLOPT_POST - it will still send POST, not GET (as you might think - since GET is default).
So the line:

curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

is synonym to:

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

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

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

it will send POST, since CURLOPT_POSTFIELDS is latter.
So if you want GET - make sure you don't have CURLOPT_POSTFIELDS specified somewhere.
up
2
Madcat
10 years ago
If you have a mixture of strings starting with @ (at character) and files in CURLOPT_POSTFIELDS you have a problem (such as posting a tweet with attached media) because curl tries to interpret anything starting with @ as a file.

<?php

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

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

?>

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

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

Original source: http://bit.ly/AntMle
up
1
Salil Kothadia
15 years ago
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:

<?php
$ch
= curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
up
1
Sylvain R
14 years ago
When you are using CURLOPT_FILE to download directly into a file you must close the file handler after the curl_close() otherwise the file will be incomplete and you will not be able to use it until the end of the execution of the php process.

<?php

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

# at this point your file is not complete and corrupted

fclose($fh);

# now you can use your file;

read_file('/tmp/foo');

?>
up
2
julien veneziano
13 years ago
If you need to send deta in a DELETE request, use:

<?php
$request_body
= 'some data';
$ch = curl_init('http://www.example.com');
curl_setopt($ch, CURLOPT_POSTFIELDS, $request_body);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$response = curl_exec($ch);
var_dump($response);
?>
up
1
adrian at foeder dot de
11 years ago
if you want to do a GET request with additional body data it will become tricky not to implicitly change the request to a POST, like many notes below correctly state.
So to do the analogy of command line's

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

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

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

during my experiments, every other "similar" way, like e.g. CURLOPT_HTTPGET, didn't send the additional data or fell into POST.
up
1
alexchexes at gmail dot com
7 months ago
If you want cURL to successfully write cookies to a file specified with CURLOPT_COOKIEJAR, ensure that cURL has the necessary permissions to modify the file if it already exists.

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

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

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

CURLOPT_POSTFIELDS will set CURLOPT_POST to true for you, no need for repeat.
If you really need to set both, then either:
- set CURLOPT_POST *before* CURLOPT_POSTFIELDS
- or don't use array and convert CURLOPT_POSTFIELDS to URL-encoded string, it will not be affected this way (ie. <?php curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($yourArray)); ?> )
up
1
urkle at outoforder dot cc
15 years ago
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call

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