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

lb3vh1jj  于 4个月前  发布在  其他
关注(0)|答案(2)|浏览(53)

我写了一个方法来设置一个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(),它会说:
第一个月
我已经从这里复制了代码:http://www.phpriot.com/articles/images-in-mysql/8,如果这有帮助的话。

50pmv0ei

50pmv0ei1#

原来数据库中的图像已损坏,因此无法显示,因为我已将addslashes()添加到文件内容中(不知道为什么,似乎记得阅读它在对抗XSS漏洞时很有用)。
删除这意味着我有非腐败的图像存储,然后他们显示好。

yptwkmov

yptwkmov2#

首先,您需要在on_clean()之前启动ob_start(),然后您需要像header()一样编写。
下面是一个例子。

ob_start();
ob_clean();
header ("Content-type: image/png");

字符串

相关问题