从远程网站下载图像并显示使用

时间:2013-10-16 20:01:32

标签: php curl proxy

下载远程映像然后将其显示给用户的最快内存最有效的方法是什么? - 注意我不想保存它,我只是想把它传递给用户。

即。     用户访问www.website.com/image1.jpg

在后台我会使用类似于此的getFile脚本来检索文件,但是如何向用户显示这个,这是一种记忆效率高的方法吗?

function getUrl($url, $method='', $vars='', $fh = '') {
    $ch = curl_init();
    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
    }
    if ($fh != '')
    {
        curl_setopt($ch, CURLOPT_FILE, $fh);
    }

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies/cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies/cookies.txt');
    $buffer = curl_exec($ch);

    curl_close($ch);
    return $buffer;
}

1 个答案:

答案 0 :(得分:1)

这是:

function proxyImage( $fromHost, $path, $bufsize=4096 ) {
  $conn = fsockopen($fromHost,80);
  fwrite( $conn, "GET {$path} HTTP/1.0\r\n" );
  fwrite( $conn, "Host: {$fromHost}\r\n" );
  fwrite( $conn, "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0\r\n" );
  fwrite( $conn, "Connection: close\r\n" );
  fwrite( $conn, "\r\n" );

  $answer = ''; 
  while( !feof($conn) and !$bodystarted ) {
    $portion = fread( $conn, $bufsize );
    if( strpos($portion,"\r\n\r\n")!==false ) $bodystarted = true;
    $answer .= $portion;
  }
  list( $headers, $bodypart ) = explode( "\r\n\r\n", $answer, 2 );

  foreach( explode("\r\n",$headers) as $h )
    header($h);

  echo $bodypart;
  while( !feof($conn) )
    echo fread( $conn, $bufsize );
  fclose($conn);
}

proxyImage( 'www.newyorker.com', '/online/blogs/photobooth/NASAEarth-01.jpg' );