【问题标题】:Set the header( content-type: image/<ANY IMG FORMAT>)设置标题(内容类型:image/<ANY IMG FORMAT>)
【发布时间】:2014-05-23 02:20:50
【问题描述】:

处理我显示的图像的 php 文件只允许一种图像格式,.jpg、.png、.bmp 等,但不是全部。 imageName 存储存储在数据库中的图像的文件名,包括其格式。这是我的代码,到目前为止它还不能工作,我不确定这是否允许。你能帮我解决它吗?

$con = mysqli_connect("localhost","root","","tickets");
$ticket = 109;
$result = mysqli_query($con,"SELECT image, imageName FROM tix WHERE tktNum=$ticket");


while($row = mysqli_fetch_array($result))
{
    $image = $row['image'];
    $imageName = $row['imageName'];
    $format = substr( $imageName, -3 ); //gets the last 3 chars of the file name, ex: "photo1.png" gets the ".png" part
    header('content-type: image/' . $format);
}

【问题讨论】:

标签: php http-headers substr


【解决方案1】:

我只是用这个,只是表明它是一个图像,但没有指定图像类型。

header("Content-type: image");

无论文件类型如何,它似乎都可以正常工作。我使用 IE、Firefox、Safari 和 Android 浏览器进行了测试。

【讨论】:

  • image/* 不同,image 会在某些浏览器中内嵌图像,否则这些浏览器会以文件下载的形式提供 Content-type image/* 的图像。
【解决方案2】:

解决方案是读取文件并确定它是哪种图像,并根据它发送适当的标题。

$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));

switch( $file_extension ) {
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpeg"; break;
    case "svg": $ctype="image/svg+xml"; break;
    default:
}

header('Content-type: ' . $ctype);

【讨论】:

  • @user3663049 很高兴听到这个消息,请接受并投票赞成这个答案,以便其他人知道它已经解决,以便他们可以使用这个答案
  • 请在此处提供答案,而不仅仅是提供答案的链接。
猜你喜欢
  • 2018-11-18
  • 2019-08-22
  • 1970-01-01
  • 2019-07-20
  • 1970-01-01
  • 1970-01-01
  • 2019-03-28
  • 2013-04-18
  • 2021-12-03
相关资源
最近更新 更多