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 The image “http://localhost/xampp/site_name/image_handler.php?ID=d5xa24tdufoseg868r66yjz5sr19u41i” cannot be displayed because it contains errors. 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?
EDIT: Showing all code
<?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 OUTPUT
<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.">
If you do a
echo "test"prior to sending headers… things will go wrong.If you send an
echo "test"and your headers say that you’re sending an image… things will go wrong.Code is working.