Proxying Remote Images with PHP and cURL to avoid CORS issues

Are you tired of getting those pesky “Cross-Origin Resource Sharing” errors when trying to load images from a different website? Well, have no fear, because this PHP script is here! With this bad boy, you can proxy those images through your own server, and avoid those CORS errors like a boss. It’s like a superhero for your image loading needs. Say goodbye to those pesky error messages and hello to smooth image loading.

Download php Http proxy image (245 downloads )

It’s like a secret agent for your image loading needs. It utilises the power of cURL library to send HTTP requests in PHP and proxy those remote images through your own server, avoiding those CORS errors like a pro. It’s like having your own personal image butler, at your service.

The script starts off by setting the image’s URL to be proxied to the value of the “url” parameter in the GET request, just like passing a secret message. Then, it sets up the cURL session like a boss, initializing a new cURL handle and setting various options like a true hacker. If there’s an error with the request, it’ll output the error message and exit like a true professional. But if everything goes well, it’ll proceed to split the response into headers and image data like a true detective.

The headers are then sent to the browser using the “header()” function like a true agent and the image data is output to the browser like a true spy. It’s so easy, even a caveman could do it.

This script is perfect for situations where you want to proxy images through your own server, like adding a watermark to an image, or applying image processing on the image. So why wait? Give it a try and experience the magic for yourself! To use this script, simply call it in the format of “script.php?url=image_url”, like passing a secret code, with the desired image URL replacing “image_url”. The script should output the proxied image like a true master of disguise.

// The URL of the image you want to proxy
$url = $_GET['url'];
// Open the remote image
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if($response === false) {
echo 'Curl error: ' . curl_error($ch);
// Split the response into headers and content
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);
$data = substr($response, $header_size);
// Close the cURL handle
// Send the headers to the browser
foreach (explode("\r\n", $headers) as $header) {
// Output the image data
echo $data;

Was this helpful?

1 / 0

Leave a Reply 0

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