如何在HTML页面上显示来自FTP服务器的图像?

时间:2016-01-20 07:55:08

标签: php html ftp

我尝试为FTP服务器显示图像构建图库。 FTP服务器需要密码验证。我扫描文件成功,但图像不显示在页面上,点击参考页面询问用户名和密码。

$content = '';
$ftp_server = "255.122.111.111";
$ftp_user = "user_name";
$ftp_pass = "password";

$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server"); 

if (@ftp_login($conn_id, $ftp_user, $ftp_pass)) {
    $content .= "<br />Connected as $ftp_user@$ftp_server\n";
} else {
    $content .= "<br />Couldn't connect as $ftp_user\n";
}

$files = ftp_nlist($conn_id, $dir);
foreach($files as $file_name)
{
    $content.=  '
         <div>
            <a href="ftp://'.$ftp_server.'/'.$file_name.'">
            <img src="ftp://'.$ftp_server.'/'.$file_name.'"    width="150" height="150">
           </a>
         </div>';
}

我需要做什么才能在页面上显示图像?

2 个答案:

答案 0 :(得分:1)

您可以根据要求准备一个脚本(例如 getimage.php )......

  • 将来自FTP服务器的图像文件转换为(二进制)字符串变量,就像在脚本中一样,然后
  • 正确准备图片标题,如下面的代码段所示,(另请参阅this link from stackoverflow
  • 打印(二进制)图像字符串。

在HTML代码中插入常用的 标记。

关注 getimage.php 脚本的片段。手动提取图像类型:

// Get the image contents from FTP server into $binary
// $binary contains image text now
// Then ....

header('Content-type: ' . image_file_type_from_binary($binary));
echo $binary;

function image_file_type_from_binary($binary) {
  if (
    !preg_match(
        '/\A(?:(\xff\xd8\xff)|(GIF8[79]a)|(\x89PNG\x0d\x0a)|(BM)|(\x49\x49(?:\x2a\x00|\x00\x4a))|(FORM.{4}ILBM))/',
        $binary, $hits
    )
  ) {
    return 'application/octet-stream';
  }
  $type = array (
    1 => 'image/jpeg',
    2 => 'image/gif',
    3 => 'image/png',
    4 => 'image/x-windows-bmp',
    5 => 'image/tiff',
    6 => 'image/x-ilbm',
  );
  return $type[count($hits) - 1];
}

答案 1 :(得分:0)

在网络服务器上打开的FTP连接无论如何都无法帮助webbrowser对FTP服务器进行身份验证。

正确的解决方案是通过您的网络服务器路由图像,不仅隐藏凭证,还隐藏图像的原始来源。

创建一个充当图像源的脚本(PHP或您使用的任何其他脚本)(您将在<img src=...>属性中使用它。脚本将通过从FTP服务器下载来“生成”图像。 / p>

实现这样一个脚本(比如说image.php)最简单的方法是:

<?

header('Content-Type: image/jpeg');

echo file_get_contents('ftp://username:password@ftp.example.com/path/image.jpg');

然后你在HTML中使用它:

<a src="image.php" />

(假设image.php与HTML页面位于同一文件夹中)

该脚本使用FTP URL wrappers。如果您的Web服务器上不允许这样做,您必须更加努力地使用FTP功能。看到 PHP: How do I read a file from FTP server into a variable?

虽然对于一个非常正确的解决方案,您应该提供一些与该文件相关的HTTP标头,例如Content-LengthContent-TypeContent-Disposition。为此,请参阅Download file via PHP script from FTP server to browser with Content-Length header without storing the file on the web server