私は次のような簡単なコードを書きました:
$ch = curl_init();
//Set options
curl_setopt($ch, CURLOPT_URL, "http://www.php.net");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$website_content = curl_exec ($ch);
私の場合は、$website_content
次のようになりますfalse
。何が問題なのか、誰か提案/アドバイスをいただけませんか?
ベストアンサー1
エラーのチェックと処理はプログラマーの味方です。cURL 関数の初期化と実行の戻り値をチェックしてください。curl_error()
そしてcurl_errno()
失敗した場合の詳細情報が含まれます:
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ($ch === false) {
throw new Exception('failed to initialize');
}
// Better to explicitly set URL
curl_setopt($ch, CURLOPT_URL, 'http://example.com/');
// That needs to be set; content will spill to STDOUT otherwise
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Set more options
curl_setopt(/* ... */);
$content = curl_exec($ch);
// Check the return value of curl_exec(), too
if ($content === false) {
throw new Exception(curl_error($ch), curl_errno($ch));
}
// Check HTTP return code, too; might be something else than 200
$httpReturnCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
/* Process $content here */
} catch(Exception $e) {
trigger_error(sprintf(
'Curl failed with error #%d: %s',
$e->getCode(), $e->getMessage()),
E_USER_ERROR);
} finally {
// Close curl handle unless it failed to initialize
if (is_resource($ch)) {
curl_close($ch);
}
}
*のcurl_init()
マニュアル状態:
成功した場合はcURLハンドルを返します。間違いエラーについて。
FALSE
パラメータを使用してい$url
てドメインを解決できなかった場合、関数が返されるのを確認しました。パラメータが使用されていない場合、関数はかもしれない決して返さないでくださいFALSE
。ただし、マニュアルには「エラー」が実際に何であるかが明確に記載されていないため、常に確認してください。