Question

I am trying to grab an image from an external server with fsockopen in PHP. I need to get the image data into a variable in BASE64 encoding in my code. The image is a .jpeg file-type and is a small image.

I could not find any answers on Google after some searching. So i wonder if it is even directly possible without weird workarounds?

Any help and/or suggestions is much appreciated!

Note that allow_url_fopen is disabled on my server due to security threats.

This is my current code:

$wn_server = "111.111.111.111";

$url = "GET /webnative/portalDI?action=getimage&filetype=small&path=".$tmp." HTTP/1.1\r\n";

$fp = fsockopen($wn_server,80,$errno,$errstr,15);
stream_set_timeout($fp, 30);

$imageDataStream = "";

if (!$fp) {
    echo "Error " . $errno . "(" . $errstr . ")";
} else {
    $out = $url;
    $out .= "Host: " . $wn_server . "\r\n";
    $out .= "Authorization: Basic " . $_SESSION['USER'] . "\r\n";
    $out .= "Connection: Close\r\n\r\n";
    $out .= "\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $imageDataStream .= fgets($fp, 128);
    }
    fclose($fp);
}
Was it helpful?

Solution

Do you mean something like this:

$ch = curl_init();

// Authentication
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); 
curl_setopt($ch, CURLOPT_USERPWD, 'username:password'); 

// Fetch content as binary data
curl_setopt($ch, CURLOPT_URL, $urlToImage);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// Fetch image data
$imageData = curl_exec($ch);

curl_close($ch);

// Encode returned data with base64
echo base64_encode($imageData);

OTHER TIPS

Try the follwoing

header('Content-Type: image/png');
echo $imageData;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top