如何使用 CodeIgniter 设置 header() 并回显图像?

问题描述 投票:0回答:2

我编写了一个方法来将 header() 设置为存储在数据库中的上传的适当文件类型,然后我想 echo() 该文件。

在控制器内部方法如下:

function view_upload( $id = 0 ) {

    $id = $this->db->escape( $id );

    $query = $this->db->query( "SELECT file_type FROM media WHERE id = $id" )->row();
    $query2 = $this->db->query( "SELECT file FROM media WHERE id = $id" )->row();       

    header("Content-type: ".$query->file_type);
    //die( "moo" );
    echo( $query2->file );
}

奇怪的是,一旦我设置了 header() ,该方法的其余部分似乎就被忽略了,例如,如果我取消注释 die() 语句,它不会死,也不会回显图像。如果我删除 header() 调用,我会看到原始上传 blob 呈现在屏幕上..

这与 CodeIgniter 有关还是我犯了 PHP 错误?

编辑:

我已经更改了该函数并将其放在 CodeIgniter 之外的单独文件中,但如果我浏览到它并传入 $id,它仍然不显示图像...

<?php
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
    //connect to the db
    $link = mysql_connect("localhost", "user", "pass") or die("Could not connect: " . mysql_error());

    // select our database
    mysql_select_db("database") or die(mysql_error());

    $id = $_GET['id'];

    // get the file from the db
    $sql = "SELECT file FROM media WHERE id=$id";
    // the result of the query
    $result = mysql_query("$sql") or die("Invalid query: " . mysql_error());

    // get the file_type from the db
    $sql = "SELECT file_type FROM media WHERE id=$id";
    // the result of the query
    $result2 = mysql_query("$sql") or die("Invalid query: " . mysql_error());

    // set the header for the image
    //ob_clean();
    //die( mysql_result($result, 0) );
    //header('Content-type:'.mysql_result($result2, 0));
    header('Content-type: image/png');
    //ob_clean();
    echo mysql_result($result, 0);

    // close the db link
    mysql_close($link);
}
else {
    echo 'Please use a real id number';
}
?>
两个 $result 上的

die() 产生了我所期望的结果,但它没有在浏览器中显示页面。如果我再次添加 ob_clean() 它会说:

ob_clean() [<a href='ref.outcontrol'>ref.outcontrol</a>]: failed to delete buffer. No buffer to delete.

我从这里复制了代码:http://www.phpriot.com/articles/images-in-mysql/8如果这有帮助..

php codeigniter
2个回答
1
投票

事实证明,数据库中的图像已损坏,因此无法显示,因为我在文件内容中添加了addslashes()(不太清楚为什么,似乎记得阅读它对于对抗XSS漏洞很有用)。

删除它意味着我存储了未损坏的图像,然后它们显示正常。


1
投票

首先你需要在

ob_start()
之前开始
on_clean()
然后你需要像
header()
那样写。

以下是。

ob_start();
ob_clean();
header ("Content-type: image/png");
© www.soinside.com 2019 - 2024. All rights reserved.