Making cURL Requests, Retrieving, and Displaying Data in a Single PHP File
As a senior developer at Laravel Company (https://laravelcompany.com), I often need to fetch data from one site (Site B) and display it on another site (Site A). In this post, I’ll guide you through combining cURL requests, data retrieval, and display into a single PHP file.
Why Combine Everything?
There are several reasons why you might want to combine these operations. First, it makes your code more modular and reusable. You can drop this script into any project that needs to fetch data from Site B. Second, it simplifies your development environment by reducing the number of files involved.
The Original Attempt with Laravel
You've already experimented with a Laravel 4.0 approach using route filters and controllers. While this works, it involves multiple files and is tied to the Laravel framework. Let's refactor this into a standalone PHP script that can be used in any environment.
Route Filter (Refactored)
First, let's rewrite the route filter as a simple function in our new single file:
function validateKey($key)
{
if ($key != '**********')
return false;
return true;
}
cURL Request and Data Retrieval
Next, we'll implement the cURL request to fetch data from Site B. I've refactored your controller function into a standalone function that takes an API URL as input:
function fetchDataFromApi($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, "admin:**********");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the cURL request and capture the response
$body = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Decode the JSON response into a PHP array
return json_decode($body, TRUE);
}
Displaying the Data
Finally, let's create a function to display the fetched data in a nicely formatted manner. I've used your existing JSON structure as an example:
function displayDistributors($distributors)
{
echo "<table border='1'>";
foreach ($distributors['distributors'] as $distributor) {
echo "<tr>";
echo "<td>" . $distributor['name'] . "</td>";
echo "<td>" . $distributor['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
Putting It All Together
Now, let's combine these functions into a single PHP file. I've added error handling for the cURL request and used environment variables to determine which API URL to use:
<?php
function validateKey($key)
{
if ($key != '**********')
return false;
return true;
}
function fetchDataFromApi($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, "admin:**********");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the cURL request and capture the response
$body = curl_exec($ch);
// Close the cURL session
curl_close($ch);
// Decode the JSON response into a PHP array
return json_decode($body, TRUE);
}
function displayDistributors($distributors)
{
echo "<table border='1'>";
foreach ($distributors['distributors'] as $distributor) {
echo "<tr>";
echo "<td>" . $distributor['name'] . "</td>";
echo "<td>" . $distributor['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
$apiKey = $_GET['key']; // Get the API key from the query parameter
if (!validateKey($apiKey)) {
http_response_code(403);
die("Invalid API key");
}
$url = getenv('API_URL'); // Fetch the API URL based on environment variables
try {
$distributors = fetchDataFromApi($url);
displayDistributors($distributors);
} catch (Exception $e) {
http_response_code(500);
die("Error fetching data: " . $e->getMessage());
}
Using the Single PHP File
This script can now be placed anywhere in your project. To use it, simply include the file and pass an API key via a query parameter (e.g., `api.php?key=**********`). The script will validate the key, fetch data from Site B using cURL, parse the JSON response, and display the results in a table format.
Remember to replace the placeholders (**********) with your actual API key and URL. Also, ensure that your environment variables are correctly set up for the `API_URL`.
Conclusion
As you can see, it's possible to combine cURL requests, data retrieval, and display logic into a single PHP file. This approach promotes code reusability and simplifies your development process by reducing the number of files involved.
At Laravel Company (https://laravelcompany.com), we emphasize clean, modular, and maintainable code. By following this example, you can create scripts that are easy to understand, modify, and deploy across different projects.
Don't hesitate to reach out if you have any further questions or need assistance with your projects. We're always here to help!