Alice
Alice

Reputation: 424

Grab image from database and then write file in url

I'm working on my game website, but in order to get the Facebook API to work right, I have to make a new script that can grab a thumbnail based off of the game's ID. This is what this script is trying to do but I get this error.

Warning: readfile(localhost/thumbs/6c9e40d35e8cf07e.png) [function.readfile]: failed to open stream: No such file or directory in B:\home\home\thumb.php on line 22

I was wondering if any of you could help me with this.

<?php
require_once "functions.php";
if(!isset($_REQUEST['t'])){
die("No ID Defined");
}
$t = $_REQUEST['t'];
$t = intval($t);
connect();
$fetch = fetchdata("select * from `games` where id = $t");
$thumb = $fetch{'thumb'};
$file = "/thumbs/$thumb";
$filename = basename($file);
$file_extension = strtolower(substr(strrchr($filename,"."),1));
switch( $file_extension ) {
    case "gif": $ctype="image/gif"; break;
    case "png": $ctype="image/png"; break;
    case "jpeg":
    case "jpg": $ctype="image/jpg"; break;
    default:
}
header($ctype);
readfile($_SERVER['HTTP_HOST'].'/thumbs/'.$thumb);
?>

Upvotes: 0

Views: 129

Answers (2)

Baba
Baba

Reputation: 95161

you don't need http or https for PHP readfile to work ... in fact using http would make it slower to load those images ....

 readfile('/thumbs/'.$thumb); //or
 readfile(PATH_TO_LOCAL_DIR. '/thumbs/'.$thumb);

Should work fine.

This is a version of your script in 10 lines

require_once "functions.php";
if (! isset ( $_REQUEST ['t'] )) {
    die ( "No ID Defined" );
}
connect ();
$fetch = fetchdata ( sprintf("select * from `games` where id = '%d'",$_REQUEST ['t']) );
if(!is_file("thumbs/" . $fetch ['thumb'] ))
    die("Thum Does not exist");
header ( "Content-type: ", image_type_to_mime_type ( exif_imagetype ( $fetch ['thumb'] ) ) );
readfile ( "thumbs/" . $fetch ['thumb'] );

Upvotes: 2

hakre
hakre

Reputation: 198247

You need to actually set the mime-type header like this:

header(sprintf("Content-Type: %s", $ctype));

Then see @Baba's answer.

Upvotes: 0

Related Questions