我正试图弄清楚如何在PHP中将图像类型设置为变量。我需要从数据库中提取一个图像,找到它的图像类型并显示它。目前它只显示jpg。
上传代码为:
if(isset($_FILES['image']) && $_FILES['image']['tmp_name'] != '') {
$tempext = explode('.', $_FILES['image']['name']);
$tempext = strtolower($tempext[count($tempext) - 1]);
switch($tempext) {
case 'jpg':
case 'jpeg':
$ext = '.jpg';
break;
case 'gif':
$ext = '.gif';
break;
case 'png':
$ext = '.png';
break;
default:
$ext = false;
}
if($ext != false && move_uploaded_file($_FILES['image']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . '/img/profiles/' . $id . $ext)) {
$imagesuccess = chmod($_SERVER['DOCUMENT_ROOT'] . '/img/profiles/' . $id . $ext, 0644) ? 'yes' : 'no';
} else {
$imagesuccess = 'no';
}
}
编辑:
我已经取得了一些进展,主要是清理了一些愚蠢的错误,但我仍然没有看到任何图像。
以下是更新的交换机案例:
switch ($ext) {
case 'jpg':
case 'jpeg':
$ext = '.jpg';
break;
case 'gif':
$ext = '.gif';
break;
case 'png':
$ext = '.png';
}
和图像放置:
if(!file_exists($_SERVER['DOCUMENT_ROOT'] . $imgurl . 'profiles/' . $r['id'] . $ext)) {
echo '<img src="' . $imgurl . 'profiles/unavailable.gif" id="profile-big-img" />' . PHP_EOL;
} else {
echo '<p><img class="profileimg" src="' . $imgurl . 'profiles/' . $r['id'] . $ext . 'id="profile-big-img" alt="' . $r['forename'] . ' ' . $r['surname'] . (($r['course'] == 'graphics') ? ' Graphic Design' : ' Illustration') . '" /></p>' . PHP_EOL;
}
最可靠的方法是使用FileInfo。
当代码为位CREAMY时,很难跟踪问题;)
让我们首先从命令行检查您的图像有什么问题:
a) 开放式终端b) cd到带图像的目录(可能是weba目录)c) 在上运行(复制+过去+输入)
php -r ' $dh= opendir(".");while(($file=readdir($dh))!==false){ if(!is_dir($file)){ $tp=exif_imagetype($file);echo "$file: =====> $tp'n"; } } '
输出将是这样的:
...
error.JPG: =====> 2
features.JPG: =====> 2
kunfu_panda.jpg: =====> 2
.....
将代码与php提供的Imagetype常量进行比较。
这将是解决问题的第一步。
您可以使用pathinfo函数进行检查。我很确定它应该起作用。