curl_exec
This function should be called after initializing a cURL session and all the options for the session are set.
Parameters
A cURL handle returned by curl_init() .
Return Values
Returns true on success or false on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, false on failure.
This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Note:
Note that response status codes which indicate errors (such as 404 Not found ) are not regarded as failure. curl_getinfo() can be used to check for these.
Changelog
Examples
Example #1 Fetching a web page
// create a new cURL resource
$ch = curl_init ();
?php
// set URL and other appropriate options
curl_setopt ( $ch , CURLOPT_URL , «http://www.example.com/» );
curl_setopt ( $ch , CURLOPT_HEADER , 0 );
// grab URL and pass it to the browser
curl_exec ( $ch );
// close cURL resource, and free up system resources
curl_close ( $ch );
?>
See Also
User Contributed Notes 23 notes
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.
/**
* 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 ;
>
?>
If you are looking the debug curl_exec, you may wish to log its details, and analyze the various time points during its execution.
// 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:
// 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(, $metrics, FILE_APPEND)
?>
Happy debugging
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:
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:
// fictional URL to an existing file with no data in it (ie. 0 byte file)
$url = ‘http://www.example.com/empty_file.txt’ ;
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 );
// the value of $str is actually bool(true), not empty string »
var_dump ( $str );
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’ ];
?php
@ 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:
.
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 keyword»>. $result [ ‘http_code’ ]);
if (! $result [ ‘body’ ]) throw new Exception ( «Body of file is empty» );
.
>
catch ( Exception $e )
echo $e -> getMessage ();
>
?>
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.
fyi:
It returns false if there’s an error while executing the curl session, no matter how CURLOPT_RETURNTRANSFER is set.
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;
>
If you are accessing HTTPS URLs and you do not receive any contents, try to disable verifying SSL.
curl_setopt ( $ch , CURLOPT_SSL_VERIFYHOST , 0 );
curl_setopt ( $ch , CURLOPT_SSL_VERIFYPEER , 0 );
?>
Great class Roman — just one fix:
Replace the following line:
if (isset( $params [ ‘host’ ]) && $params [ ‘host’ ]) $header []= «Host: » . $host ;
?>
with this:
if (isset( $params [ ‘host’ ]) && $params [ ‘host’ ]) $header []= «Host: » . $params [ ‘host’ ];
?>
CURL automatically creates the host parameter (since it is required for HTTP/1.1 requests), so you don’t need to set it. But if you created a custom host parameter, the above bug would cause a ‘400 Bad Request’ response due to invalid host specified.
Also when copying and pasting the class code, make sure that no line breaks occur (for example in the $header and $user_agent definitions etc.). It will still be valid PHP, but the HTTP request will not be valid, and you may get a ‘400 Bad Request’ response from the server.
It took me a little playing around with an HTTP Sniffer before I finally got an HTTP POST request fully working!
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);
>
fyi — if you are having problems getting a
webpage to display in your webpage with
curl_setopt(CURLOPT_RETURNTRANSFER, 1);
due to version bugginess perhaps,
you may can use output control functions
like this to show a web page
inside your webpage:
There will be times when you need to get the response from curl_exec and capture the transfer — this is not very well documented but you can do so with the CURLOPT_RETURNTRANSFER Option
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
If you’ve got problems with curl_exec not working, you should rather check curl_errno and curl_error than using commandline curl, like so:
(since this is easier, and also allows you to check for errors runtime, which is a vital part of any well-design piece of code. 😉
$creq = curl_init ();
curl_setopt ( $creq , CURLOPT_URL , «http://www.foo.internal» );
curl_exec ( $creq );
/* To quote curl_errno documentation:
Returns the error number for the last cURL operation on the resource ch, or 0 (zero) if no error occurred. */
if ( curl_errno ( $creq )) print curl_error ( $creq );
> else curl_close ( $creq );
>
?>
If you see a «0» at the end of the output, you might want to switch to HTTP/1.0:
curl_setopt($ch, CURLOPT_HTTP_VERSION, 1.0);