在CakePHP中将标题设置为内容图像

在CakePHP中将标题设置为内容图像,cakephp,Cakephp,我正在控制器中编写一个操作,在特定情况下,我希望直接输出原始图像数据,并希望设置适当的标题内容类型。然而,我认为CakePHP已经在前面设置了头(我将render设置为false) 有没有办法绕过这个问题?谢谢 如果render为false,则cake不会发送头 您可以在这里使用普通的ol'php 巴布亚新几内亚: JPEG: 巴布亚新几内亚: 它不是$this->render(false),而是$this->autoRender=false除非您回显某些内容,否则不会在控制器操作中发送头。如前

我正在控制器中编写一个操作,在特定情况下,我希望直接输出原始图像数据,并希望设置适当的标题内容类型。然而,我认为CakePHP已经在前面设置了头(我将render设置为false)


有没有办法绕过这个问题?谢谢

如果render为false,则cake不会发送头

您可以在这里使用普通的ol'php

巴布亚新几内亚:

JPEG:

巴布亚新几内亚:


它不是
$this->render(false)
,而是
$this->autoRender=false
除非您回显某些内容,否则不会在控制器操作中发送头。

如前所述,当
render
false
时,CakePHP不会发送头。不过要注意,任何执行“echo”的代码都会发送头(除非您使用的是输出缓冲)。这包括来自PHP的消息(警告等)

发送文件有多种方式,但有两种基本方式:

使用普通PHP发送文件 使用X-Sendfile并让Web服务器为该文件提供服务 第一个函数在发送数据时占用一个PHP进程/线程,不支持范围请求或其他高级HTTP功能。因此,这只能用于小文件或非常小的站点

使用X-Sendfile,您可以获得所有这些信息,但您需要知道哪个web服务器正在运行,甚至可能需要更改配置。特别是在使用lighttp或nginx时,这在性能方面确实是值得的,因为这些web服务器非常擅长从磁盘提供静态文件

这两个函数都支持不在Web服务器文档根目录中的文件。在nginx中有所谓的“内部位置”(http://wiki.nginx.org/HttpCoreModule#internal). 这些可与
X-Accel-Redirect
-标题一起使用。甚至速率抖动也是可能的,看看吧


如果使用apache,则有modxsendfile,它实现了第二个函数所需的功能。

奇怪,我先调用$this->render(false),然后尝试设置头。在此期间,我正在调用一个使用imagejpeg(..)的库。这就是CakePHP声明正在设置头的地方。但是,当我试图打印出没有标题的输出时,它无法正确渲染。
header('Content-Type: image/gif');
readfile('path/to/myimage.gif');
header('Content-Type: image/jpeg');
readfile('path/to/myimage.jpg');
header('Content-Type: image/png');
readfile('path/to/myimage.png');
function send_file_using_plain_php($filename) {
    // Avoids hard to understand error-messages
    if (!file_exists($filename)) {
        throw RuntimeException("File $filename not found");
    }

    $fileinfo = new finfo(FILEINFO_MIME);
    $mime_type = $fileinfo->file($filename); 
    // The function above also returns the charset, if you don't want that:
    $mime_type = reset(explode(";", $mime_type));
    // gets last element of an array

    header("Content-Type: $mime_type");
    header("Content-Length: ".filesize($filename));
    readfile($filename);
}
// This was only tested with nginx

function send_file_using_x_sendfile($filename) {
    // Avoids hard to understand error-messages
    if (!file_exists($filename)) {
        throw RuntimeException("File $filename not found");
    }

    $fileinfo = new finfo(FILEINFO_MIME);
    $mime_type = $fileinfo->file($filename); 
    // The function above also returns the charset, if you don't want that:
    $mime_type = reset(explode(";", $mime_type));
    // gets last element of an array

    header("Content-Type: $mime_type");
    // The slash makes it absolute (to the document root of your server)
    // For apache and lighttp use:
    header("X-Sendfile: /$filename");
    // or for nginx: header("X-Accel-Redirect: /$filename");

}