php_ curl_exec - manual
DESCRIPTION
PHP CURLTRANSCRIPT
-
[edit] Last updated: Fri, 05 Jul 2013
Report a bug
Report a bug
Report a bug
Report a bug
curl_exec
(PHP 4 >= 4.0.2, PHP 5)
curl_exec Perform a cURL session
Description
mixed curl_exec ( resource $ch )
Execute the given cURL session.
This function should be called after initializing a cURL session and all the options for the sessionare set.
Parameters
ch
A cURL handle returned by curl_init().
Return Values
Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option isset, it will return the result on success, FALSE on failure.
Examples
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
1 of 16 11/07/2013 12:02
-
Report a bug
11 3 years ago
See Also
curl_multi_exec() - Run the sub-connections of the current cURL handle
User Contributed Notes curl_exec - [26 notes]
David from Code2Design.com
Just in case anyone is looking for a a couple of simple functions [to help automate cURLprocesses for POST and GET queries] I thought I'd post these.
-
2 10 years ago
2 11 years ago
{ 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;}?>
nagyp at hunaxon dot hu
fyi:It returns false if there's an error while executing the curl session, no matter howCURLOPT_RETURNTRANSFER is set.
ppruett at webengr dot com
fyi - if you are having problems getting awebpage to display in your webpage withcurl_setopt(CURLOPT_RETURNTRANSFER, 1);due to version bugginess perhaps,you may can use output control functionslike this to show a web pageinside your webpage:
whatever
$ch = curl_init("http://www.cocoavillage.com/");// use output buffering instead of returntransfer -itmaybebuggyob_start();
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
3 of 16 11/07/2013 12:02
-
1 2 years ago
$retrievedhtml = ob_get_contents();ob_end_clean();// if you intend to print this page with meta tags, better clear out any expiration tag// $result = preg_replace('/(?s)]*>/i', '', $retrievedhtml);// for now I just want what is between the body tags so need// somehow cut the header footer $bodyandend = stristr($retrievedhtml,"") + 1;// got to change all to lowercase temporarily// because end body may be upperlowercasemix// to bad strirstr does not exist$temptofindposition=strtolower($bodyandend);$positionendendbodytag=strpos($temptofindposition,"
-
1 3 years ago
1 11 years ago
1 12 years ago
4 11 months ago
------------------------------------------------------(now useless) details at:
http://curl.haxx.se/mail/lib-2011-02/0101.html
http://readlist.com/lists/lists.php.net/php-general/16/81195.html
ivanargulo at NOSPAM gmail dot com
If having problems with special chars or entities (like , , , etc.), using the ISOencode, just decode the values given with the function utf8_decode().
For example:
The returned string is the following:
Ivn
Using utf8_decode, the result in ISO is
Ivn
colins at infofind dot com
Checking the source, curl_exec seems to return FALSE on failure, TRUE on success (unlessCURLOPT_RETURNTRANSFER is set 1, and then it returns the returned data).
csaba at alum dot mit dot edu
If you retrieve a web page and print it (so you can see it in your browser), and the pagehas an expiration, this expiration now applies to MyProgram.php and next time yourprogram/page is called, even if it's grabbing a different web page, it will show what itjust displayed. In Netscape you can get rid of this by going into Edit, Options, Advanced,Cache, and clear out the Disk Cache. But this is really annoying after short order. Thefollowing prevents the above scenario:
-
4 5 years ago
CURLOPT_RETURNTRANSFER Option
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Bert
roman dot ivasyuk at gmail dot com
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" ) {
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
6 of 16 11/07/2013 12:02
-
} @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:
-
1 8 years ago
-1 5 years ago
-1 11 years ago
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(); }?>
Jrgen Tjern
If you've got problems with curl_exec not working, you should rather check curl_errno andcurl_error than using commandline curl, like so:
(since this is easier, and also allows you to check for errors runtime, which is a vitalpart of any well-design piece of code. ;)
Florian Holzhauer
If you use apache2+mod_chroot with php5, add
LoadFile /lib/libnss_dns.so.2
to your mod_chroot config - this should resolver problems.
sharky at im dot net dot ua
If You want to hide result which return curl_exec
Use bufeered output.For example:-----------------------$ch = curl_init();curl_setopt($ch, CURLOPT_URL,"http://url.com/index.php");curl_setopt($ch, CURLOPT_POST, 1);curl_setopt($ch, CURLOPT_POSTFIELDS, "a=3&b=5");//--- Start bufferingob_start();curl_exec ($ch);//--- End buffering and clean output
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
8 of 16 11/07/2013 12:02
-
-2 1 year ago
0 3 years ago
curl_close ($ch);------------------
maybe it help somebody :))
----------Best Regards Sharky
ggarmento at yahoo dot com
I am a more tenacious designer than I am a code monkey; but the sample curl function endedan exhaustive four hour search.
I needed to execute a Search URL in a WordPress 3 page in order to return some Real Estateresults and my "unnamed" shared server had fopen and load() shut down.
The code below was the only code in the whole page; the WP3 theme wrapped around the searchresults like a mother and child at feeding time.
[code]
[code]
Whoot!!
petermiller1986[nospam] at gmail dot com
so far i have not come across any code or library file that willextract cookie information from a http header, so i've writtenone.
there are two files:file1.php - acts as server and sets the cookiesfile2.php - acts as browser and retrieves the cookies set by file1
/*****file1.php****/
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
9 of 16 11/07/2013 12:02
- /*****file2.php****/
-
0 4 years ago
4 years ago
{$matches[expiry_second][$i]}
{$matches[expiry_zone][$i]} "; $i++;}$table_string .= "";echo $table_string;?>/****end file2.php**/
i based this code on the following http header:(obtained by going: echo $server_output; in file2.php)
HTTP/1.1 200 OK Date: Thu, 30 Jul 2009 07:10:07 GMTServer: Apache/2.2.11 (Win32) DAV/2 mod_ssl/2.2.11OpenSSL/0.9.8i PHP/5.2.9 X-Powered-By: PHP/5.2.9Set-Cookie: cookie1=cookie+1+data; expires=Wed,29-Jul-2009 03:23:27 GMT Set-Cookiecookie2=cookie+2+data; expires=Wed, 29-Jul-2009 03:23:27GMT Set-Cookie: cookie3=cookie+3+data; expires=Wed,29-Jul-2009 03:23:27 GMT Content-Length: 196Content-Type: text/html
if your header differs from this one then $pattern in file2.phpwill need to be modified accordingly. hopefully this code will saveyou a lot of time though!
Mark Omohundro, ajamyajax.com
Just a simple curl_exec() example with a twist: I use the familiar http response status codereturned from curl_getinfo() to put either data, or a custom error message + curl_error()into a single string. I find this useful when the response ends up in a or tag.
lmshad at wp dot pl dot foo dot bar
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
11 of 16 11/07/2013 12:02
-
CurlTool::downloadFile('http://download.gadu-gadu.pl/gg77.exe', 'c:/');
-
} $content = preg_replace('#\n+#', ' ', $content); $content = preg_replace('#\s+#', ' ', $content); return $content; } public static function downloadFile($url, $fileName, $verbose = false) { if (($curl = curl_init($url)) == false) { throw new Exception("curl_init error for url $url."); } if (self::$proxyCount > 0) { $proxy = self::$proxyServers[self::$currentProxyIndex++ % self::$proxyCount]; curl_setopt($curl, CURLOPT_PROXY, $proxy); if ($verbose === true) { echo "Downloading $url [Proxy: $proxy] ... "; } } else if ($verbose === true) { echo "Downloading $url ... "; } curl_setopt_array($curl, self::$options); if (substr($fileName, -1) == '/') { $targetDir = $fileName; $fileName = tempnam(sys_get_temp_dir(), 'c_'); } if (($fp = fopen($fileName, "wb")) === false) { throw new Exception("fopen error for filename $fileName"); } curl_setopt($curl, CURLOPT_FILE, $fp); curl_setopt($curl, CURLOPT_BINARYTRANSFER, true); if (curl_exec($curl) === false) { fclose($fp); unlink($fileName); throw new Exception("curl_exec error for url $url."); } elseif (isset($targetDir)) { $eurl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL); preg_match('#^.*/(.+)$#', $eurl, $match); fclose($fp); rename($fileName, "$targetDir{$match[1]}"); $fileName = "$targetDir{$match[1]}"; } else { fclose($fp); } curl_close($curl); if ($verbose === true) { echo "Done.\n"; } return $fileName; } }
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
13 of 16 11/07/2013 12:02
-
0 5 years ago
0 5 years ago
0 5 years ago
alan at forsyth dot cz
Great class Roman - just one fix:
Replace the following line:
with this:
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 wouldcause 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 (forexample in the $header and $user_agent definitions etc.). It will still be valid PHP, butthe HTTP request will not be valid, and you may get a '400 Bad Request' response from theserver.
It took me a little playing around with an HTTP Sniffer before I finally got an HTTP POSTrequest fully working!
Thanks,Alan
me at lawrencemok dot com
Note that when you use CURL to POST things....e.g:
curl_setopt($ch, CURLOPT_POSTFIELDS, "string=This is a string");
The data part (e.g. "This is a string") inside the 3rd parameter should be applied withurlencode()
Otherwise, if you intend to send a string like "%2F", you will end up with a "/" on thereceiving end, which can cause troubles. (e.g. serialize() data cannot be unserialize()becase of the change in string length).
shanto at ultimawebsolutions dot com
A function to retrieve the status code of an HTTP request using CURL:
function getHttpResponseCode($url) { $ch = @curl_init($url); @curl_setopt($ch, CURLOPT_HEADER, TRUE); @curl_setopt($ch, CURLOPT_NOBODY, TRUE); @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); @curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $status = array(); $response = @curl_exec($ch); preg_match('/HTTP\/.* ([0-9]+) .*/', $response, $status); return $status[1];
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
14 of 16 11/07/2013 12:02
-
0 5 years ago
0 6 years ago
0 6 years ago
0 10 years ago
test at test dot com
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);
lukasl at ackleymedia dot com
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 sessioncurl_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;}
Anonymous
Be careful when using curl_exec() and the CURLOPT_RETURNTRANSFER option. According to themanual and assorted documentation:Set CURLOPT_RETURNTRANSFER to TRUE to return the transfer as a string of the return value ofcurl_exec() instead of outputting it out directly.
When retrieving a document with no content (ie. 0 byte file), curl_exec() will returnbool(true), not an empty string. I've not seen any mention of this in the manual.
Example code to reproduce this:
sybren at thirdtower dot com
If you see a "0" at the end of the output, you might want to switch to HTTP/1.0:
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
15 of 16 11/07/2013 12:02
-
-1 2 years ago
-2 8 years ago
-3 8 years ago
slash.dash.dash.com
[I was having a problem with] URLs not resolving I also tried cURL on the command line for anon-SSL request. It failed. wget failed. Then, I realized my ID is 10T.
Remember kids, if you go from DHCP to static, update your DNS server list!
landon at phazeforward dot com
If your curl installation is not compiled with SSL support you will beat your head against awall when trying to figure out why curl_exec() is failing to fail or do anything else ...
If you run into a situation where your call to curl_exec is not returning anything youshould try the same call with the command line curl
fifa_2k [-at-] sina [-dot-] com
With php 4.3.9 or higher,you can upload file to ftp server on win32 system
lower version php (I tried on php 4.3.3) on win32 can't do this and may cause php crash evenyou use CURLOPT_READFUNCTION.
Copyright 2001-2013 The PHP GroupAll rights reserved.
dismiss Step into the future! Click here to switch tothe beta php.net site
PHP: curl_exec - Manual http://au1.php.net/manual/en/function.curl-exec.php
16 of 16 11/07/2013 12:02