提问者:小点点

如何在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个答案

匿名用户

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

  • 从FTP服务器获取图像文件到一个(二进制)字符串变量,就像你的脚本一样,然后
  • 正确地准备图像标头,如下面的片段中所示,
    (也可参见stackoverflow的链接)
  • 打印(二进制)图像字符串。

在超文本标记语言代码中插入常用的标记。

跟随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];
}

匿名用户

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

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

创建一个脚本(PHP或您使用的任何其他脚本)作为图像源(您将在

实现这样一个脚本(比如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包装器。如果在Web服务器上不允许这样做,则必须使用FTP函数。请参见PHP:如何将文件从FTP服务器读取到变量中?

虽然要获得真正正确的解决方案,您应该提供一些与文件相关的HTTP头,如内容长度内容类型内容处置。为此,请参阅通过PHP脚本将文件从FTP服务器下载到带有内容长度标题的浏览器,而不将文件存储在web服务器上。

相关问题