user1346107
user1346107

Reputation: 157

file_get_contents is not able to read image from facebook image url

I have got an image url from facebook:

https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/s720x720/156510_443901075651849_1975839315_n.jpg

I need to save this in my local. when i used file_get_contents it gave error failed to open stream. when i open image in the browser it is showing fine. I just understand how to do it.

infact i used curl in the following way and got no response at all

$url = https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/s720x720/156510_443901085651849_1975839315_n.jpg;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);
$filename = 'ex'.$src['photo_id'].'.jpg';
$imgRes = imagecreatefromstring($response);
imagejpeg($imgRes, $filename, 70);

header("Content-Type: image/jpg");
imagejpeg($imgRes, NULL, 70);

Upvotes: 1

Views: 5763

Answers (3)

Matt Humphrey
Matt Humphrey

Reputation: 1554

It's because you are requesting an secure URL and your server probably doesn't support it without configuration. You can either use CURL to request the URL with a valid certificate or just try and request it without SSL:

<?php

$file = 'http://url/to_image.jpg';
$data = file_get_contents($file);

header('Content-type: image/jpg');
echo $data;

Upvotes: 3

Repox
Repox

Reputation: 15476

You need to tell cURL that you don't wan't to verify the SSL connection.

The following is tested and works.

$url = "https://******";


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // ignore SSL verifying
curl_setopt($ch, CURLOPT_HEADER, 0);
$response = curl_exec($ch);
curl_close($ch);

header("Content-Type: image/jpg");
echo $response;

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

It's most likely that Facebook requires a valid User-Agent string and is denying your request because file_get_contents doesn't send one when accessing remote files.

You could use this:

if( $f = fsockopen($host="fbcdn-sphotos-e-a-.akamaihd.net",80)) {
    fputs($f,"GET /hphotos-ak-prn1/........ HTTP/1.0\r\n"
            ."Host: ".$host."\r\n"
            ."User-Agent: My Image Downloader\r\n\r\n");
    $ret = "";
    $headers = true;
    while(!feof($f)) {
        $line = fgets($f);
        if( $headers) {
            if( trim($line) == "") $headers = false;
        }
        else $ret .= $line;
    }
    fclose($f);
    file_put_contents("mylocalfile.png",$ret);
}

Upvotes: 0

Related Questions