What is curl in php with example?
The 'Client for URLs,' is shortly called cURL, which was originally pronounced with URL in uppercase to emphasize that it deals with URLs. It's pronounced as: "see URL." 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. 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. php_info(); ?> $url_name = "https://google.com"; $ch_session = curl_init(); curl_setopt($ch_session, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch_session, CURLOPT_URL, $url); $result_url = curl_exec($ch_session); echo $result_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. OutputIn 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. To Download a File from a Remote Site using cURL in PHPIf 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$url_name ="https://support.microsoft.com/en-in/whats-new.html"; $file_name = __DIR__ . DIRECTORY_SEPARATOR . "Microsot_new_launch.html"; $handle_session = curl_init(); $fileHandle_name = fopen($file, "w"); curl_setopt_array($handle_session, array( CURLOPT_URL => $url_name, CURLOPT_FILE => $fileHandle_name, ) ); $data_result = curl_exec($handle_session); curl_close($handle_session); fclose($fileHandle_name); ?> 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 */ class curlDownloader { private $remoteFileName = NULL; private $ch = NULL; private $headers = array(); private $response = NULL; private $fp = NULL; private $debug = FALSE; private $fileSize = 0; const DEFAULT_FNAME = 'remote.out'; public function __construct($url) { $this->init($url); } public function toggleDebug() { $this->debug = !$this->debug; } public function init($url) { if( !$url ) throw new InvalidArgumentException("Need a URL"); $this->ch = curl_init(); curl_setopt($this->ch, CURLOPT_URL, $url); curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($this, 'headerCallback')); curl_setopt($this->ch, CURLOPT_WRITEFUNCTION, array($this, 'bodyCallback')); } public function headerCallback($ch, $string) { $len = strlen($string); if( !strstr($string, ':') ) { $this->response = trim($string); return $len; } list($name, $value) = explode(':', $string, 2); if( strcasecmp($name, 'Content-Disposition') == 0 ) { $parts = explode(';', $value); if( count($parts) > 1 ) { foreach($parts AS $crumb) { if( strstr($crumb, '=') ) { list($pname, $pval) = explode('=', $crumb); $pname = trim($pname); if( strcasecmp($pname, 'filename') == 0 ) { // Using basename to prevent path injection // in malicious headers. $this->remoteFileName = basename( $this->unquote(trim($pval))); $this->fp = fopen($this->remoteFileName, 'wb'); } } } } } $this->headers[$name] = trim($value); return $len; } public function bodyCallback($ch, $string) { if( !$this->fp ) { trigger_error("No remote filename received, trying default", E_USER_WARNING); $this->remoteFileName = self::DEFAULT_FNAME; $this->fp = fopen($this->remoteFileName, 'wb'); if( !$this->fp ) throw new RuntimeException("Can't open default filename"); } $len = fwrite($this->fp, $string); $this->fileSize += $len; return $len; } public function download() { $retval = curl_exec($this->ch); if( $this->debug ) var_dump($this->headers); fclose($this->fp); curl_close($this->ch); return $this->fileSize; } public function getFileName() { return $this->remoteFileName; } private function unquote($string) { return str_replace(array("'", '"'), '', $string); } } $dl = new curlDownloader( 'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.pexels.com%2Fsearch%2Ffree%2520download%2F&psig=AOvVaw3lIh07E0ZIZyNjqNl-JNSd&ust=1638024513705000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCKDNtfuitvQCFQAAAAAdAAAAABAD' ); $size = $dl->download(); printf("Downloaded %u bytes to %s\n", $size, $dl->getFileName()); ?> OutputForm Submission Using cURL in PHPWe'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.
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. The form design code is
$handle = curl_init(); $url = "https://localhost/curl/theForm.php"; $postData = array( 'firstName' => 'Lady', 'lastName' => 'Gaga', 'submit' => 'ok' ); curl_setopt_array($handle, array( CURLOPT_URL => $url, // Enable the post response. CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData, CURLOPT_RETURNTRANSFER => true, ) ); $data = curl_exec($handle); curl_close($handle); echo $data; ?> 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. OutputTo Perform Basic HTTP Authentication With cURL in PHPIn order to authenticate with cURL, the following three options need to be set:
Source Codecurl_setopt_array($handle_session, array( CURLOPT_URL => $url_, CURLOPT_HTTPAUTH => CURLAUTH_ANY, CURLOPT_USERPWD => "$user_name:$p_word", CURLOPT_RETURNTRANSFER => true, ) ); ?> OutputTo Handle the Cookies in cURL in PHPCookies 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$handle_session = curl_init(); $url_name = "https://support.microsoft.com/en-in/whats-new"; $file_name = __DIR__ . DIRECTORY_SEPARATOR . "cookie.txt"; curl_setopt_array($handle_session, array( CURLOPT_URL => $url_name, CURLOPT_COOKIEFILE => $file_name, CURLOPT_COOKIEJAR => $file_name, CURLOPT_RETURNTRANSFER => true, ) ); $data = curl_exec($handle); curl_close($handle); ?> OutputAdvance your career as a MEAN stack developer with the Full Stack Web Developer - MEAN Stack Master's Program. Enroll now! ConclusionUsing 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. What is a 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.
What is cURL function?curl, In mathematics, a differential operator that can be applied to a vector-valued function (or vector field) in order to measure its degree of local spinning. It consists of a combination of the function's first partial derivatives.
What are the cURL options in PHP?Available since PHP 7.3. 0 and libcurl >= cURL 7.52.
...
Parameters ¶. How get cURL URL in PHP?Use curl_getinfo($ch) , and the first element ( url ) would indicate the effective URL.
|