Curl is a tool that allows us to send or receive data across the network via various protocols. One of its most common uses is on servers to make HTTP requests. Understanding how to work with curl is fundamental in web development, especially when we need to interact with APIs. One of the crucial things when making HTTP requests is being able to handle error statuses or success statuses correctly. PHP offers us the function `curl_getinfo()` to retrieve the status of an HTTP request.
[b]The solution to print the HTTP status code in PHP using curl[/b] is quite simple.
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, "http://example.com"); curl_exec($curl); if (!curl_errno($curl)) { $info = curl_getinfo($curl); echo 'Took ' . $info['total_time'] . ' seconds to send a request to ' . $info['url']; echo 'HTTP Status: ' . $info['http_code']; } else { echo 'Curl error: ' . curl_error($curl); } curl_close($curl);
To understand this code block, let’s break it down step by step:
First, we initialize a new curl session through `curl_init()`. This function returns a curl handle on success, FALSE on errors. We use curl_setopt to set some options for a cURL transfer. In our case, we set CURLOPT_URL to the URL we want to fetch.
After all our options are set, we use `curl_exec()` to execute the session. If the session is executed successfully, `curl_errno()` will return 0. In this particular case, we are only interested in output if there was no error. If there is no error, we use `curl_getinfo()` on our curl handle to retrieve session information. The information we are particularly interested in is the URL information and the total time of the transfer, and most importantly, the HTTP status code. If there was an error in the curl execution, we handle it in the else statement.
Understanding HTTP Status Codes
HTTP responses come with status codes that are indicative of the type of response. They are three-digit numbers where the first digit defines the class of the response. There are 5 classes of response:
- 1xx (Informational): The request was received, continuing process
- 2xx (Successful): The request was successfully received, understood, and accepted
- 3xx (Redirection): Further action needs to be taken in order to complete the request
- 4xx (Client Error): The request contains bad syntax or cannot be fulfilled
- 5xx (Server Error): The server failed to fulfill an apparently valid request
Understanding these codes helps in handling responses appropriately in our applications.
Some Common PHP curl Functions
PHP’s curl library has a ton of functions that make working with HTTP a breeze. Here are a few:
- curl_init: Initializes a new cURL session
- curl_setopt: Set an option on a cURL session
- curl_exec: Executes the given cURL session
- curl_getinfo: Retrieve information about a cURL session
- curl_errno: Returns the last error number
- curl_error: Returns a string containing the last cURL error