Ensuring Reliable Image Delivery with a Fallback Mechanism - CDN vs Server

Images play a crucial role in making web content more engaging and visually appealing. However, relying solely on a Content Delivery Network (CDN) to serve these images can sometimes lead to issues, such as images not loading correctly. This can happen if the CDN experiences problems or if an image is unavailable.
This blog post will walk you through a script that ensures a fallback mechanism for image delivery, making sure your images are always displayed correctly.
Fetching Images from the Database
The first step in our script is to retrieve all the images from the database. The images are stored in a variable called $imageAll, which is a placeholder for our image data. This step is crucial because it centralizes image management, making it easier to update and maintain consistency across your website.
# Get Images from database
$imageAll = '{apps_image_001}';
Cleaning and Splitting Image Paths
Next, we need to clean the image paths. Sometimes, the paths may have complex delimiters that make them hard to handle. Our script replaces these complex delimiters with simpler ones (commas) and then splits the string into an array of individual image paths.
# Replace the complex delimiter with a simpler one (comma)
$cleaned_paths = str_replace('//..*..//', ',', $imageAll);
# Split the string by commas
$image_paths = explode(',', $cleaned_paths);
Setting Up Base URLs
We define two base URLs in our script: one for the CDN and one for the original source. The CDN base URL helps deliver optimized images, while the original base URL acts as a fallback.
# CDN base URL
$cdn_base_url = "https://YOURCDNPROVIDER.com/?w=640&h=480&fit=cover&q=90&url=";
# Original base URL
$original_base_url = "https://mydomain.com/";
We suggest using either Cloudflare Image CDN (paid, recommended) or wsrv.nl (free but limited).
Trimming and Cleaning Image Paths
Before we can use the image paths, we need to ensure they are clean and free of any unwanted characters. This involves trimming any leading slashes or spaces from the paths.
# Initialize an empty string to hold the formatted output
$formatted_output = '';
# Loop through each image path and format the output
foreach ($image_paths as $path) {
$trimmed_path = trim($path);
# Ensure there are no unwanted characters or leading slashes
$trimmed_path = ltrim($trimmed_path, '/');
Validating CDN URLs
Our script constructs both the CDN and original URLs for each image. It then checks if the CDN URL is valid by fetching headers and looking for a "404 Not Found" error. If the CDN URL is valid, it uses that; otherwise, it falls back to the original URL.
# Construct the CDN URL and the original URL
$cdn_url = $cdn_base_url . $original_base_url . $trimmed_path;
$original_url = $original_base_url . $trimmed_path;
# Check if the CDN URL is valid by fetching headers
$is_valid_cdn = stripos($headers[0], "404 Not Found") === false;
# Use the CDN URL if valid, otherwise use the original URL
$final_url = $is_valid_cdn ? $cdn_url : $original_url;
if ($trimmed_path != '') {
$formatted_output .= '<a href="' . $final_url . '" target="_blank" rel="noopener">
<div style="background-image: url(' . $final_url . '); width: 225px; height: 169px; background-repeat: no-repeat; background-size: cover;"> </div>
</a>';
}
}
# Return the final formatted output
return $formatted_output;
Building the Final Output
The final part of our script generates the HTML needed to display the images. It ensures that each image is displayed correctly, even if the CDN fails. The script creates an HTML string that sets the image as a background, ensuring it fits the designated area.
if ($trimmed_path != '') {
$formatted_output .= '<a href="' . $final_url . '" target="_blank" rel="noopener">
<div style="background-image: url(' . $final_url . '); width: 225px; height: 169px; background-repeat: no-repeat; background-size: cover;"> </div>
</a>';
}
}
# Return the final formatted output
return $formatted_output;
Further notes...
Having a fallback mechanism for image delivery is essential to maintain a seamless user experience. The provided script ensures that your images are always displayed, even if the CDN fails.
If you have any questions about the script or need further assistance, feel free to ask.
Full code snippet
# Get Images from database
$imageAll = '{apps_image_001}';
# Replace the complex delimiter with a simpler one (comma)
$cleaned_paths = str_replace('//..*..//', ',', $imageAll);
# Split the string by commas
$image_paths = explode(',', $cleaned_paths);
# CDN base URL
$cdn_base_url = "https://YOURCDNPROVIDER.com/?w=640&h=480&fit=cover&q=90&url=";
# Original base URL
$original_base_url = "https://mydomain.com/";
# Initialize an empty string to hold the formatted output
$formatted_output = '';
# Loop through each image path and format the output
foreach ($image_paths as $path) {
$trimmed_path = trim($path);
# Ensure there are no unwanted characters or leading slashes
$trimmed_path = ltrim($trimmed_path, '/');
# Construct the CDN URL and the original URL
$cdn_url = $cdn_base_url . $original_base_url . $trimmed_path;
$original_url = $original_base_url . $trimmed_path;
# Check if the CDN URL is valid by fetching headers
$is_valid_cdn = stripos($headers[0], "404 Not Found") === false;
# Use the CDN URL if valid, otherwise use the original URL
$final_url = $is_valid_cdn ? $cdn_url : $original_url;
if ($trimmed_path != '') {
$formatted_output .= '<a href="' . $final_url . '" target="_blank" rel="noopener">
<div style="background-image: url(' . $final_url . '); width: 225px; height: 169px; background-repeat: no-repeat; background-size: cover;"> </div>
</a>';
}
}
# Return the final formatted output
return $formatted_output;