PHP 8.4.1 Released!

curl_exec

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

curl_exec执行 cURL 会话

说明

curl_exec(CurlHandle $handle): string|bool

执行指定 cURL 会话。

这个函数应该在初始化 cURL 会话并且设置所有选项后调用。

参数

handle

curl_init() 返回的 cURL 句柄。

返回值

成功时返回 true, 或者在失败时返回 false。 然而,如果设置CURLOPT_RETURNTRANSFER 选项,将会在成功时返回结果,失败时返回 false

警告

此函数可能返回布尔值 false,但也可能返回等同于 false 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。

注意:

注意:指示错误的响应状态码(例如 404 Not found)不会视为失败。这种情况可以使用 curl_getinfo() 来检查。

更新日志

版本 说明
8.0.0 handle 现在接受 CurlHandle 实例;之前接受 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);
?>

参见

添加备注

用户贡献的备注 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