how to call url of any other website in php

how to call url of any other website in php

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How to Call URLs of Any Other Website in PHP

When you need your PHP application to interact with external resources, whether it's fetching JSON data from a third-party API or scraping content from a public webpage, the core mechanism remains consistent: use an HTTP client. While older tutorials often suggest using file_get_contents() for its simplicity, that function is increasingly discouraged in modern development due to poor error handling, lack of streaming support, and security concerns regarding remote file inclusion (RFI). The robust standard for making outbound requests today is the Guzzle HTTP library or leveraging built-in cURL capabilities directly.

Using Guzzle for Modern Request Handling

Guzzle is arguably the most popular HTTP client for PHP because it abstracts away the complexities of underlying sockets and provides a clean, fluent interface. To get started, you must first install the library via Composer:

composer require guzzlehttp/guzzle

Once installed, instantiation is straightforward. You create a Client instance and then use the request() method to send GET or POST calls. Here is a practical example of fetching data from an external URL:

use GuzzleHttp\Client;

$client = new Client();

try {
    $response = $client->get('https://api.example.com/data', [
        'headers' => [
            'User-Agent' => 'MyApp/1.0', // Essential for compliance with many APIs
            'Accept' => 'application/json'
        ],
        'query' => ['key' => 'value']
    ]);

    $data = json_decode((string) $response->getBody(), true);

    if ($response->getStatusCode() === 200) {
        // Process the data
        echo "Success: " . json_encode($data);
    } else {
        throw new \Exception("Request failed with status " . $response->getStatusCode());
    }
} catch (\GuzzleHttp\Exception\RequestException $e) {
    // Handle network errors, timeouts, or HTTP errors gracefully
    echo "Error: " . $e->getMessage();
}

This approach offers significant advantages over raw file functions. The try-catch block captures exceptions thrown by Guzzle when a connection times out or the server returns an error status code (like 404 or 500). Furthermore, you can easily configure timeouts and retries within the client options to prevent your application from hanging indefinitely on slow networks.

Leveraging cURL for Fine-Grained Control

If you cannot use Composer or prefer not to add a dependency, PHP's native curl extension provides powerful alternatives. The curl_init() function starts a new session, and subsequent functions configure the request before execution with curl_exec().

$ch = curl_init('https://example.com');

// Set options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return response as string instead of outputting directly
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Redirects are handled automatically
curl_setopt($ch, CURLOPT_TIMEOUT, 10);          // Prevent hanging requests
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true); // Enforce SSL certificate validation

$response = curl_exec($ch);

if ($response === false) {
    $error = curl_error($ch);
    echo "cURL Error: " . $error;
} else {
    echo "Response: " . $response;
}

curl_close($ch);

One critical detail when using cURL is handling SSL verification. Setting CURLOPT_SSL_VERIFYPEER to true is a security best practice, ensuring that the certificate presented by the external server belongs to the expected domain. Skipping this check makes your application vulnerable to Man-in-the-Middle (MitM) attacks.

Security and Best Practices

Regardless of the client you choose, several architectural considerations apply to any external request. First, always validate input before constructing URLs to prevent open redirect vulnerabilities or malformed requests. Second, never rely solely on HTTP status codes; always decode the response body and verify its structure if you expect JSON.

For complex applications requiring robust state management, session handling, or integration with Laravel's ecosystem, utilizing a dedicated HTTP client package like Guzzle is often superior. If you are building a larger scale application and need comprehensive documentation on setting up secure API integrations, checking resources like LaravelCompany can provide further context on securing your backend interactions.

Our network