Jun 15, 2020 5:05 PM

Getting response by URL in PHP using cURL

Getting response by URL in PHP using cURL

In this article I will give an example of how to get a response by URL in PHP using cURL. The response may be HTML, XML, JSON, etc. You can get the contents of the site for further parsing. You can also find out if the server is redirecting you to another URL and determine what the last URL will be.

function getResponseByUrl($url, $followLocation = false, $maxRedirects = 10, &$lastUrl = '')
{
    // Options
    $curlOptions = [
        CURLOPT_HEADER => false,
        CURLOPT_NOBODY => false,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 10,
    ];

    if ($followLocation) {
        $curlOptions[CURLOPT_FOLLOWLOCATION] = true;
        $curlOptions[CURLOPT_MAXREDIRS] = $maxRedirects;
    }

    // Initialization
    $ch = curl_init($url);

    // Set options
    curl_setopt_array($ch, $curlOptions);

    // Execute request
    $result = curl_exec($ch);

    // Get last URL
    $lastUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    // Close the resource
    curl_close($ch);

    return $result;
}

Let's check getting the response by URL:

print_r(getResponseByUrl('https://www.google.com'));

Now consider the redirection case:

print_r(getResponseByUrl('https://maps.google.com'));

You must set the $followLocation = true parameter to determine the last URL. You can also specify the maximum number of redirects using the $maxRedirects parameter. Let's determine the last URL from the previous example:

getResponseByUrl('https://maps.google.com', true, 10, $lastUrl);
print_r($lastUrl);

Other articles