问题
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);
}
回答1:
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);
回答2:
Try the follwoing
header('Content-Type: image/png');
echo $imageData;
来源:https://stackoverflow.com/questions/19834971/php-get-image-with-fsockopen