Fetch an array of domain names from external php file

In this task, we will create a PHP script that fetches an array of domains from an external PHP file hosted on another server. We will utilize cURL for the HTTP request and handle the response using json_encode and json_decode. Additionally, we will implement error handling and exception handling to ensure robustness. We will also create the external PHP file that contains the array of domains.

External PHP File (domains.php)

First, we need to create the external PHP file that will return an array of domains in JSON format.

<?php
// domains.php
$domains = [
    "example.com",
    "test.com",
    "mywebsite.org"
];

// Return the domains as a JSON response
header('Content-Type: application/json');
echo json_encode($domains);
?>

Main PHP Script

Now, we will create the main PHP script that fetches the domains and checks if the current domain is in the array.

<?php
// Main PHP script

// Function to fetch domains from the external PHP file
function fetchDomains($url) {
    $ch = curl_init();
    
    // Set cURL options
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    // Execute cURL request
    $response = curl_exec($ch);
    
    // Error handling for cURL
    if (curl_errno($ch)) {
        throw new Exception('cURL Error: ' . curl_error($ch));
    }
    
    curl_close($ch);
    
    // Decode the JSON response
    $domains = json_decode($response, true);
    
    // Error handling for JSON decoding
    if (json_last_error() !== JSON_ERROR_NONE) {
        throw new Exception('JSON Decode Error: ' . json_last_error_msg());
    }
    
    return $domains;
}

// Main execution
try {
    $url = 'http://example.com/domains.php'; // Replace with the actual URL of the external PHP file
    $domains = fetchDomains($url);
    
    // Get the current domain
    $currentDomain = $_SERVER['HTTP_HOST'];
    
    // Check if the current domain is in the fetched array
    if (in_array($currentDomain, $domains)) {
        echo "Success: The current domain ($currentDomain) is in the list.";
    } else {
        echo "Error: The current domain ($currentDomain) is not in the list.";
    }
} catch (Exception $e) {
    // Handle exceptions
    echo "An error occurred: " . $e->getMessage();
}
?>

What we have done:

  1. External PHP File: The domains.php file returns a JSON-encoded array of domains.
  2. cURL Setup: The main script initializes a cURL session to fetch the domains.
  3. Error Handling: We handle potential errors from cURL and JSON decoding using exceptions.
  4. Domain Check: The script checks if the current domain is in the fetched array and displays an appropriate message.

This implementation ensures that the script is robust and can handle errors gracefully, providing a seamless experience for users.

Happy Coding.

Leave a Reply

Your email address will not be published. Required fields are marked *