15

I created a script that extracts photos in the gallery of a certain profile… Using instagram-web-api

Unfortunately now it no longer works, instagram does not return the image of the media This is the mistake: ERR_BLOCKED_BY_RESPONSE

Instagram has changed it’s CORS policy recently? How I can fix?

Vypertek
  • 159
  • 1
  • 1
  • 3
  • 1
    We need more information. Show us the API call that you are using, and the details of the CORS error, if this is what you suspect it is. – Cal McLean Apr 27 '21 at 14:27

8 Answers8

9

for php; I changed my img src to this and it works like charm! Assume that $image is the instagram image cdn link came from instagram page:

'data:image/jpg;base64,'.base64_encode(file_get_contents($image))

EDIT FOR BETTER SOLUTION

I have also noticed that, this method is causing so much latency. So I have changed my approach and now using a proxy php file (also mentioned on somewhere on stackoverflow but I don't remember where it is)

This is my common proxy file content:

<?php
function ends_with( $haystack, $needle ) {
    return substr($haystack, -strlen($needle))===$needle;
}

if (!in_array(ini_get('allow_url_fopen'), [1, 'on', 'true'])) {
   die('PHP configuration change is required for image proxy: allow_url_fopen setting must be enabled!');
}

$url = isset($_GET['url']) ? $_GET['url'] : null;


if (!$url || substr($url, 0, 4) != 'http') {
    die('Please, provide correct URL');
}

$parsed = parse_url($url);

if ((!ends_with($parsed['host'], 'cdninstagram.com') && !ends_with($parsed['host'], 'fbcdn.net')) || !ends_with($parsed['path'], 'jpg')) {
    die('Please, provide correct URL');
}

// instagram only has jpeg images for now..
header("Content-type: image/jpeg");
readfile( $url );

?>

Then I have just converted all my instagram image links to this (also don't forget to use urlencode function on image links):

./proxyFile.php?url=https://www.....

It worked like charm and there is no latency anymore.

littlealien
  • 429
  • 4
  • 11
8

now 100% working. You can try this.

corsDown

  • Using the Google translation vulnerability, it can display any image URL, with or without permission. All these processes are done by the visitor's IP and computer.
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 07 '22 at 02:57
  • 2
    This is awesome... Hats off to the person who realized this vulnerability! – Jester Jan 11 '22 at 21:46
  • Simply amazing. How is really that working? – Ömer Faruk Demirel Sep 14 '22 at 12:34
  • 1
    Can you explain how this JS file works? – Alex Dec 14 '22 at 11:38
  • 1
    @Alex it changes the host of the url. It replaces every "-" with "--", and every "." with "-" and also appends ".translate.goog" to the end, basically "media.example-site.com/image.jpg" becomes "media-example--site-com.translate.goog/image.jpg" – kess Jul 07 '23 at 13:39
3

I have the same problem, when I try to load a Instagram's pictures url (I tried with 3 IP addresses), I see this on the console:

Failed to load resource: net::ERR_BLOCKED_BY_RESPONSE

You can see it here, the Instagram image doesn't load (Actually, when I paste this url on google it works, but Instagram puts a timestamp on there pictures so, it's possible it won't work for you).

It's very recent, 3 days ago, it works with no issues.

<img src="https://scontent-cdt1-1.cdninstagram.com/v/t51.2885-19/s320x320/176283370_363930668352575_6367243109377325650_n.jpg?tp=1&_nc_ht=scontent-cdt1-1.cdninstagram.com&_nc_ohc=nC7FG1NNChYAX8wSL7_&edm=ABfd0MgBAAAA&ccb=7-4&oh=696d56547f87894c64f26613c9e44369&oe=60AF5A34&_nc_sid=7bff83">
Lior
  • 31
  • 1
  • 2
0

The answer is as follows. You can use the imgproxy.php file. You can do it like this:

echo '<a href="' . $item->link . '" class="image" target="_blank">
         <span style="background-image:url(imgproxy.php?url=' . urlencode($thumbnail) . ');">&nbsp;</span>
      </a>';
Kuubs
  • 1,300
  • 1
  • 14
  • 42
0

Using PHP u can grab content of the image and show it in php file as an image by setting the header:

<?php
$img_ctn = file_get_contents("https://scontent-ber1-1.cdninstagram.com/v/......");
header('Content-type: image/png');
echo $img_ctn;
Abdes
  • 926
  • 1
  • 15
  • 27
0

You can display the Image using Base64 encoded.

Base64 func based on @abubakar-ahmad answer.

JavaScript:

export const checkUserNameAndImage = (userName) => {
/* CALL THE API */
return new Promise((resolve, reject) => {
fetch(`/instagram`, {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ userName }),
})
  .then(function (response) {
    return response.text();
  })
  /* GET RES */
  .then(function (data) {
    const dataObject = JSON.parse(data);
    /* CALL BASE64 FUCNTION */
    toDataUrl(dataObject.pic, function (myBase64) {
      /* INSERT TO THE OBEJECT BASE64 PROPERTY */
      dataObject.picBase64 = myBase64;
      /* RETURN THE OBJECT */
      resolve(dataObject);
    });
  })
  .catch(function (err) {
    reject(err);
  });
});
};

Base64 func:

function toDataUrl(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
  callback(reader.result);
};
   reader.readAsDataURL(xhr.response);
  };
 xhr.open("GET", url);
 xhr.responseType = "blob";
 xhr.send();
}

Now, instead of using the original URL, use the picBase64 property:

<image src={data.picBase64)}/>
Ori
  • 160
  • 1
  • 10
0

I have built a simple PHP based media proxy to minimize copy&paste. https://github.com/skmachine/instagram-php-scraper#media-proxy-solving-cors-issue-neterr_blocked_by_response

Create mediaproxy.php file in web server public folder and pass instagram image urls to it.

<?php
use InstagramScraper\MediaProxy;

// use allowedReferersRegex to restrict other websites hotlinking images from your website
$proxy = new MediaProxy(['allowedReferersRegex' => "/(yourwebsite\.com|anotherallowedwebsite\.com)$/"]);

$proxy->handle($_GET, $_SERVER);
skn1
  • 1
0

I was too lazy to do the suggested solutions and since i had a nodejs server sending me urls i just wrote new functions to get the images, convered them to base64 and sent them to my frontend. Yes it's slower and heavier but it gets the job done for me since i don't have a huge need for performance.

Fetch and return base64 from url snippet

const getBase64Image = async (url) => {
  return new Promise((resolve, reject) => {
    // Safety net so the entire up
    // doesn't fucking crash
    if (!url) {
      resolve(null);
    }
    https
      .get(url, (resp) => {
        resp.setEncoding("base64");
        body = "data:" + resp.headers["content-type"] + ";base64,";
        resp.on("data", (data) => {
          body += data;
        });
        resp.on("end", () => {
          resolve(body);
        });
      })
      .on("error", (e) => {
        reject(e.message);
      });
  });
};

You don't need any external modules for this.

Dharman
  • 30,962
  • 25
  • 85
  • 135
omkobass
  • 194
  • 1
  • 10