CURL and PHP combined can be really useful for getting data from websites, connecting to APIs (such as the Google Analytics API) and so on. Sometimes you may need to connect to a website that is password protected so this post looks at how to pass the username and password with PHP and CURL.
If the following example, $url is the url to connect to and $username and $password contain your authorization details:
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_USERPWD, "$username:$password"); curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); $output = curl_exec($ch); $info = curl_getinfo($ch); curl_close($ch);
The "curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);" line is not actually necessary but it means the HTML from the web page returned goes into the $output variable rather than echoed out to standard output.
Likewise you don’t necessarily need to do "$info = curl_getinfo($ch);" but it does contain useful information about the HTTP status and so on. Doing print_r($info) from the above example on the script I used for writing and testing this post outputs the following:
Array ( [url] => http://www.testing.local/auth/ [content_type] => text/html;charset=UTF-8 [http_code] => 200 [header_size] => 208 [request_size] => 100 [filetime] => -1 [ssl_verify_result] => 0 [redirect_count] => 0 [total_time] => 0.022493 [namelookup_time] => 0.000279 [connect_time] => 0.000475 [pretransfer_time] => 0.000487 [size_upload] => 0 [size_download] => 732 [speed_download] => 32543 [speed_upload] => 0 [download_content_length] => 732 [upload_content_length] => 0 [starttransfer_time] => 0.022389 [redirect_time] => 0 )
Getting the http_code from the information is useful so you know if it successfully connected to the page before parsing any of the return data.