PHPのお勉強!

PHP TOP

curl_exec

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

curl_execcURL セッションを実行する

説明

curl_exec(CurlHandle $handle): string|bool

指定した cURL セッションを実行します。

この関数は、cURL セッションを初期化し、 オプションを全て設定した後にコールする必要があります。

パラメータ

handle

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

戻り値

成功時には、この関数は結果を直接 stdout にフラッシュし、true を返します。失敗した場合に false を返します しかし、オプション CURLOPT_RETURNTRANSFER設定されていると、 成功した場合に取得結果を、失敗した場合に false を返します。

警告

この関数は論理値 false を返す可能性がありますが、false として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

注意:

(404 Not found のような) エラーを示すレスポンスステータスコード は、 失敗とはみなされないことに注意してください。 curl_getinfo() 関数が、そうしたチェックを行うのに使えます。

変更履歴

バージョン 説明
8.0.0 handleCurlHandle クラスのインスタンスを期待するようになりました。 これより前のバージョンでは、resource を期待していました。

例1 ウェブページの取得

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

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

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

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

参考

  • curl_multi_exec() - 現在の cURL ハンドルから、サブ接続を実行する

add a note

User Contributed Notes 9 notes

up
117
David from Code2Design.com
14 years ago
Just in case anyone is looking for a a couple of simple functions [to help automate cURL processes for POST and GET queries] I thought I'd post these.

<?php

/**
* Send a POST requst using cURL
* @param string $url to request
* @param array $post values to send
* @param array $options for cURL
* @return string
*/
function curl_post($url, array $post = NULL, array $options = array())
{
$defaults = array(
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_URL => $url,
CURLOPT_FRESH_CONNECT => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FORBID_REUSE => 1,
CURLOPT_TIMEOUT => 4,
CURLOPT_POSTFIELDS => http_build_query($post)
);

$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( !
$result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return
$result;
}

/**
* Send a GET requst using cURL
* @param string $url to request
* @param array $get values to send
* @param array $options for cURL
* @return string
*/
function curl_get($url, array $get = NULL, array $options = array())
{
$defaults = array(
CURLOPT_URL => $url. (strpos($url, '?') === FALSE ? '?' : ''). http_build_query($get),
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_TIMEOUT => 4
);

$ch = curl_init();
curl_setopt_array($ch, ($options + $defaults));
if( !
$result = curl_exec($ch))
{
trigger_error(curl_error($ch));
}
curl_close($ch);
return
$result;
}
?>
up
32
Anonymous
18 years ago
Be careful when using curl_exec() and the CURLOPT_RETURNTRANSFER option. According to the manual and assorted documentation:
Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

When retrieving a document with no content (ie. 0 byte file), curl_exec() will return bool(true), not an empty string. I've not seen any mention of this in the manual.

Example code to reproduce this:
<?php

// fictional URL to an existing file with no data in it (ie. 0 byte file)
$url = 'http://www.example.com/empty_file.txt';

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);

// execute and return string (this should be an empty string '')
$str = curl_exec($curl);

curl_close($curl);

// the value of $str is actually bool(true), not empty string ''
var_dump($str);

?>
up
22
turiyag
7 years ago
Don't disable SSL verification! You don't need to, and it's super easy to stay secure! If you found that turning off "CURLOPT_SSL_VERIFYHOST" and "CURLOPT_SSL_VERIFYPEER" solved your problem, odds are you're just on a Windows box. Takes 2 min to solve the problem. Walkthrough here:

https://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
up
7
jpatta at digitalgamesystems dot com
3 years ago
If you are looking the debug curl_exec, you may wish to log its details, and analyze the various time points during its execution.

before curl_exec:

<?php
// this will produce a curl log
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl, CURLOPT_STDERR, fopen('/your/writable/app/logdir/curl.log', 'a+')); // a+ to append...
?>

after curl_exec, but before curl_close:

<?php
// this will extract the timing information
extract(curl_getinfo($curl)); // create metrics variables from getinfo
$appconnect_time = curl_getinfo($curl, CURLINFO_APPCONNECT_TIME); // request this time explicitly
$downloadduration = number_format($total_time - $starttransfer_time, 9); // format, to get rid of scientific notation
$namelookup_time = number_format($namelookup_time, 9);
$metrics = "CURL...: $url Time...: $total_time DNS: $namelookup_time Connect: $connect_time SSL/SSH: $appconnect_time PreTransfer: $pretransfer_time StartTransfer: $starttransfer_time Download: $downloadduration";
error_log($metrics); // write to php-fpm default www-error.log, or append it to same log as above with file_put_contents(<filename>, $metrics, FILE_APPEND)
?>

