- curl_exec
- Parameters
- Return Values
- Changelog
- Examples
- See Also
- What Is cURL in PHP: Uses, Basic Concepts and Authentication
- Basics to Advanced — Learn It All!
- Role of cURL in PHP
- Basic Syntax for PHP Info
- Uses of cURL in PHP
- Functions of cURL in PHP
- Basics to Advanced — Learn It All!
- The Way to Download the Contents of a Remote Website to a Local File Using cURL in PHP
- Output
- Basics to Advanced — Learn It All!
- To Download a File from a Remote Site using cURL in PHP
- Source code
- Source Code for Response Page
- Output
- Form Submission Using cURL in PHP
- Output
- To Perform Basic HTTP Authentication With cURL in PHP
- Source Code
- Output
- To Handle the Cookies in cURL in PHP
- Source Code
- Output
- Conclusion
- Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
- About the Author
- Recommended Programs
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(); // 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
PHP 8.2
(PHP 4 4.0.3, 5, 7, 8) curl_error Return a string containing the last for current session Returns a clear text error message for the last cURL operation.
(PHP 5 5.5.0, 7, 8) curl_escape encodes the given string This function URL encodes the given string according to RFC 3986.
(PHP 5 5.5.0, 7, 8) curl_file_create CURLFile object This function an alias of: CURLFile::__construct()
(PHP 4 4.0.4, 5, 7, 8) curl_getinfo information regarding specific transfer Gets information about the last transfer.
What Is cURL in PHP: Uses, Basic Concepts and Authentication
cURL is a PHP library and command-line tool (similar to wget) that allows you to send and receive files over HTTP and FTP. You can use proxies, pass data over SSL connections, set cookies, and even get files that are protected by a login.
Basics to Advanced — Learn It All!
Role of cURL in PHP
This is a PHP module that allows PHP programs to use curl functions. When PHP’s cURL support is turned on, the phpinfo() function’s output will include cURL information. Before you write your first basic PHP program, you can double-check it.
Basic Syntax for PHP Info
Uses of cURL in PHP
- cURL is a PHP extension that allows you to use the URL syntax to receive and submit data.
- cURL makes it simple to connect between various websites and domains.
- Obtaining a copy of a website’s material.
- Submission of forms automatically, authentication and cookie use.
Functions of cURL in PHP
- curl_close — Used to close the session of cURL
- curl_error — It will return the string which represents the error for the particular current session.
- curl_exec — After a cURL session has been created and all of the session’s options have been set, the function should be named. Its sole aim is to run a predefined CURL session (given by ch).
- curl_file_create — To create a CURLFile as object
- curl_getinfo — Get information regarding a specific transfer
- curl_init — To initialize the cURL session for the URL
- curl_multi_close — Close a set of cURL handles
- curl_pause — Pause and unpause the session connection
- curl_reset — Reset all options of a libcurl session handle
- curl setopt($ch, option, value) sets a cURL session option defined by the ch parameter. The value specifies the value for the specified option, and the option specifies which option to set.
- Return page contents with curl setopt($ch, CURLOPT RETURNTRANSFER, 1). If the value is zero, no output will be returned.
- $url is passed as a parameter to curl setopt($ch, CURLOPT URL, $url). This is the website address for your goal server and the internet URL you’re looking for.
- curl_version — This may help in getting the information for the cURL version
Basics to Advanced — Learn It All!
The Way to Download the Contents of a Remote Website to a Local File Using cURL in PHP
curl_setopt($ch_session, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch_session, CURLOPT_URL, $url);
In the above example, we are trying to show the URL information which is assigned to google.com This URL name is assigned with the variable $url_name. The session has started with the variable $ch_session.
Output
In the above example, we are trying to view the home page of a Google website. The session was assigned with the curl_init(). This method will show the content of an assigned website into a particular curl_setopt() method. It will be saved as an html file for remote accessing.
Basics to Advanced — Learn It All!
To Download a File from a Remote Site using cURL in PHP
If the option CURLOPT_ FILE is activated, a remote file can be downloaded to our server. For example, the following code downloads «Microsoft new launch» from Microsoft company website and saves it to our server as the microsoft_new_launch.html:
Source code
$file_name = __DIR__ . DIRECTORY_SEPARATOR . «Microsot_new_launch.html»;
$fileHandle_name = fopen($file, «w»);
In the above source code, the url_name is nothing but an original resource location of the website. The handle session will manage the session details of the current website location.
We use the curl_getinfo command to get more information about the request. This command allows us to get important technical information about the response, such as the status code (200 for success), and the size of the downloaded file.
Source Code for Response Page
* vim: ts=4 sw=4 fdm=marker noet tw=78
private $remoteFileName = NULL;
const DEFAULT_FNAME = ‘remote.out’;
public function __construct($url)
public function toggleDebug()
throw new InvalidArgumentException(«Need a URL»);
curl_setopt($this->ch, CURLOPT_URL, $url);
public function headerCallback($ch, $string)
list($name, $value) = explode(‘:’, $string, 2);
if( strcasecmp($name, ‘Content-Disposition’) == 0 )
list($pname, $pval) = explode(‘=’, $crumb);
if( strcasecmp($pname, ‘filename’) == 0 )
// Using basename to prevent path injection
$this->fp = fopen($this->remoteFileName, ‘wb’);
public function bodyCallback($ch, $string)
trigger_error(«No remote filename received, trying default»,
$this->fp = fopen($this->remoteFileName, ‘wb’);
throw new RuntimeException(«Can’t open default filename»);
public function getFileName() < return $this->remoteFileName; >
private function unquote($string)
return str_replace(array(«‘», ‘»‘), », $string);
printf(«Downloaded %u bytes to %s\n», $size, $dl->getFileName());
Output
Form Submission Using cURL in PHP
We’ve seen how to use the GET method of HTTP up to this stage (which is generally used to watch and download content). In order to send forms, cURL can also use the HTTP POST process.
Let’s now see how to submit a form using cURL. To do this we need to create two files.
In this example, we are going to create the following two files — index.php, form.php.
- Include the cURL script in the index.php file.
- The design details of the form is enclosed in the form.php file.
In fact, form.php will be located on a remote server (although, for the sake of the example, both files may be placed on the same server). In addition, we’ll use a form with three fields: first_Name, last_Name, and submit.
With the help of the above mentioned form, we may get the details of first_name and last_name of the person using the form.
The details obtained is then be passed to the PHP response form.
Output
To Perform Basic HTTP Authentication With cURL in PHP
In order to authenticate with cURL, the following three options need to be set:
- CURLOPT_HTTPAUTH
- CURLOPT_USERPWD– Through which we define the username and password.
- CURLOPT_RETURNTRANSFER
Source Code
Output
To Handle the Cookies in cURL in PHP
Cookies are used to recognize returning tourists and authenticated users on a website. In order to do this, cURL includes a method for saving cookies.
The two key choices for dealing with cookies are:
CURLOPT COOKIEJAR– Defines the file that must be used to write cookies.
CURLOPT COOKIEFILE– This variable specifies the file from which the cookies will be read.
Source Code
$file_name = __DIR__ . DIRECTORY_SEPARATOR . «cookie.txt»;
Output
Conclusion
Using PHP’s cURL extension gives us a quick and easy way to communicate with other websites, particularly APIs provided by third parties. In the next tutorial, we’ll learn how to request private information on behalf of users who log in to our website using their GitHub account which will be achieved with the aid of cURL and the Github API.
In this article, you learned about cURL with syntax and examples. To get expertise in C programming, and to further enhance your career prospects and become a specialist and a full stack technologist, you can sign up for Simplilearn’s Full Stack Web Development program. For learners, Simplilearn has made a special selection of courses available for free. Join Simplilearn for free courses on SkillUp and revolutionize your profession with certificates, specializations, and dozens of other courses.
Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you soon.
Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:
Name | Date | Place | |
---|---|---|---|
Post Graduate Program in Full Stack Web Development | Cohort starts on 15th Aug 2023, Weekend batch | Your City | View Details |
Post Graduate Program in Full Stack Web Development | Cohort starts on 12th Sep 2023, Weekend batch | Your City | View Details |
Post Graduate Program in Full Stack Web Development | Cohort starts on 10th Oct 2023, Weekend batch | Your City | View Details |
About the Author
Ravikiran A S
Ravikiran A S works with Simplilearn as a Research Analyst. He an enthusiastic geek always in the hunt to learn the latest technologies. He is proficient with Java Programming Language, Big Data, and powerful Big Data Frameworks like Apache Hadoop and Apache Spark.
Recommended Programs
Post Graduate Program in Full Stack Web Development