File outside of web directory is corrupt or truncated
<p>I am trying to use a handler to serve a file that is outside of my web directory and I am having some issues. I want to do checks in the handler and need to be able to run a query but as soon as I add a line of code other than what I have shown, I get the error <strong>The image “http://localhost/xampp/site_name/image_handler.php?ID=d5xa24tdufoseg868r66yjz5sr19u41i” cannot be displayed because it contains errors</strong>. In firefox I checked the console in firebug and it says image is corrupt or truncated. However if I leave the base code I have shown it just serves the image. Anyone know why this could be?</p>

<p><strong>EDIT: Showing all code</strong></p>

<pre><code>&lt;?php
include("roc/include/connection.php");
$db = new PDOConnectionFactory();
$conn = $db-&gt;getConnection();

//prepare for utf8 characters
$sql = 'SET NAMES utf8';
$stmt = $conn-&gt;prepare($sql);
$result=$stmt-&gt;execute();

$sql = 'SET CHARACTER SET utf8';
$stmt = $conn-&gt;prepare($sql);
$result=$stmt-&gt;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'])&gt;35){
exit("error");
}

}


$sql="SELECT file_name FROM video WHERE vid_id=?";
$stmt=$conn-&gt;prepare($sql);
$result=$stmt-&gt;execute(array($ID));

while($row = $stmt-&gt;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");
}

?&gt;
</code></pre>

<p><strong>HTML OUTPUT</strong></p>

<pre><code>&lt;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."&gt;
</code></pre>
