从数据库中获取图像,然后在 url 中写入文件


Grab image from database and then write file in url

我正在开发我的游戏网站,但为了让Facebook API正常工作,我必须创建一个新的脚本,可以根据游戏的ID抓取缩略图。这就是这个脚本试图做的事情,但我收到这个错误。

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

想知道你们中是否有人可以帮助我解决这个问题。

<?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);
?>

你不需要httphttps就可以让 PHP readfile工作......实际上,使用HTTP将使加载这些图像变得slower....

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

应该工作正常。

这是 10 行脚本的版本

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'] );

您需要像这样实际设置 mime 类型的标头:

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

然后看看@Baba的答案。