cURL is a library which allows you to connect and communicate to many different types of servers with many different types of protocols. Using cURL you can:
- Implement payment gateways’ payment notification scripts.
- Download and upload files from remote servers.
- Login to other websites and access members only sections.
A typical PHP cURL usage follows the following sequence of steps.
curl_init – Initializes the session and returns a cURL handle which can be passed to other cURL functions.curl_opt – This is the main work horse of cURL library. This function is called multiple times and specifies what we want the cURL library to do.
curl_exec – Executes a cURL session.
curl_close – Closes the current cURL session.
Download file or web page using PHP cURL
The below piece of PHP code uses cURL to download Google’s RSS feed.
The below PHP code is a slight variation of the above code. It not only downloads the contents of the specified URL but also saves it to a file.
/** * Initialize the cURL session */ $ch = curl_init(); /*** Set theURLof the page or file to download.
*/curl_setopt($ch,CURLOPT_URL, ‘http://news.google.com/news?hl=en&topic=t& output=rss’);
/** * Create a new file */ $fp = fopen(‘rss.xml’, ‘w’); /** * Ask cURL to write the contents to a file */curl_setopt($ch,CURLOPT_FILE, $fp);
/** * Execute the cURL session */ curl_exec ($ch); /** * Close cURL session and file */ curl_close ($ch); fclose($fp); Here we have used another of the cURL options, CURLOPT_FILE. Obtain a file handler by creating a new file or opening an existing one and then pass this file handler to the curl_set_opt function.
cURL will now write the contents to a file as it downloads a web page or file.
No comments:
Post a Comment