Pergunta

Estou tentando pegar uma imagem de um servidor externo com fsockopen em php. Preciso colocar os dados da imagem em uma variável na codificação Base64 no meu código. A imagem é um tipo de arquivo .jpeg e é uma imagem pequena.

Não consegui encontrar nenhuma resposta no Google após algumas pesquisas. Então, eu me pergunto se é mesmo diretamente possível sem soluções alternativas estranhas?

Qualquer ajuda e/ou sugestões é muito apreciada!

Observe que allow_url_fopen está desativado no meu servidor devido a ameaças à segurança.

Este é o meu código atual:

$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);
}
Foi útil?

Solução

Você quer dizer algo assim:

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

Outras dicas

Experimente o seguinte

header('Content-Type: image/png');
echo $imageData;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top