if unserialize() returns FALSE on a serialized PHP object due to an extraneous string (e.g. "1") appended at the end of the object, you need to set the ff cURL option:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt
(PHP 4 >= 4.0.2, PHP 5)
curl_setopt — cURL 転送用オプションを設定する
パラメータ
- ch
-
curl_init() が返す cURL ハンドル。
- option
-
設定したい CURLOPT_XXX オプション。
- value
-
option に設定する値。
value には、 option の以下の値に関して bool 値を指定する必要があります。
オプション value への設定値 注記 CURLOPT_AUTOREFERER TRUE を設定すると、Location: によるリダイレクトを たどる際には自動的に Referer: フィールドをリクエストに 追加します。 PHP 5.1.0 以降で有効です。 CURLOPT_BINARYTRANSFER TRUE を設定すると、CURLOPT_RETURNTRANSFER が使用された場合に出力結果を何も加工せずに返します。 CURLOPT_COOKIESESSION TRUE を設定すると、クッキーの "セッション" を新しく開始します。 以前のセッションで読み込まれていた "セッションクッキー" は無視するよう、 libcurl に指示します。デフォルトでは、それがセッションクッキーであるか どうかにかかわらず libcurl はすべてのクッキーを読み込んで保存します。 セッションクッキーとは、有効期限が指定されておらず "セッション" の間のみ 有効であるクッキーのことです。 PHP 5.1.0 以降で有効です。 CURLOPT_CRLF TRUE を設定すると、転送時に Unix 形式の改行を CRLF 形式に変換します。 CURLOPT_DNS_USE_GLOBAL_CACHE TRUE を設定すると、グローバル DNS キャッシュを利用します。 このオプションはスレッドセーフではありません。また、デフォルトで 有効になっています。 CURLOPT_FAILONERROR TRUE を設定すると、HTTP で 400 以上のコードが返ってきた際に 処理失敗と判断し、何もしません。デフォルトでは、コードの値を無視して ページの内容を取得します。 CURLOPT_FILETIME TRUE を設定すると、ドキュメントの更新日時を取得しようと試みます。 この値を取得するには、curl_getinfo() で CURLINFO_FILETIME オプションを用います。 CURLOPT_FOLLOWLOCATION TRUE を設定すると、サーバが HTTP ヘッダの一部として送ってくる "Location: " ヘッダの内容をたどります (これは再帰的に行われます。CURLOPT_MAXREDIRS が指定されていない限り、送ってくる "Location: " ヘッダの内容をずっとたどり続けることに注意しましょう)。 CURLOPT_FORBID_REUSE TRUE を設定すると、処理が終了した際に明示的に接続を切断します。 接続を再利用しません。 CURLOPT_FRESH_CONNECT TRUE を設定すると、キャッシュされている接続を利用せずに 新しい接続を確立します。 CURLOPT_FTP_USE_EPRT TRUE を設定すると、FTP のダウンロードに EPRT(および LPRT) を利用します。FALSE の場合は EPRT・LPRT を無効にして PORT を利用します。 PHP 5.0.0 で追加されました。 CURLOPT_FTP_USE_EPSV TRUE を設定すると、FTP 転送の際にまず EPSV コマンドの利用を 試みます。失敗した場合は PASV を利用します。FALSE を設定すると、 EPSV を無効にします。 CURLOPT_FTPAPPEND TRUE を設定すると、リモートファイルを上書きせずに追記します。 CURLOPT_FTPASCII CURLOPT_TRANSFERTEXT のエイリアスです。 CURLOPT_FTPLISTONLY TRUE を設定すると、FTP でディレクトリ名のみ表示します。 CURLOPT_HEADER TRUE を設定すると、ヘッダの内容も出力します。 CURLOPT_HTTPGET TRUE を設定すると、HTTP のリクエスト形式を GET に戻します。 GET はデフォルト設定なので、リクエスト形式が変更されている 場合にのみ必要となります。 CURLOPT_HTTPPROXYTUNNEL TRUE を設定すると、指定された HTTP プロキシを利用します。 CURLOPT_MUTE TRUE を設定すると、cURL 関数に関連する出力を完全に抑えます。 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 および PHP 5.0.0 で追加されました。 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_SSL_VERIFYPEER FALSE を設定すると、cURL はサーバ証明書の検証を行いません。 別の証明書を CURLOPT_CAINFO オプションで 指定するか、CURLOPT_CAPATH オプションで 証明ディレクトリを指定します。 CURLOPT_SSL_VERIFYPEER を無効にする場合、 CURLOPT_SSL_VERIFYHOST もまた TRUE あるいは FALSE にする必要があります(デフォルトは 2 です)。 cURL 7.10 以降、デフォルト値は TRUE です。また、 cURL 7.10 以降、デフォルトでインストールされています。 CURLOPT_TRANSFERTEXT TRUE を設定すると、FTP 転送を ASCII モードで行います。 LDAP の場合は、データを HTML ではなくプレーンテキストで取得します。 Windows システムでは STDOUT に対してバイナリモードを設定しないでください。 CURLOPT_UNRESTRICTED_AUTH TRUE を設定すると、(CURLOPT_FOLLOWLOCATION を利用して)場所をたどっていく際にユーザ名とパスワードを送信し続けます。 これは、たとえホスト名が変わっても続けられます。 PHP 5.0.0 で追加されました。 CURLOPT_UPLOAD TRUE を設定すると、アップロードの準備をします。 CURLOPT_VERBOSE TRUE を設定すると、詳細な情報を出力します。情報は STDERR か、または CURLOPT_STDERR で指定したファイルに出力されます。 value には、 option の以下の値に関して 整数値を指定する必要があります。
オプション value への設定値 注記 CURLOPT_BUFFERSIZE 1 回の読み込みに用いるバッファのサイズ。しかしながら、必ず このバッファいっぱいまで読み込まれることを保証するものではありません。 cURL 7.10 および PHP 5.0.0 で追加されました。 CURLOPT_CLOSEPOLICY CURLCLOSEPOLICY_LEAST_RECENTLY_USED あるいは CURLCLOSEPOLICY_OLDEST です。 他にも 3 つの CURLCLOSEPOLICY_ 定数が存在しますが、 cURL はそれらをまだサポートしていません。 CURLOPT_CONNECTTIMEOUT 接続の試行を待ち続ける秒数。0 は永遠に待ち続けることを意味します。 CURLOPT_DNS_CACHE_TIMEOUT DNS エントリをメモリ内に保持し続ける秒数。デフォルトでは 120(2 分)に設定されています。 CURLOPT_FTPSSLAUTH (使用可能な場合の)FTP 認証方法。 CURLFTPAUTH_SSL(まず SSL を試す)、 CURLFTPAUTH_TLS(まず TLS を試す)あるいは CURLFTPAUTH_DEFAULT(cURL が決める)のいずれかです。 cURL 7.12.2 および PHP 5.1.0 で追加されました。 CURLOPT_HTTP_VERSION CURL_HTTP_VERSION_NONE (デフォルト。 使用するバージョンを決めるのは cURL にまかせる)、 CURL_HTTP_VERSION_1_0 (HTTP/1.0 を使用する)、 あるいは CURL_HTTP_VERSION_1_1 (HTTP/1.1 を使用する) のいずれかです。 CURLOPT_HTTPAUTH 使用する HTTP 認証方法。以下の中から選びます。 CURLAUTH_BASIC 、 CURLAUTH_DIGEST 、 CURLAUTH_GSSNEGOTIATE 、 CURLAUTH_NTLM 、 CURLAUTH_ANY および CURLAUTH_ANYSAFE 。
2 つ以上の方法を組み合わせるには、ビット演算子 |(or) を使用します。このような場合、cURL はサーバがサポートしている方法を 問い合わせたうえで最適な方法を選択します。
CURLAUTH_ANY は CURLAUTH_BASIC | CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM のエイリアスです。
CURLAUTH_ANYSAFE は CURLAUTH_DIGEST | CURLAUTH_GSSNEGOTIATE | CURLAUTH_NTLM のエイリアスです。
PHP 5.0.0 で追加されました。 CURLOPT_INFILESIZE ファイルをリモートサイトにアップロードする際のファイルサイズ。 CURLOPT_LOW_SPEED_LIMIT 1 秒あたりのバイト数で、転送速度がこれより遅い期間が CURLOPT_LOW_SPEED_TIME 秒以上続いた場合に PHP は転送を終了します。 CURLOPT_LOW_SPEED_TIME 転送速度が CURLOPT_LOW_SPEED_LIMIT より遅い期間がどれだけ続いた場合に転送を異常終了させるかを、 秒単位で指定します。 CURLOPT_MAXCONNECTS 許可される持続的接続の最大数。もしこの値に達した場合、 どの接続を閉じるのかを CURLOPT_CLOSEPOLICY によって決定します。 CURLOPT_MAXREDIRS HTTP のリダイレクト先を追いかける最大値。 CURLOPT_FOLLOWLOCATION とあわせて使用します。 CURLOPT_PORT 接続先のポート番号。 CURLOPT_PROXYAUTH プロキシ接続に使用する HTTP 認証の方法。 CURLOPT_HTTPAUTH で説明したのと同じオプションを 指定可能です。プロキシ認証でサポートされているのは、今のところ CURLAUTH_BASIC および CURLAUTH_NTLM のみです。 cURL 7.10.7 および PHP 5.1.0 で追加されました。 CURLOPT_PROXYPORT プロキシ接続のポート番号。このポート番号は、 CURLOPT_PROXY で指定することも可能です。 PHP 5.0.0 で追加されました。 CURLOPT_PROXYTYPE CURLPROXY_HTTP (デフォルト)あるいは CURLPROXY_SOCKS5 。 cURL 7.10 および PHP 5.0.0 で追加されました。 CURLOPT_RESUME_FROM 転送を途中から再開する場合のバイトオフセット。 CURLOPT_SSL_VERIFYHOST 1 は SSL ピア証明書に一般名が存在するかどうかを調べます。 2 はそれに加え、その名前がホスト名と一致することを検証します。 CURLOPT_SSLVERSION 使用する SSL のバージョン(2 あるいは 3)。デフォルトでは PHP が自動的に判断しますが、これを手動で設定する必要がある場合もあります。 CURLOPT_TIMECONDITION CURLOPT_TIMEVALUE の扱いを決定します。 CURLOPT_TIMEVALUE で指定した時刻以降に 変更されたページのみを返す場合は CURL_TIMECOND_IFMODSINCE を使用します。 CURLOPT_HEADER が TRUE だと仮定すると、 ページが変更されていない場合は "304 Not Modified" ヘッダが返されます。 CURL_TIMECOND_IFUNMODSINCE は反対の意味です。 デフォルトは CURL_TIMECOND_IFMODSINCE です。 PHP 5.1.0 で追加されました。 CURLOPT_TIMEOUT cURL 関数の実行にかけられる時間の最大値。 CURLOPT_TIMEVALUE 1970 年 1 月 1 日からの経過秒数。この値は CURLOPT_TIMECONDITION で使用されます。デフォルトでは CURL_TIMECOND_IFMODSINCE が設定されます。 value は、 option パラメータの 以下の値に関して文字列である必要があります。
オプション value への設定値 注記 CURLOPT_CAINFO 接続先を検証するための証明書を保持するファイル名。 これは CURLOPT_SSL_VERIFYPEER を使用する場合に のみ意味を持ちます。 CURLOPT_CAPATH 複数の証明書ファイルを保持するディレクトリ。このオプションは CURLOPT_SSL_VERIFYPEER とともに使用します。 CURLOPT_COOKIE HTTP リクエストにおける "Set-Cookie: " ヘッダの内容。 CURLOPT_COOKIEFILE クッキーのデータを保持するファイルの名前。クッキーファイルは、 Netscape フォーマットあるいは HTTP ヘッダを単純にファイルにダンプしたものが使用可能です。 CURLOPT_COOKIEJAR 接続を閉じる際に、すべての内部クッキーを保存するファイルの名前。 CURLOPT_CUSTOMREQUEST HTTP リクエストで "GET" あるいは "HEAD" 以外に 使用するカスタムメソッド。これが有用なのは、"DELETE" やその他のあまり知られていない HTTP リクエストを実行する場合です。 使用可能な値は "GET"、 "POST"、"CONNECT" などです。 HTTP リクエストの内容をすべて指定するわけではありません。つまり、 "GET /index.html HTTP/1.0\r\n\r\n" のような 記述は間違いだということです。 注意: 使用しようとしているメソッドをサーバがサポートしていることを 確かめるまで、これを使用しないでください。
CURLOPT_EGDSOCKET CURLOPT_RANDOM_FILE と似ていますが、 Entropy Gathering Daemon ソケットを使用してファイル名を生成する点が 違います。 CURLOPT_ENCODING "Accept-Encoding: " ヘッダの内容。 これにより、応答のデコードを可能にします。サポートされる エンコーディングは "identity"、 "deflate" および "gzip" です。もし空文字列 "" が指定された場合、 サポートされるエンコーディングをすべて含むヘッダが送信されます。 cURL 7.10 で追加されました。 CURLOPT_FTPPORT FTP で "POST" を使用するための IP アドレスを取得する際に使用される値。 "POST" は、リモートサーバに対してこちらが指定した IP アドレスに 接続するよう指示します。この値に設定できる内容は IP アドレス、ホスト名、 ネットワークインターフェース名(Unix)、あるいは単に '-' を指定する ことでシステムのデフォルト IP アドレスを指定します。 CURLOPT_INTERFACE 使用するネットワークインターフェースの名前。 インターフェース名、IP アドレスあるいはホスト名が指定可能です。 CURLOPT_KRB4LEVEL KRB4(Kerberos 4)セキュリティレベル。以下の値のいずれか (セキュリティの低い順です)が指定可能です。 "clear"、 "safe"、 "confidential"、 "private"。 文字列がこれらのどれでもなかった場合は、 "private" が使用されます。このオプションを NULL にすると KRB4 セキュリティを無効にします。現時点では、KRB4 セキュリティは FTP 転送にのみ使用可能です。 CURLOPT_POSTFIELDS HTTP "POST" で送信するすべてのデータ。 ファイルを送信するには、ファイル名の先頭に @ をつけてフルパスを指定します。これは、 'para1=val1¶2=val2&...' のように url エンコードされた文字列形式で渡すこともできますし、 フィールド名をキー、データを値とする配列で渡すこともできます。 CURLOPT_PROXY リクエストを経由させる HTTP プロキシ。 CURLOPT_PROXYUSERPWD プロキシに接続するためのユーザ名とパスワード。 "[username]:[password]" 形式で指定します。 CURLOPT_RANDOM_FILE 使用するファイル名を、SSL の乱数生成器を使用して作成します。 CURLOPT_RANGE 取得するデータの範囲を "X-Y" 形式で指定します。X あるいは Y は省略可能です。 HTTP 転送では、いくつかの範囲をカンマで区切った "X-Y,N-M" のような形式もサポートしています。 CURLOPT_REFERER HTTP リクエストで使用される "Referer: " ヘッダの内容。 CURLOPT_SSL_CIPHER_LIST SSL で使用する暗号のリスト。例えば RC4-SHA および TLSv1 が 使用可能です。 CURLOPT_SSLCERT PEM フォーマットの証明書を含むファイルの名前。 CURLOPT_SSLCERTPASSWD CURLOPT_SSLCERT 証明書を使用する際に必要なパスワード。 CURLOPT_SSLCERTTYPE 証明書の形式。サポートされるフォーマットは "PEM"(デフォルト)、"DER" および "ENG" です。 cURL 7.9.3 および PHP 5.0.0 で追加されました。 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_URL 取得する URL 。curl_init() でセッションを 初期化する際に指定することも可能です。 CURLOPT_USERAGENT HTTP リクエストで使用される "User-Agent: " ヘッダの内容。 CURLOPT_USERPWD 接続に使用するユーザ名とパスワード。 "[username]:[password]" 形式で指定します。 value には、 option の以下の値に関して 配列を指定する必要があります。
オプション value への設定値 注記 CURLOPT_HTTP200ALIASES エラーではなく正常な応答として扱われる、HTTP 200 レスポンスの配列。 cURL 7.10.3 および PHP 5.0.0 で追加されました。 CURLOPT_HTTPHEADER 設定する HTTP ヘッダフィールドの配列。 CURLOPT_POSTQUOTE FTP リクエストの実行後に、サーバ上で実行する FTP コマンドの配列。 CURLOPT_QUOTE FTP リクエストの前にサーバ上で実行する FTP コマンドの配列。 value はストリームリソース(例えば fopen() が作成するもの)であり、以下の option パラメータに設定します。
オプション value に設定する内容 注釈 CURLOPT_FILE 転送内容が書き込まれるファイル。デフォルトは STDOUT (ブラウザウィンドウ)。 CURLOPT_INFILE アップロード時に転送内容を読み込むファイル。 CURLOPT_STDERR STDERR の代わりにエラーを出力する場所。 CURLOPT_WRITEHEADER 転送のヘッダ部分が書き込まれるファイル。 value には、 option の以下の値に関して 有効なコールバック関数の名前を指定する必要があります。
オプション value への設定値 注記 CURLOPT_HEADERFUNCTION コールバック関数の名前で、このコールバック関数は 2 つの引数を とります。最初のパラメータは CURL リソースで、2 番目は書き込む ヘッダデータの文字列です。このコールバック関数を使用するにあたり、 ヘッダデータを書き込む処理を実装するのはあなたの役目となります。 書き込んだデータのバイト数を返します。 CURLOPT_PASSWDFUNCTION コールバック関数の名前で、このコールバック関数は 3 つの引数を とります。最初のパラメータは CURL リソースで、2 番目はパスワード プロンプトの文字列、そして 3 番目はパスワードの最大長です。 入力されたパスワードを文字列で返します。 CURLOPT_READFUNCTION コールバック関数の名前で、このコールバック関数は 2 つの引数を とります。最初のパラメータは cURL リソースで、2 番目は読み込む データの文字列です。このコールバック関数を使用するにあたり、 データを読み込む処理を実装するのはあなたの役目となります。 読み込んだデータのバイト数を返します。EOF シグナルを受け取った場合は 0 を返します。 CURLOPT_WRITEFUNCTION コールバック関数の名前で、このコールバック関数は 2 つの引数を とります。最初のパラメータは cURL リソースで、2 番目は書き込む データの文字列です。このコールバック関数を使用するにあたり、 データを書き込む処理を実装するのはあなたの役目となります。 書き込んだデータの正確なバイト数を返す必要があり、さもないと この関数は失敗します。
返り値
成功した場合に TRUE を、失敗した場合に FALSE を返します。
例
例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);
?>
例2 ファイルのアップロード
<?php
/* http://localhost/upload.php:
print_r($_POST);
print_r($_FILES);
*/
$ch = curl_init();
$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_exec($ch);
?>
上の例の出力は以下となります。
Array
(
[name] => Foo
)
Array
(
[file] => Array
(
[name] => test.png
[type] => image/png
[tmp_name] => /tmp/phpcpjNeQ
[error] => 0
[size] => 279
)
)
curl_setopt
02-Feb-2009 04:36
28-Jan-2009 04:49
To send a post as a different content-type (ie.. application/json or text/xml) add this setopt call
curl_setopt($ch, CURLOPT_HTTPHEADERS,array('Content-Type: application/json"));
01-Dec-2008 09:48
There is no CURLOPT_MAXFILESIZE in the PHP module but it's function only works with Content-Length headers anyway. There are two ways of checking download sizes, one is after the download is complete using filesize(), the other is as the download is running allowing you to terminate before wasting time and disk space.
<?php
$GLOBALS['file_size'] = 0;
$GLOBALS['max_file_size'] = 1024 * 1024;
function on_curl_header($ch, $header)
{
$trimmed = rtrim($header);
if (preg_match('/^Content-Length: (\d+)$/', $trimmed, $matches))
{
$file_size = $matches[1];
if ($file_size > $GLOBALS['max_file_size']) {
// handle error here.
}
}
return strlen($header);
}
function on_curl_write($ch, $data)
{
$bytes = strlen($data);
$GLOBALS['file_size'] += $bytes;
if ($GLOBALS['file_size'] > $GLOBALS['max_file_size']) {
// handle error here.
}
return $bytes;
}
$ch = curl_init();
$options = array(CURLOPT_URL => 'http://www.php.net/',
CURLOPT_HEADER => false,
CURLOPT_HEADERFUNCTION => 'on_curl_header',
CURLOPT_WRITEFUNCTION => 'on_curl_write');
curl_setopt_array($ch, $options);
curl_exec($ch);
// ...
?>
01-Dec-2008 09:28
Note that CURLOPT_RETURNTRANSFER when used with CURLOPT_WRITEFUNCTION has effectively three settings: default, true, and false.
default - callbacks will be called as expected.
true - content will be returned but callback function will not be called.
false - content will be output and callback function will not be called.
Note that CURLOPT_HEADERFUNCTION callbacks are always called.
19-Nov-2008 11:31
Passing in PHP's $_SESSION into your cURL call:
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!
11-Oct-2008 12:20
This may not be a surprise for many, but I know I bled my eyes out trying to implement this in php. And when I knew it was this simple, I really felt extremely stupid. So I put this just so google will save somebody some time in the future.
PHP NTLM AUTH
Make sure you have the 'curl' extension loaded
now just do...
curl_setopt($ch,CURLAUTH_NTLM);
curl_setopt($ch,CURLOPT_USERPWD,"$username:$password");
and just continue to use curl in the ordinary fashion.
26-Sep-2008 04:10
In response to rkirilow's post, where he said to set the option CURLOPT_FILE, that should really be CURLOPT_COOKIEFILE. I was bitten by this issue myself with code that previously worked for logging into a website and posting a form. However, at some point the code just stopped working, and I eventually found that I needed to set this option to /dev/null for it to work.
26-Sep-2008 10:37
To fetch (or submit data to) multiple pages during one session,use this:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_COOKIESESSION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookiefile");
curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_URL, 'http://site.com/page1.php');
$result1 = curl_exec($ch);
curl_setopt($ch, CURLOPT_URL, 'http://site.com/page2.php');
$result2 = curl_exec($ch);
curl_close($ch);
?>
16-Sep-2008 11:34
Some of you may noticed that curl is not transferring cookies between sequent calls to a host. This is because you must activate curl`s "cookie parser". That is achieved using an external file like this:
<?php
curl_setopt(CURLOPT_FILE, '/tmp/cookies_file');
?>
If you don`t need to read any cookies but you still want the "cookie parser" use the same code but with dummy file with no data like '/dev/null', that way curl is storing cookies internaly per curl_handle:
<?php
curl_setopt(CURLOPT_FILE, '/dev/null');
?>
07-Sep-2008 12:51
Like eion said before (http://br.php.net/manual/ro/function.curl-setopt.php#71313), the function CURLOPT_FOLLOWLOCATION don't will work when OPEN_BASEDIR is ON (or SAFE_MODE is ON).
he created a CURLOPT_FOLLOWLOCATION function alternative named: curl_redir_exec()
Well, this function have a little error on line that contains:
list($header, $data) = explode("\n\n", $data, 2);
do you have replace for:
list($header, $data) = explode("\r\n", $data, 2);
note the '\n\n' cause this error, so just replace for '\r\n'.
Thanks Eion for your curl_redir_exec() Function :)
23-Aug-2008 03:14
If you set CURLOPT_RESUME_FROM to resume the file, and then reuse the same Curl handle to download another file, you must reset the resume status by calling curl_setopt( $ch, CURLOPT_RESUME_FROM, 0 ). It will not reset, and will apply to all subsequent transfers even if the URL is the same.
12-Aug-2008 08:12
Just a small detail I too easily overlooked.
<?php
/* If you set: */
curl_setopt ($ch, CURLOPT_POST, 1);
/* then you must have the data: */
curl_setopt ($ch, CURLOPT_POSTFIELDS, $PostData);
?>
I found with only the CURLOPT_POST set (from copy, paste editing of course) cookies were not getting sent with CURLOPT_COOKIE. Just something subtle to watch out for.
06-Aug-2008 02:28
What encoding will a given HTTP POST request use?
The answer 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.
05-Aug-2008 02:56
if you use
<?php
curl_setopt($ch, CURLOPT_INTERFACE, "XXX.XXX.XXX.XXX");
?>
to specify IP adress for request, sometimes you need to get list of all your IP's.
ifconfig command will output something like:
rl0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=8<VLAN_MTU>
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 82.146.XXX.XXX netmask 0xffffffff broadcast 82.146.XXX.XXX
inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
inet 78.24.XXX.XXX netmask 0xffffffff broadcast 78.24.XXX.XXX
ether XX:XX:XX:XX:XX:XX
media: Ethernet autoselect (100baseTX <full-duplex>)
status: active
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
tun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
Opened by PID 564
tun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1500
Opened by PID 565
Opened by PID 565
My solution for FreeBSD 6 and PHP 5 was:
<?php
ob_start();
$ips=array();
$ifconfig=system("ifconfig");
echo $ifconfig;
$ifconfig=ob_get_contents();
ob_end_clean();
$ifconfig=explode(chr(10), $ifconfig);
for ($i=0; $i<count($ifconfig); $i++) {
$t=explode(" ", $ifconfig[$i]);
if ($t[0]=="\tinet") {
array_push($ips, $t[1]);
}
}
for ($i=0; $i<count($ips); $i++) {
echo $ips[$i]."\n";
}
?>
You will get list of IP adresses in $ips array, like:
82.146.XXX.XXX
78.24.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
82.146.XXX.XXX
78.24.XXX.XXX
78.24.XXX.XXX
01-Aug-2008 11:03
Be careful when following Salil Kothadia's suggestion of using http_build_query with CURLOPT_POSTFIELDS.
As pinkgothic at gmail dot com explains on the http_build_query page: "Be careful if you're assuming that arg_separator defaults to '&'." For example, XAMPP changes the default in PHP.ini to '& amp' which may cause hours of frustration when trying to resolve failed form submissions.
10-Jul-2008 08:08
If you want to connect to a server which requires that you identify yourself with a certificate, use following code. Your certificate and servers certificate are signed by an authority whose certificate is in ca.ctr.
<?php
curl_setopt($ch, CURLOPT_VERBOSE, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '1');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '1');
curl_setopt($ch, CURLOPT_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
07-Jul-2008 07:18
Although CURLOPT_CLOSEPOLICY and the applicable choices are valid constants, setting this option with curl_setopt() always returns false. A quick google search suggests the option is deprecated and/or never worked.
20-Jun-2008 12:19
Someone posted this under tmpfile (http://us3.php.net/manual/en/function.tmpfile.php#69419), and I thought it was particularly useful:
By the way, this function is really useful for libcurl's CURLOPT_PUT feature if what you're trying to PUT is a string. For example:
/* Create a cURL handle. */
$ch = curl_init();
/* Prepare the data for HTTP PUT. */
$putString = "Hello, world!";
$putData = tmpfile();
fwrite($putData, $putString);
fseek($putData, 0);
/* Set cURL options. */
curl_setopt($ch, CURLOPT_URL, "http://www.example.com");
curl_setopt($ch, CURLOPT_PUT, true);
curl_setopt($ch, CURLOPT_INFILE, $putData);
curl_setopt($ch, CURLOPT_INFILESIZE, strlen($putString));
/* ... (other curl options) ... */
/* Execute the PUT and clean up */
$result = curl_exec($ch);
fclose($putData);
curl_close($ch);
19-Jun-2008 07:02
In PHP5, for the "CURLOPT_POSTFIELDS" option, we can use:
<?php
$ch = curl_init($URI);
$Post = http_build_query($PostData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $Post);
$Output = curl_exec($ch);
curl_close($ch);
?>
09-Jun-2008 02:07
Be careful setting options while reusing a curl handle. I do not believe curl_exec resets the previous options e.g. the referrer and headers you set two requests ago may remain for the latest request.
I have not fully tested this and am interested in your results.
13-May-2008 10:17
Please note that the below is not entirely correct. This format will work partially, but does not always produce correct headers. The correct form for the same code is:
<?php
$str = array(
"Accept-Language: en-us,en;q=0.5",
"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300",
"Connection: keep-alive"
);
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, $str);
?>
The appropriate newlines/cr's *should* be handled by curl.
This realization has cost me many hours, because Host, User-Agent, Cache-Control, etc appear to be handled correctly with the string form, but Content-Length and Content-Type are duplicated and the second copy is not parsed correctly by the server!
07-May-2008 04:26
I just spent the last 45 minutes banging my head against my keyboard because when using libcurl for a lighttpd server I would get a 400 Bad Request Error.
It turns out, that despite what has been mentioned in other comments, when using the CURLOPT_HTTPHEADER option, you must use \r\n as newline separators for each header NOT \n. For some reason lighttpd will not accept them. Other webservers will however.
Example:
<?php
$str = "Accept-Language: en-us,en;q=0.5\r\n";
$str .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
$str .= "Keep-Alive: 300\r\n";
$str .= "Connection: keep-alive\r\n";
curl_setopt($this->curl_handle, CURLOPT_HTTPHEADER, array($str));
?>
30-Apr-2008 12:31
OMG! I've joust found kinda bug:
YES, you can set an IP for curl to use by using this statement: curl_setopt($curl, CURLOPT_INTERFACE, $ip);
NO, you CAN NOT set another IP for the same curl object. I mean if u do curl_setopt($curl, CURLOPT_INTERFACE, $ip2); - it wont work!
So to change an IP you need to re-create curl object (curl_close, then curl_init).
10-Apr-2008 03:55
If you are doing a POST, and the content length is 1,025 or greater, then curl exploits a feature of http 1.1: 100 (Continue) Status.
See http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3
* it adds a header, "Expect: 100-continue".
* it then sends the request head, waits for a 100 response code, then sends the content
Not all web servers support this though. Various errors are returned depending on the server. If this happens to you, suppress the "Expect" header with this command:
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
?>
See http://www.gnegg.ch/2007/02/the-return-of-except-100-continue/
04-Apr-2008 07:22
Clarification for the CURLOPT_NOBODY option: by excluding the body from your request, you're effectively making a HEAD request. Use the CURLOPT_NOBODY option to return only the headers in the remote response.
Example:
function check_url($url) {
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_HEADER, 1); // get the header
curl_setopt($c, CURLOPT_NOBODY, 1); // and *only* get the header
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); // get the response as a string from curl_exec(), rather than echoing it
curl_setopt($c, CURLOPT_FRESH_CONNECT, 1); // don't use a cached version of the url
if (!curl_exec($c)) { return false; }
$httpcode = curl_getinfo($c, CURLINFO_HTTP_CODE);
return ($httpcode < 400);
}
16-Feb-2008 08:26
If you try to upload file to a server, you need do CURLOPT_POST first and then fill CURLOPT_POSTFIELDS.
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
^^ This will post multipart/form-data
Next example don't work:
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_POST, 1);
Sets to content-lenght:0 if $postvars an array.
29-Dec-2007 07:13
Despite the documentation for CURLOPT_HTTPHEADER, all header fields MUST be in one string, with a eol indicator, inside a single element array, in my experience.
For example, this will fail.
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50"));
?>
This will work.
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n"));
?>
This will only set the first header
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\n","Otherheader: stuff\n"));
?>
This however, will set both headers as we want.
<?php
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Range: Bytes=0-50\nOtherheader: stuff\n"));
?>
12-Dec-2007 10:34
hey hey hey!
the problem: curl_setopt($ch,FOLLOW_LOCATION,1);
the error: trouble with open_basedir and safe_mode
the solution: a function already developed by someone
the solution n 2: the same function, modifed, works great for me..
function curl_redir_exec($ch,$debug="")
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$debbbb = $data;
list($header, $data) = explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
//print_r($url);
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
/* if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];*/
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
curl_setopt($ch, CURLOPT_URL, $new_url);
// debug('Redirecting to', $new_url);
return curl_redir_exec($ch);
} else {
$curl_loops=0;
return $debbbb;
}
}
just use this function without de FOLLOW_LOCATION and should work. the problem was that when you get to the line where you return the data if http_code was different than 301 oe 302, $data has obsolete information or none. so $debbbb does the job.
hope this helps someone out there
thanks from argentina
21-Aug-2007 12:03
This is very clear in hindsight, but it still cost me several hours:
curl_setopt($session, CURLOPT_HTTPPROXYTUNNEL, 1);
means that you will tunnel THROUGH the proxy, as in "your communications will go as if the proxy is NOT THERE".
Why do you care? - Well, if you are trying to use, say, Paros, to debug HTTP between your cURL and the server, with CURLOPT_HTTPPROXYTUNNEL set to TRUE Paros will not see or log your traffic thus defeating the purpose and driving you nuts.
There are other cases, of course, where this option is extremely useful...
20-Jul-2007 07:07
The explanation of CURLOPT_NOBODY ("TRUE to exclude the body from the output.") seems unclear to me -- I originally read "output" to mean the return value, i.e. the response. In fact it means to exclude the body from your *request*. Not sure whether "output" means the same thing for CURLOPT_HEADER though.
06-Jul-2007 01:09
if you are trying to connect to 'https://...' and after that want to work with POST data - that's the way:
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_COOKIEFILE, "cookiefile");
curl_setopt($curl, CURLOPT_COOKIEJAR, "cookiefile"); # SAME cookiefile
curl_setopt($curl, CURLOPT_URL, "url1"); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
$xxx = curl_exec($curl);
curl_setopt($curl, CURLOPT_URL, "url2"); # this is where you are requesting POST-method form results (working with secure connection using cookies after auth)
curl_setopt($curl, CURLOPT_POSTFIELDS, "var1=value&var2=value&var3=value&"); # form params that'll be used to get form results
$xxx = curl_exec($curl);
curl_close ($curl);
echo $xxx;
27-Jun-2007 09:18
Two things that I noted, one of which has been mentioned earlier, if you are connecting to an SSL site (https) and don't have the appropriate certificate, don't forget to set CURLOPT_SSL_VERIFYPEER as "false"... it's set to "true" by default. Scratched my head over 2 hours to figure this one out as I had a machine with an older version installed and everything worked fine without using this option on that one - but failed on other machines with newer versions.
Second very important thing, I've never had my scripts work (tried on various machines, multiple platforms) with a Relative path to a COOKIEJAR or COOKIEFILE. In my experience I HAVE to specify the absolute path and not the relative path.
Small script I wrote to connect to a page, gather all cookies into a jar, connect to another page to login, taking the cookiejar with you for authentication:
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/start.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
ob_start(); // Prevent output
curl_exec ($ch);
ob_end_clean(); // End preventing output
curl_close ($ch);
unset($ch);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "field1=".$f1."&field2=".$f2."&SomeFlag=True");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/Library/WebServer/Documents/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"https://www.example.com/myaccount/Login.asp");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$result = curl_exec ($ch);
curl_close ($ch);
13-Jun-2007 12:35
If you are getting the following error:
SSL: certificate subject name 'domain-or-ip-1.com' does not match target host name 'domain-or-ip-2.com'
Then you can set the following option to get around it:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
12-Jun-2007 11:55
Please note that the CURLOPT_INTERFACE setting only accepts IP addresses and hostnames of the local machine. It is not meant to send a URL to a specific IP address.
12-May-2007 07:52
curl will sometimes return an "Empty reply from server" error if you don't send a User-Agent string. Use the CURLOPT_USERAGENT option.
24-Apr-2007 07:01
Options not included in the above, but that work (Taken from the libcurl.a C documentation)
CURLOPT_FTP_SSL
Pass a long using one of the values from below, to make libcurl use your desired level of SSL for the ftp transfer. (Added in 7.11.0)
CURLFTPSSL_NONE
Don't attempt to use SSL.
CURLFTPSSL_TRY
Try using SSL, proceed as normal otherwise.
CURLFTPSSL_CONTROL
Require SSL for the control connection or fail with CURLE_FTP_SSL_FAILED.
CURLFTPSSL_ALL
Require SSL for all communication or fail with CURLE_FTP_SSL_FAILED.
14-Mar-2007 02:26
Seems that CURLOPT_RETURNTRANSFER Option set to TRUE, returns a "1" when the transaction returns a blank page.
I think is for eliminate the FALSE to can be with a blank page as return
08-Mar-2007 04:50
How to get rid of response after POST: just add callback function for returned data (CURLOPT_WRITEFUNCTION) and make this function empty.
function curlHeaderCallback($ch, $strHeader) {
}
curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'curlHeaderCallback')
03-Mar-2007 04:36
In response to "brett at brettbrewer dot com" and Jamolkhon, the fact you don't take into account is when a redirection (Location: ...) occurs, all the headers are given so the \r\n\r\n can also separate twp consecutive headers.
An even better trick to get the header is to use CURLINFO_HEADER_SIZE :
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($output, 0, $header_size - 4);
$body = substr($output, $header_size);
Then $headers contains all the headers.
15-Dec-2006 09:11
in response to "brett at brettbrewer dot com":
another useful way of getting headers without using regular expression
<?php
class CCurl {
var $m_handle;
var $m_header;
var $m_body;
function CCurl($sUrl) {
$this->m_handle = curl_init();
curl_setopt($this->m_handle, CURLOPT_URL, $sUrl);
curl_setopt($this->m_handle, CURLOPT_HEADER, 1);
curl_setopt($this->m_handle, CURLOPT_RETURNTRANSFER, 1);
return;
}
function getHeader() {
return $this->m_header;
}
function execute() {
$sResponse = curl_exec($this->m_handle);
$this->m_body = substr($sResponse, strpos($sResponse, "\r\n\r\n") + 4);
$this->m_header = substr($sResponse, 0, -strlen($this->m_body));
return $this->m_body;
}
function close() {
curl_close($this->m_handle);
return;
}
}
?>
(you can add something or make some changes to suit your needs)
22-Nov-2006 06:40
If you are trying to use CURLOPT_FOLLOWLOCATION and you get this warning:
Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set...
then you will want to read http://www.php.net/ChangeLog-4.php which says "Disabled CURLOPT_FOLLOWLOCATION in curl when open_basedir or safe_mode are enabled." as of PHP 4.4.4/5.1.5. This is due to the fact that curl is not part of PHP and doesn't know the values of open_basedir or safe_mode, so you could comprimise your webserver operating in safe_mode by redirecting (using header('Location: ...')) to "file://" urls, which curl would have gladly retrieved.
Until the curl extension is changed in PHP or curl (if it ever will) to deal with "Location:" headers, here is a far from perfect remake of the curl_exec function that I am using.
Since there's no curl_getopt function equivalent, you'll have to tweak the function to make it work for your specific use. As it is here, it returns the body of the response and not the header. It also doesn't deal with redirection urls with username and passwords in them.
<?php
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
list($header, $data) = explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = @parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . ($url['query']?'?'.$url['query']:'');
curl_setopt($ch, CURLOPT_URL, $new_url);
debug('Redirecting to', $new_url);
return curl_redir_exec($ch);
} else {
$curl_loops=0;
return $data;
}
}
?>
09-Nov-2006 09:27
I have seen two posts complaining the "CURLOPT_POSTFIELDS" option is not working well.
This was the solution given below:
$o="";
foreach ($post_data as $k=>$v)
{
$o.= "$k=".utf8_encode($v)."&";
}
$post_data=substr($o,0,-1);
The assumption that this is an error is not true, as stated on http://curl.rtin.bz/docs/httpscripting.html:
" The data you send to the server MUST already be properly encoded, curl will
not do that for you. For example, if you want the data to contain a space,
you need to replace that space with %20 etc. Failing to comply with this
will most likely cause your data to be received wrongly and messed up."
This means you do really have to encode the data yourself the right way.
01-Oct-2006 02:51
As Yevgen mentioned earlier sometimes we can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE. Below is a header callback function I wrote back in January that lets you maintain cookies between cURL requests. Cookies are added to $ch during all requests even during redirection, so you can use it together with CURLOPT_FOLLOWLOCATION.
Here is the code:
function read_header($ch, $string)
{
global $location; #keep track of location/redirects
global $cookiearr; #store cookies here
global $ch;
# ^overrides the function param $ch
# this is okay because we need to
# update the global $ch with
# new cookies
$length = strlen($string);
if(!strncmp($string, "Location:", 9))
{ #keep track of last redirect
$location = trim(substr($string, 9, -1));
}
if(!strncmp($string, "Set-Cookie:", 11))
{ #get the cookie
$cookiestr = trim(substr($string, 11, -1));
$cookie = explode(';', $cookiestr);
$cookie = explode('=', $cookie[0]);
$cookiename = trim(array_shift($cookie));
$cookiearr[$cookiename] = trim(implode('=', $cookie));
}
$cookie = "";
if(trim($string) == "")
{ #execute only at end of header
foreach ($cookiearr as $key=>$value)
{
$cookie .= "$key=$value; ";
}
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
}
return $length;
}
Using the header function with curl (add this before curl_exec):
#don't forget globals, especially if you are using this in function
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'read_header');
This code assumes that you will reuse $ch without initializing it every time (call curl_init only once, in the beginning). If you need to initialize $ch again at any point in your code you can access the currently stored cookies in $cookiearr and include them in the new $ch.
I wrote this function before I had enough experience with regular expressions so you won't find any preg_match calls here. I have used this code for quite a while and without any problems accessing gmail, yahoo, hotmail, aol etc. where I had to go through login and a few pages before getting to what I was looking for.
Svetlozar Petrov (http://svetlozar.net)
23-Aug-2006 08:35
Note that if you want to use a proxy and use it as a _cache_, you'll have to do:
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.
14-Jul-2006 01:58
You can use CURLOPT_HEADERFUNCTION with a callback inside an object. This makes is it easy to capture the headers for later use. For example:
<?
class Test
{
public $headers;
//...
public function exec($opts)
{
$this->headers = array();
$opts[CURLOPT_HEADERFUNCTION] = array($this, '_setHeader');
$ch = curl_init();
curl_setopt_array($ch, $opts);
return curl_exec($ch);
}
private function _setHeader($ch, $header)
{
$this->headers[] = $header;
return strlen($header);
}
}
$test = new Test();
$opts = array(
//... your curl opts here
);
$data = $test->exec($opts);
print_r($test->headers);
?>
...something like that
(This works in php v. 5.1.4)
30-May-2006 09:31
Clarification on the callback methods:
- CURLOPT_HEADERFUNCTION is for handling header lines received *in the response*,
- CURLOPT_WRITEFUNCTION is for handling data received *from the response*,
- CURLOPT_READFUNCTION is for handling data passed along *in the request*.
The callback "string" can be any callable function, that includes the array(&$obj, 'someMethodName') format.
-Philippe
14-Apr-2006 05:22
Sometimes you can't use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE becoz of the server php-settings(They say u may grab any files from server using these options). Here is the solution
1)Don't use CURLOPT_FOLLOWLOCATION
2)Use curl_setopt($ch, CURLOPT_HEADER, 1)
3)Grab from the header cookies like this:
preg_match_all('|Set-Cookie: (.*);|U', $content, $results);
$cookies = implode(';', $results[1]);
4)Set them using curl_setopt($ch, CURLOPT_COOKIE, $cookies);
Good Luck, Yevgen
27-Mar-2006 01:59
- CURLOPT-HTTPAUTH is defined in php 4.4.2 9and maybe lower), even tough the manual says php 5.0 only...
- it is not clear from the manual what kind of http auth is carried out by default if user specifies username/pwd: it is BASIC auth
ps: note to manual writers: the version info on this page always looks a bit inaccurate, especially regarding the php version where a given option first appeared...
28-Dec-2005 12:24
To further expand upon use of CURLOPT_CAPATH and CURLOPT_CAINFO...
In my case I wanted to prevent curl from talking to any HTTPS server except my own using a self signed certificate. To do this, you'll need openssl installed and access to the HTTPS Server Certificate (server.crt by default on apache)
You can then use a command simiar to this to translate your apache certificate into one that curl likes.
$ openssl x509 -in server.crt -out outcert.pem -text
Then set CURLOPT_CAINFO equal to the the full path to outcert.pem and turn on CURLOPT_SSL_VERIFYPEER.
If you want to use the CURLOPT_CAPATH option, you should create a directory for all the valid certificates you have created, then use the c_rehash script that is included with openssl to "prepare" the directory.
If you dont use the c_rehash utility, curl will ignore any file in the directory you set.
22-Dec-2005 12:13
There is really a problem of transmitting $_POST data with curl in php 4+ at least.
I improved the encoding function by Alejandro Moreno to work properly with mulltidimensional arrays.
<?php
function data_encode($data, $keyprefix = "", $keypostfix = "") {
assert( is_array($data) );
$vars=null;
foreach($data as $key=>$value) {
if(is_array($value)) $vars .= data_encode($value, $keyprefix.$key.$keypostfix.urlencode("["), urlencode("]"));
else $vars .= $keyprefix.$key.$keypostfix."=".urlencode($value)."&";
}
return $vars;
}
curl_setopt($ch, CURLOPT_POSTFIELDS, substr(data_encode($_POST), 0, -1) );
?>
23-Oct-2005 04:34
Resetting CURLOPT_FILE to STDOUT won't work by calling curl_setopt() with the STDOUT constant or a php://output stream handle (at least I get error messages when trying the code from phpnet at andywaite dot com). Instead, one can simply reset it as a side effect of CURLOPT_RETURNTRANSFER. Just say
curl_setopt($this->curl,CURLOPT_RETURNTRANSFER,0);
and following calls to curl_exec() will output to STDOUT again.
20-Oct-2005 11:42
A little mistake, that took a half-day to fix it:
When specifing CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR options, don't forget to "chmod 777" that directory where cookie-file must be created.
23-Aug-2005 06:10
when specifing the file for either CURLOPT_COOKIEFILE or CURLOPT_COOKIEJAR you may need to use the full file path instead of just the relative path.
08-Jun-2005 12:08
After setting CURLOPT_FILE, you may want want to revert back to the normal behaviour of displaying the results. This can be achieved using:
$fp = fopen ("php://output", "w") or die("Unable to open stdout for writing.\n");
curl_setopt($ch, CURLOPT_FILE, $fp);
09-May-2005 07:26
Using cURL, I needed to call a third-party script which was returning binary data as attachment to pass on retrieved data again as attachment.
Problem was that the third-party script occassionally returned HTTP errors and I wanted to avoid passing on zero-length attachment in such case.
Combination of using CURLOPT_FAILONERROR and CURLOPT_HEADERFUNCTION callback helped to process the third-party script HTTP errors neatly:
<?
function curlHeaderCallback($resURL, $strHeader) {
if (preg_match('/^HTTP/i', $strHeader)) {
header($strHeader);
header('Content-Disposition: attachment; filename="file-name.zip"');
}
return strlen($strHeader);
}
$strURL = 'http://www.somesite.com/script-whichs-dumps-binary-attachment.php';
$resURL = curl_init();
curl_setopt($resURL, CURLOPT_URL, $strURL);
curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback');
curl_setopt($resURL, CURLOPT_FAILONERROR, 1);
curl_exec ($resURL);
$intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE);
curl_close ($resURL);
if ($intReturnCode != 200) {
print 'was error: ' . $intReturnCode;
}
?>
05-May-2005 03:00
I don't know if in PHP 5+ this problem is solved, but, when I send via POST using CURLOPT_POSTFIELDS some times it doesnt work an associative array as parameter... and, if I need to send non-ascii characters (like ,,,,etc..) this problem appears too.
The solution is to encode in a unique string all the post key=>values
Possibly this code doesnt work:
<?php
$post_data = array();
$post_data['var1'] = "Diseo web uruguay";
$post_data['var2'] = "Other string";
$url = "http://www.someurl.com/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
?>
But this works:
<?php
$post_data = array();
$post_data['var1'] = "Diseo web uruguay";
$post_data['var2'] = "Other string";
$url = "http://www.someurl.com/";
$o="";
foreach ($post_data as $k=>$v)
{
$o.= "$k=".utf8_encode($v)."&";
}
$post_data=substr($o,0,-1);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_URL, );
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
$result = curl_exec($ch);
?>
Rgds.
Alejandro Moreno.-
23-Mar-2005 08:03
AZAds is a traffic exchange that we wrote. We wanted to come up with a way to check the UP or DOWN status of a submitted URL. Here is the solution we came up with. Can also be used for a site monitoring service.
<?
$uServer="$url";
@$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$uServer");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
@curl_exec($ch);
$errnum=curl_errno($ch);
@curl_close($ch);
if($errnum != "0") {
print "Remote Site Status: DOWN";
} else {
print "Remote Site Status: UP";
}
?>
Simply feed the URL to be tested into $url. The code will check the site and return the error code if there is one and display to appropriate message.
Hope this is useful.
Keith
www.azads.net
21-Feb-2005 07:38
Another way to automate a login process and store multiple cookies for additional transfers.
(The easiest way is probably just to use CURLOPT_COOKIEJAR and CURLOPT_COOKIEFILE and save them to a file. But if you need to change those cookie values or add/delete them then you can use the code below to set them.)
Continuing with Paul Ebermann's parsing function.
function parse_response($this_response)
{
// Split response into header and body sections
list($response_headers, $response_body) = explode("\r\n\r\n", $this_response, 2);
$response_header_lines = explode("\r\n", $response_headers);
// First line of headers is the HTTP response code
$http_response_line = array_shift($response_header_lines);
if(preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line, $matches)) { $response_code = $matches[1]; }
// put the rest of the headers in an array
$response_header_array = array();
foreach($response_header_lines as $header_line)
{
list($header,$value) = explode(': ', $header_line, 2);
$response_header_array[$header] .= $value."\n";
}
return array("code" => $response_code, "header" => $response_header_array, "body" => $response_body);
}
// Do transfer, and make sure to include header in response
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "[login process]");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// Parse the response message
$response = parse_response($response);
// Create the basic header
$this_header = array(
"MIME-Version: 1.0",
"Content-type: text/html; charset=iso-8859-1",
"Content-transfer-encoding: text"
);
// Add each cookie that has been returned in the response
// If cookies need to be added/deleted or value changed, then add code here
$cookies = explode("\n", $response["header"]["Set-Cookie"]);
foreach($cookies as $this_cookie) { array_push($this_header, "Cookie: ".$this_cookie); }
// Next set of transfers
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "[new transfer]");
curl_setopt($ch, CURLOPT_HTTPHEADER, $this_header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
11-Nov-2004 07:51
The parse_response code below does not return multiple cookies as the value of 'Set-Cookie' if multiple cookies are set by the server. It appears to only return the last cookie set.
09-Oct-2004 12:10
Each example of CURLOPT_POSTFIELDS in these comments has missing urlencode() on variable values. This should be applied according to RFC1738
<?php
$vars=null;
foreach($data as $key=>$value)
if($key && $value)
$vars.=$key."=".urlencode($value)."&";
?>
21-Jul-2004 11:19
Hi!
I have found some information I am sure it could help lot of programmers when they want to connect with curl to any https website and they haven't a good or right CA Cert :)
I give you just one example It has resolved me 2 hours of my time looking for a solution.
It is simple, just if you get any error in the curl_exec (use curl_error(...) to see the error to trace it) add the next line and everything is solved:
(note: replace $ch with the right curl variable)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
<?php
$ch = curl_init();
$res= curl_setopt ($ch, CURLOPT_URL,"https://yoururl/cgi");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "Idc=si&");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$xyz = curl_exec ($ch);
curl_close ($ch);
echo $xyz;
if ($xyz == NULL) {
echo "Error:<br>";
echo curl_errno($ch) . " - " . curl_error($ch) . "<br>";
}
?>
I hope this helps.
Raul Mate Galan
Ceo Navenetworks Corp.
Note: Thanks to Ruben Lopez Gea for his help too.
07-May-2004 06:00
If you specify a CAINFO, note that the file must be in PEM format! (If not, it won't work).
Using Openssl you can use:
openssl x509 -in <cert> -inform d -outform PEM -out cert.pem
To create a pem formatted certificate from a binary certificate (the one you get if you download the ca somewhere).
29-Apr-2004 05:48
I found it very annoying that cURL did not offer any easy way to extract the response headers. If you do
curl_setopt($ch, CURLOPT_HEADER, 1);
then you only get the headers output inline with the rest of your response. Here's a nice little function to parse the cURL response when you use CURLOPT_HEADER. I took it from an example on another site and turned it into a function. It assumes you're using CURLOPT_RETURNTRANSFER to return the response to some variable that is then passed to the function. You just pass it a curl_exec result and it returns the result parsed into an array with headers broken up into their correct parts.
<?php
function parse_response($response){
/*
***original code extracted from examples at
***http://www.webreference.com/programming
/php/cookbook/chap11/1/3.html
***returns an array in the following format which varies depending on headers returned
[0] => the HTTP error or response code such as 404
[1] => Array
(
[Server] => Microsoft-IIS/5.0
[Date] => Wed, 28 Apr 2004 23:29:20 GMT
[X-Powered-By] => ASP.NET
[Connection] => close
[Set-Cookie] => COOKIESTUFF
[Expires] => Thu, 01 Dec 1994 16:00:00 GMT
[Content-Type] => text/html
[Content-Length] => 4040
)
[2] => Response body (string)
*/
list($response_headers,$response_body) = explode("\r\n\r\n",$response,2);
$response_header_lines = explode("\r\n",$response_headers);
// first line of headers is the HTTP response code
$http_response_line = array_shift($response_header_lines);
if (preg_match('@^HTTP/[0-9]\.[0-9] ([0-9]{3})@',$http_response_line,
$matches)) {
$response_code = $matches[1];
}
// put the rest of the headers in an array
$response_header_array = array();
foreach ($response_header_lines as $header_line) {
list($header,$value) = explode(': ',$header_line,2);
$response_header_array[$header] = $value;
}
return array($response_code,$response_header_array,$response_body);
}
?>
04-Apr-2004 11:20
A bit more documentation (without minimum version numbers):
- CURLOPT_WRITEFUNCTION
- CURLOPT_HEADERFUNCTION
Pass a function which will be called to write data or headers respectively. The callback function prototype:
long write_callback (resource ch, string data)
The ch argument is CURL session handle. The data argument is data received. Note that its size is variable. When writing data, as much data as possible will be returned in all invokes. When writing headers, exactly one complete header line is returned for better parsing.
The function must return number of bytes actually taken care of. If that amount differs from the amount passed to this function, an error will occur.
- CURLOPT_READFUNCTION
Pass a function which will be called to read data. The callback function prototype:
string read_callback (resource ch, resource fd, long length)
The ch argument is CURL session handle. The fd argument is file descriptor passed to CURL by CURLOPT_INFILE option. The length argument is maximum length which can be returned.
The function must return string containing the data which were read. If length of the data is more than maximum length, it will be truncated to maximum length. Returning anything else than a string means an EOF.
[Note: there is more callbacks implemented in current cURL library but they aren't unfortunately implemented in php curl interface yet.]
19-Nov-2003 04:18
The page http://curl.haxx.se/libcurl/c/curl_easy_setopt.html at the cURL site has a list of all the CURLOPTS, including many not mentioned here. Also see http://curl.haxx.se/libcurl/php/examples/ for cURL examples in PHP.
14-May-2003 07:36
Just a reminder: When setting your CURLOPT_POSTFIELDS remember to replace the spaces in your values with %20
24-Feb-2003 11:38
Often times people ask about how to get data from secure servers.
Here is an example of getting the balance page from Paypal
<?
# script by Joel De Gan
# http://listbid.com
function GetCurlPage ($pageSpec) {
$agent = "up.b";
$header[] = "Accept: text/vnd.wap.wml,*.*";
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1); ########### debug
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cook");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cook");
$tmp = curl_exec ($ch);
curl_close ($ch);
return $tmp;
}
function PostCurlPage ($pageSpec, $data) {
$agent = "up.b";
$header[] = "Accept: text/vnd.wap.wml,*.*";
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1); ########### debug
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt ($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_COOKIEJAR, "cook");
curl_setopt($ch, CURLOPT_COOKIEFILE, "cook");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$tmp = curl_exec ($ch);
curl_close ($ch);
return $tmp;
}
$first = GetCurlPage("https://www.paypal.com/cgi-bin/phscr?cmd=login");
$exp = explode("=", $first);
$id = explode("\"", $exp[16]);
$second = PostCurlPage("https://www.paypal.com/cgi-bin/phscr?rs=".$id[0], "email=EMAIL@HOST.COM&pass=YOUR_PP_PASS&cmd=login-submit-pass");
echo $second."\n\n";
?>
13-Nov-2002 02:19
About the CURLOPT_HTTPHEADER option, it took me some time to figure out how to format the so-called 'Array'. It fact, it is a list of strings. If Curl was already defining a header item, yours will replace it. Here is an example to change the Content Type in a POST:
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
Yann
beware that not all cURLlib constants are supported under php :
e.g. CURLOPT_PROGRESSFUNCTION or CURLOPT_WRITEDATA are not supported.
CURLOPT_WRITEFUNCTION, although undocumented is supported. It takes the name of a user_defined function.
the function should take two arguments (the curl handle, and the inputdata) and return the length of the written data
e.g.
function myPoorProgressFunc($ch,$str){
global $fd;
$len = fwrite($fd,$str);
print("#");
return $len;
}
curl_setopt($ch,CURLOPT_WRITEFUNCTION,"myPoorProgressFunc");
Also be aware that CURLOPT_WRITEFUNCTION does NOT take the CURLOPT_FILE as a parameter!
in curl lib it would take CURLOPT_WRITEDATA but this is not supported by php; that's why I use "global $fd;" in my exemple function.
CURLOPT_HEADERFUNCTION works the same, and is guaranteed to receive complete header lines as input!
Hope this helps
Ivan
14-Sep-2002 12:34
If you set return transfer to 1 and are sending a post form and find that this crashes php try setting follow location to 1 also. I'm not exactly sure why this crashed, but after i used follow it stopped.
curl_setopt ($sess, CURLOPT_FOLLOWLOCATION, '1');
curl_setopt ($sess, CURLOPT_RETURNTRANSFER, '1');
27-Aug-2002 12:31
To make a POST in multipart/form-data mode
this worked for me, the " \n" at the end of the variables was very important on my OS X server.
<?php
$file = "file_to_upload.txt";
$submit_url = "http://www.url_to_upload_to.com/upload_page.php";
$formvars = array("cc"=>"us \n");
$formvars[variable_1] = "bla bla \n";
$formvars[variable_2] = "bla bla \n";
$formvars[variable_3] = "bla bla \n";
$formvars[variable_4] = "bla bla \n";
$formvars[upfile] = "@$file"; // "@" causes cURL to send as file and not string (I believe)
// init curl handle
$ch = curl_init($submit_url);
curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt"); //initiates cookie file if needed
curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt"); // Uses cookies from previous session if exist
curl_setopt($ch, CURLOPT_REFERER, "http://www.last_url_for_referer_logs.com"); //if server needs to think this post came from elsewhere
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); // follow redirects recursively
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $formvars);
// perform post
echo $pnp_result_page = curl_exec($ch);
curl_close ($ch);
?>
16-Apr-2002 06:05
#!/usr/local/bin/php -q
<?php
$id = "xxxx";
$pw = "xxxx";
$LOGINURL = "http://login.daum.net/Mail-bin/login.cgi";
$GETURL = "http://www.daum.net/Mail-bin/mail_list";
$POSTFIELDS = "id=$id&pw=$pw";
function AUTH_SITE_COOKIE_STORE($LOGINURL,$POSTFIELDS)
{
$parseURL = parse_url($LOGINURL);
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "$parseURL[host].cookie");
curl_setopt($ch, CURLOPT_URL,"$LOGINURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$POSTFIELDS");
ob_start();
curl_exec ($ch);
ob_end_clean();
curl_close ($ch);
return "$parseURL[host].cookie";
}
function AUTH_SITE_GET($GETURL,$cookieFile)
{
$parseURL = parse_url($GETURL);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "$cookieFile");
curl_setopt($ch, CURLOPT_URL,"$GETURL");
$result = curl_exec ($ch);
curl_close ($ch);
$fp = fopen ("$parseURL[host].html", "w");
fwrite($fp,$result);
fclose ($fp);
return $result;
}
$cookieFile = AUTH_SITE_COOKIE_STORE($LOGINURL,$POSTFIELDS);
echo $result = AUTH_SITE_GET($GETURL,$cookieFile);
?>
03-Apr-2002 12:14
CURLOPT_HTTPHEADER is NOT like the -H command line switch. The command line switch adds or replaces headers (much like the header() line in PHP, but for HTTP clients instead of servers), but the curl extension will eliminate the headers cURL sends by default.
For instance, your Authorization, Host, Referer, Pragma, and Accept headers which are normally written by default or by other CURLOPT_*'s.
Also, it might seem intuitive that this should accept an array hash of header->values, but this is not the case. It accepts an array of strings of the format "Header: Value", much like the -H command-line switch.
Hope this helps,
terry
01-Mar-2002 05:18
It's possible to take advantage of multiple URLs on the same host in one curl_exec transaction ... just use multiple instances of CURLOPT_URL.
Example:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://foo.com/a.html");
curl_setopt($ch, CURLOPT_URL, "http://foo.com/b.html");
curl_setopt($ch, CURLOPT_URL, "http://foo.com/c.html");
curl_exec($ch);
curl_close($ch);
... the URLs appear to be hit in the same order they are entered. This takes advantage of cURL's Persistant Connection capability if all the URLs are on the same host!
18-Dec-2001 11:35
To collect cookies recieved with a request, set CURLOPT_COOKIEJAR "cookieFileName". Then use CURLOPT_COOKIEFILE "cookieFileName" to recall them in subsequent transactions.
To make a POST in multipart/form-data mode
(to upload a file for example) you can use
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
where $post is an array :
$post['key1'] = 'data1'
// like a text field in a POST
$post['file1'] = '@filename1'
// upload filename1
For more informations see the
curl_formparse man page.
15-May-2001 12:00
CURLOPT_RETURNTRANSFER has the interesting behaviour of tacking a null char onto the end of the string. This null char is actually on the end of the php string, and can cause some odd results if you're not expecting it to be there.
22-Feb-2001 03:50
If you want to connect to a secure server for posting info/reading info, you need to make cURL with the openSSL options. Then the sequence is nearly identical to the previous example (except http_S_://, and possibly add the useragent):
curl_setopt($ch, CURLOPT_URL,"https://secure.website.com");
//some sites only accept your request if your browser looks legit, so send a useragent profile...
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
07-Feb-2001 05:09
If you'd like to include extra headers in your POST request, you can accomplish this by setting the following option:
CURLOPT_HTTPHEADER
This is similar to the CURL -H command line switch.
Thanks to Daniel Stenberg for pointing out this usefull feature!
Note: this option was first supported in PHP version 4.03 .
25-Jan-2001 09:33
Just because the docs are rather sparse on this, to set multiple values in a cookie, you separate them with a semicolon, as usual. An example, yo set j to j and k to k:
curl_setopt($ch,CURLOPT_COOKIE,"j=j;k=k");
-- Alex
