web目录外的文件已损坏或被截断


File outside of web directory is corrupt or truncated

我正试图使用一个处理程序为web目录之外的文件提供服务,但遇到了一些问题。我想在处理程序中进行检查,并且需要能够运行查询,但一旦我添加了一行代码,而不是我所显示的代码,我就会收到错误图像"http://localhost/xampp/site_name/image_handler.php?ID=d5xa24tdufoseg868r66yjz5sr19u41i"无法显示,因为它包含错误。在firefox中,我检查了firebug中的控制台,它显示图像已损坏或被截断。然而,如果我留下我展示的基本代码,它只会为图像服务。有人知道为什么会这样吗?

编辑:显示所有代码

<?php
include("roc/include/connection.php");
$db = new PDOConnectionFactory();
$conn = $db->getConnection();
//prepare for utf8 characters
$sql = 'SET NAMES utf8';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
$sql = 'SET CHARACTER SET utf8';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
//**************************
if (! preg_match("/^[-a-z.-@,'s]*$/i",$_GET['ID']))
{
die('No illegal characters');
}
else
$empty=strlen($_GET['ID']);
if ($empty==0)
{
die('The text field cannot be empty');
}
else
{
$ID = $_GET['ID'];

if (strlen($_GET['ID'])>35){
exit("error");
}
}

$sql="SELECT file_name FROM video WHERE vid_id=?";
$stmt=$conn->prepare($sql);
$result=$stmt->execute(array($ID));
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$file_name = $row['file_name']."[img-004].jpg";
}
echo $path="/home/g/Desktop/processed/".$file_name."";

//check if image is readible and type
if (is_readable($path)) {
header('Content-Length: '.filesize($path)); // provide file size
header("Expires: -1");
header('Content-Type: image/jpeg');
$content=file_get_contents('/home/g/Desktop/processed/986861d331e8b4b4eacee5cb7aed494a[img-004].jpg');

}
else {
error_log("Can't serve image: $file_name");
}
?>

HTML输出

<img src="http://localhost/xampp/site_name/image_handler.php?ID=d5xa24tdufoseg868r66yjz5sr19u41i" alt="The image “http://localhost/xampp/site_name/image_handler.php?ID=d5xa24tdufoseg868r66yjz5sr19u41i” cannot be displayed because it contains errors.">

如果在发送标头之前执行echo "test"。。。事情会出问题的。

如果你发送了一个echo "test",并且你的标题说你正在发送一个图像。。。事情会出问题的。

代码正在运行

如果在图像数据中添加任何附加数据,您的图像就会损坏。如果您正在输出图像,最好不要回声图像以外的任何东西。唯一的办法可能是在图像上写下你想写的任何内容。您可以使用GD函数来执行此操作。还有一种方法,我可能会建议不要,你可以添加任何你喜欢的图片结尾,而不会出现错误。但这并不能保证。

附言:除了屏幕上的回声,你仍然可以运行更多的代码。

我不知道你要添加哪些代码来进行"检查",但根据手册:请记住,在发送任何实际输出之前,必须调用header(),无论是通过普通HTML标记还是空行在文件中,或从PHP

也许你最好把图像放在缓冲区:

<?php
  // Code that checks out whatever ..
  // more checks
  ob_start();
  myClass::renderPng(); //header("Content-Type: image/png"); in here
  $pngString = ob_get_contents();
  ob_end_clean();
?>

如果出现错误,您希望脚本输出什么?HTML?一个特殊的错误图像?

<?php
$content = readfile('/home/g/Desktop/processed/986861d331e8b4b4eacee5cb7aed494a[img-004].jpg');
// Did readfile succeed?
// Do db query.
// Do some other checks.
// Now output something to browser.
if ($are_we_okay == true) {
  header("Content-type: image/jpeg");
  echo $content;
} else {
  header("Content-type: text/html");
  echo "<b>Failed!</b>";
}
?>