PHP - 使用fsockopen获取映像 [英] PHP - Get image with fsockopen

查看:232
本文介绍了PHP - 使用fsockopen获取映像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在PHP中使用 fsockopen 从外部服务器获取映像。我需要得到的图像数据变成BASE64编码的变量在我的代码。该图片是.jpeg文件类型,是一个小图片。

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!

请注意,由于安全威胁, allow_url_fopen 在我的服务器上已停用。

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

这是我当前的代码:

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

这篇关于PHP - 使用fsockopen获取映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