|
#1
|
|||
|
|||
|
How to Use CURL With PHP
Introduction CURL is a library created by Daniel Stenberg, which allows you to connect and communicate with many different types of servers through various protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+p***word authentication. Requirements You will first need to install the lubcurl package if not already installed on your webserver. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that’s 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater. Getting Started To initiate a CURL session we use the curl_init() function. There are many different options that we are allowed to set with the curl_setopt() function. Once CURL has been setup the way we want, we need to execute the request with the curl_exec() function. Here is an example of a simple script to return the contents of Google’s homepage. PHP Code:
We can also use CURL to post data to a form. The default method of sending form data with CURL is in GET, but in this example we will use POST to submit a search term to an imaginary form. PHP Code:
CURL has support for proxies, including SSL. Below we refer to the code snippet in the first example, but modify it to use a proxy. PHP Code:
CURL comes with support for most forms of HTTP authentication, including HTTP basic, digest, GSS and NTLM. We will use out code snippet from the second example, but modify it to use basic authentication. [php] // Setup a string with the form parameters in it $strParameters = "query=dog"; // Initialize the CURL library $cURL = curl_init(); // Set the URL to execute curl_setopt($cCURL, CURLOPT_URL, "http://www.mywebserver.com/mysearch.php"); // Set options curl_setopt($cCURL, CURLOPT_HEADER, 1); curl_setopt($cCURL, CURLOPT_RETURNTRANSFER, 1); curl_setopt($cCURL, CURLOPT_POST, 1); curl_setopt($cCURL, CURLOPT_POSTFIELDS, $strParameters); curl_setopt($cCURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt(CURLOPT_USERPWD, "[myusername]:[myp***word]"); // Execute, saving results in a variable $strPage = curl_exec($cURL); // Close CURL resource curl_close($cURL); // This will print out the HTML contents echo($strPage); ?> |
![]() |
| Bookmarks |
| Thread Tools | |
| Display Modes | |
|
|