Instagram web api get: :ERR_BLOCKED_BY_RESPONSE
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?
Solution 1:
The same issue was reported recently on https://github.com/restyler/instagram-php-scraper.
Instagram now sets cross-origin-resource-policy: same-origin
if it doesn't like the "referer" which your browser sends to cdninstagram domain when loading image.
One of ways to mitigate this might be to create a simple image proxy which will work on your domain, download the image from instagram server to your server, and then output it to the browser.
Here is an example of CloudFlare image proxy:
https://gist.github.com/restyler/6c51e3ad20d7596e799d76e87cf93236
Not that efficient, but can be self-hosted, PHP implementation:
https://github.com/restyler/inwidget-proxified/blob/master/imgproxy.php
It might be a good idea to add additional caching layer on the proxy to reduce the amount of duplicate image requests to instagram cdn servers.
When you have your image proxy running, you just need to replace all instagram image srcs to the proxified versions.
Solution 2:
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.