Happy debugging
up
-1
roman dot ivasyuk at gmail dot com
16 years ago
<?php
class CurlRequest
{
private
$ch;
/**
* Init curl session
*
* $params = array('url' => '',
* 'host' => '',
* 'header' => '',
* 'method' => '',
* 'referer' => '',
* 'cookie' => '',
* 'post_fields' => '',
* ['login' => '',]
* ['password' => '',]
* 'timeout' => 0
* );
*/
public function init($params)
{
$this->ch = curl_init();
$user_agent = 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; ru; rv:1.8.0.9) Gecko/20061206 Firefox/1.5.0.9'
;
$header = array(
"Accept: text/xml,application/xml,application/xhtml+xml,
text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
,
"Accept-Language: ru-ru,ru;q=0.7,en-us;q=0.5,en;q=0.3",
"Accept-Charset: windows-1251,utf-8;q=0.7,*;q=0.7",
"Keep-Alive: 300");
if (isset(
$params['host']) && $params['host']) $header[]="Host: ".$host;
if (isset(
$params['header']) && $params['header']) $header[]=$params['header'];

@
curl_setopt ( $this -> ch , CURLOPT_RETURNTRANSFER , 1 );
@
curl_setopt ( $this -> ch , CURLOPT_VERBOSE , 1 );
@
curl_setopt ( $this -> ch , CURLOPT_HEADER , 1 );

if (
$params['method'] == "HEAD") @curl_setopt($this -> ch,CURLOPT_NOBODY,1);
@
curl_setopt ( $this -> ch, CURLOPT_FOLLOWLOCATION, 1);
@
curl_setopt ( $this -> ch , CURLOPT_HTTPHEADER, $header );
if (
$params['referer']) @curl_setopt ($this -> ch , CURLOPT_REFERER, $params['referer'] );
@
curl_setopt ( $this -> ch , CURLOPT_USERAGENT, $user_agent);
if (
$params['cookie']) @curl_setopt ($this -> ch , CURLOPT_COOKIE, $params['cookie']);

if (
$params['method'] == "POST" )
{
curl_setopt( $this -> ch, CURLOPT_POST, true );
curl_setopt( $this -> ch, CURLOPT_POSTFIELDS, $params['post_fields'] );
}
@
curl_setopt( $this -> ch, CURLOPT_URL, $params['url']);
@
curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYPEER, 0 );
@
curl_setopt ( $this -> ch , CURLOPT_SSL_VERIFYHOST, 0 );
if (isset(
$params['login']) & isset($params['password']))
@
curl_setopt($this -> ch , CURLOPT_USERPWD,$params['login'].':'.$params['password']);
@
curl_setopt ( $this -> ch , CURLOPT_TIMEOUT, $params['timeout']);
}

/**
* Make curl request
*
* @return array 'header','body','curl_error','http_code','last_url'
*/
public function exec()
{
$response = curl_exec($this->ch);
$error = curl_error($this->ch);
$result = array( 'header' => '',
'body' => '',
'curl_error' => '',
'http_code' => '',
'last_url' => '');
if (
$error != "" )
{
$result['curl_error'] = $error;
return
$result;
}

$header_size = curl_getinfo($this->ch,CURLINFO_HEADER_SIZE);
$result['header'] = substr($response, 0, $header_size);
$result['body'] = substr( $response, $header_size );
$result['http_code'] = curl_getinfo($this -> ch,CURLINFO_HTTP_CODE);
$result['last_url'] = curl_getinfo($this -> ch,CURLINFO_EFFECTIVE_URL);
return
$result;
}
}
?>

Example of use:
<?php
..........
try
{
$params = array('url' => 'http://www.google.com',
'host' => '',
'header' => '',
'method' => 'GET', // 'POST','HEAD'
'referer' => '',
'cookie' => '',
'post_fields' => '', // 'var1=value&var2=value
'timeout' => 20
);

$this->curl->init($params);
$result = $this->curl->exec();
if (
$result['curl_error']) throw new Exception($result['curl_error']);
if (
$result['http_code']!='200') throw new Exception("HTTP Code = ".$result['http_code']);
if (!
$result['body']) throw new Exception("Body of file is empty");
...............
}
catch (
Exception $e)
{
echo
$e->getMessage();
}
?>
up
-1
hablutzel1 at gmail dot com
10 years ago
Be always aware that CURLOPT_SSL_VERIFYPEER set to FALSE or 0 should never be used for production as it makes the link inmediately vulnerable to man-in-the-middle attack, still you can use it during development, but I would suggest that only if you KNOW what are you doing, otherwise spend some more time making requests to HTTPS sites work without resorting to set that option to FALSE or 0.
up
-3
lukasl at ackleymedia dot com
18 years ago
Thank you for sharing this. I was wondering why my result was 1.

To get around this in a safe way, this is how I check if the result is valid.

$ch = curl_init(); /// initialize a cURL session
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec ($ch);
curl_close ($ch);

if (!is_string($xmlResponse) || !strlen($xmlResponse)) {
return $this->_set_error( "Failure Contacting Server" );
} else {
return $xmlResponse;
}
up
-4
nagyp at hunaxon dot hu
21 years ago
fyi:
It returns false if there's an error while executing the curl session, no matter how CURLOPT_RETURNTRANSFER is set.
up
-3
Roland
4 years ago
To check for a timeout or error -

if (!$responsexml || !is_string($responsexml) || !strlen($responsexml) || strpos($responsexml, 'upstream request timeout') !== false) {
return $this->sendRequest($request, $headers);
}
To Top