【问题标题】:PHP - Get image with fsockopenPHP - 使用 fsockopen 获取图像
【发布时间】:2013-11-07 11:40:17
【问题描述】:

我正在尝试使用 PHP 中的 fsockopen 从外部服务器获取图像。我需要在我的代码中将图像数据放入 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);
}

【问题讨论】:

    标签: php image curl fetch fsockopen


    【解决方案1】:

    你的意思是这样的:

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

    【讨论】:

    • 谢谢。但是我打错了(我的错)。我的意思是说“fsockopen”而不是“cURL”
    • 如果 allow_url_fopen 被禁用,Afaik fsockopen 将不起作用。但是为什么不使用curl呢?
    • 这是因为我需要进行身份验证才能访问外部服务器上的图像。我已经用 Google 搜索了好几天,但找不到适用于 cURL 的示例。如果你有:那就太棒了!
    • 您必须如何进行身份验证?向我展示您到目前为止所拥有的脚本以及您的身份验证。我敢肯定在 cURL 中也有可能
    • 我收到了一个错误和一个通知:错误:Warning: curl_setopt() [function.curl-setopt]: Invalid curl configuration option in /var/www/html/apotek1/templates/local.inc.php on line 1216
    【解决方案2】:

    试试下面的

    header('Content-Type: image/png');
    echo $imageData;
    

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 2014-05-14
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 2013-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多