【问题标题】:How do I set a header() and echo an image using CodeIgniter?如何使用 CodeIgniter 设置 header() 并回显图像?
【发布时间】:2009-12-10 16:01:52
【问题描述】:

我已经编写了一个方法来将 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() [&lt;a href='ref.outcontrol'&gt;ref.outcontrol&lt;/a&gt;]: failed to delete buffer. No buffer to delete.

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

【问题讨论】:

    标签: php codeigniter


    【解决方案1】:

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

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

    【讨论】:

    • 我不知道内容,但你肯定不想存储用户上传的文件名,然后在你的页面上回显。
    • 您能详细说明一下吗?还是你的意思是因为 XSS 漏洞?
    【解决方案2】:

    首先你需要在 on_clean() 之前启动 ob_start() 然后你需要像 header() 这样写。 以下是以下内容。

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

    ?> 试试这个,让我知道这是否有效,希望它会帮助你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-07
      • 2018-04-10
      • 2015-07-22
      • 2012-03-14
      • 2011-10-26
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      相关资源
      最近更新 更多