我正在尝试从外部服务器中获取图像 fsockopen 在PHP中。我需要将图像数据在我的代码中编码的base64中的变量中。图像是.jpeg文件类型,是一个小图像。

搜索后,我在Google上找不到任何答案。所以我想知道没有怪异的解决方法是否直接可能直接可能?

非常感谢任何帮助和/或建议!

注意 allow_url_fopen 由于安全威胁,在我的服务器上被禁用。

这是我当前的代码:

$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);
}
有帮助吗?

解决方案

你的意思是这样:

$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);

其他提示

尝试follwoing

header('Content-Type: image/png');
echo $imageData;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top