Using cURL to get information regarding remote resources
A brief introduction into using cURL to get information about remote resources using PHP 7.2.4 and the php_curl 7.59.0 library
cURL is a powerful library and command-line tool which allows the transfer of data using different protocols, such as FTP, HTTP, HTTPS, IMAP etc etc. For a full list and more information please visit https://curl.haxx.se/.
In the demonstrations below I'll be using the curl library for PHP. To find out if the cURL extension is enabled in your PHP environment, you can simply run the
phpinfo() function and search for cURL, if enabled you should see something like the below;
curl cURL support => enabled cURL Information => 7.59.0 Age => 4 Features AsynchDNS => Yes CharConv => No Debug => No GSS-Negotiate => No IDN => Yes IPv6 => Yes krb4 => No Largefile => Yes libz => Yes NTLM => Yes NTLMWB => No SPNEGO => Yes SSL => Yes SSPI => Yes TLS-SRP => No HTTP2 => Yes GSSAPI => No KERBEROS5 => Yes UNIX_SOCKETS => No PSL => No Protocols => dict, file, ftp, ftps, gopher, http, https, imap, imaps, ldap, pop3, pop3s, rtsp, scp, sftp, smb, smbs, smtp, smtps, telnet, tftp Host => x86_64-pc-win32 SSL Version => OpenSSL/1.1.0h ZLib Version => 1.2.11 libSSH Version => libssh2/1.8.0
This also gives a quick readout of the protocols supported!
You can also use the PHP function
function_exists() to see if you can initialize cURL.
echo (function_exists("curl_init") ? "cURL Function Exists" : "cURL Function Doesn't Exist");
If one of these methods shows that the cURL library doesn't exist you will need to talk to your host or enable the curl extension yourself in your php.ini file.
Checking the http status code of a remote resource with cURL
In the below I'll show you to get an array of information regarding the cURL transfer, using this we can then see the outcome of the request and the
http_code. I've also set an option to let curl know that it should exclude the body from the output.
$ch = curl_init("http://url/to/remote/resource"); curl_setopt_array($ch, array( CURLOPT_NOBODY => true, ) ); curl_exec($ch); print_r(curl_getinfo($ch)); curl_close($ch); // Output Array ( [url] => http://url/to/remote/resource [content_type] => text/html; charset=UTF-8 [http_code] => 200 [header_size] => 199 [request_size] => 59 [filetime] => -1 [ssl_verify_result] => 20 [redirect_count] => 0 [total_time] => 0.421 [namelookup_time] => 0.015 [connect_time] => 0.109 [pretransfer_time] => 0.343 [size_upload] => 0 [size_download] => 0 [speed_download] => 0 [speed_upload] => 0 [download_content_length] => -1 [upload_content_length] => -1 [starttransfer_time] => 0.421 [redirect_time] => 0 [redirect_url] => [primary_ip] => x.x.x.x [certinfo] => Array ( ) [primary_port] => 443 [local_ip] => x.x.x.x [local_port] => 49600 )
If you're wanting a specific detail from the array, you can set a
CURLINFO option like the below which will only return that specific piece of data, the
http_code in this example.