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

Php 如何在HTML页面上显示来自FTP服务器的图像?,php,html,ftp,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"

我试图建立一个图像库来显示来自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>';
}
$content='';
$ftp_server=“255.122.111.111”;
$ftp\u user=“user\u name”;
$ftp\u pass=“密码”;
$conn_id=ftp_connect($ftp_server)或die(“无法连接到$ftp_server”);
if(@ftp\u login($conn\u id,$ftp\u user,$ftp\u pass)){
$content.=“
以$ftp\u用户@$ftp\u服务器的身份连接\n”; }否则{ $content.=“
无法以$ftp\u用户身份连接\n”; } $files=ftp\u nlist($conn\u id,$dir); foreach($files as$file\u name) { $content.=' '; }

要使图像显示在页面上,我需要做什么?

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

  • 将图像文件从FTP服务器获取为(二进制)字符串变量,如脚本中所示,然后
  • 正确准备图像标题,如下面的代码段所示,
    (另请参见)
  • 打印(二进制)图像字符串
在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];
}

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


正确的解决方案是通过Web服务器路由映像,不仅要隐藏凭据,还要隐藏映像的原始源

创建一个脚本(PHP或您使用的任何其他脚本)作为图像源(您将在
属性中使用它。该脚本将通过从FTP服务器下载来“生成”图像

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


图像需要托管在用户有权访问的地方(例如CDN),或者当您从ftp服务器检索图像时,您需要将其存储在web服务器中,并通过链接使其可用。您在该代码中尝试执行的操作(即直接从ftp服务器向最终用户提供图像)是不可能的(我知道)正确。因为授权标头没有随页面请求一起发送。相反,您应该将文件复制到本地计算机,然后在必要时显示它们。如果不是一吨,您可以在会话的TMP中保存它们,也可以将它们保存到磁盘。