gpt4 book ai didi

php - 上传 JPG 但不是 jpg

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:34:54 32 4
gpt4 key购买 nike

我有一段代码可以上传图像并创建缩略图,只要扩展名是小写的 jpg,但如果是大写的 JPG,它就不会上传图像。当我重命名图像时,例如example.JPG 到 example.jpg,它会上传。但是 example.JPG 不会上传,我也没有收到任何错误。这对我来说没有任何意义。有人对此有解释吗?这是我的代码:

<?php
function createThumbnail($filename) {
require 'config.php';

if(preg_match('/[.](jpg)$/', $filename)) {
$im = imagecreatefromjpeg($filename.$path_to_image_directory);
} else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}

$ox = imagesx($im);
$oy = imagesy($im);

$nx = $final_width_of_image;
$ny = $final_height_of_image;

$nm = imagecreatetruecolor($nx, $ny);

imagecopyresampled($nm, $im, 0,0,0,0,$nx,$ny,$ox,$oy);

if(!file_exists($path_to_thumbs_directory)) {
if(!mkdir($path_to_thumbs_directory)) {
die("There was a problem. Please try again!");
}
}

imagejpeg($nm, $path_to_thumbs_directory . $filename);
$tn = '<img src="' . $path_to_thumbs_directory . $filename . '" alt="image" />';
$tn .= '<br />Congratulations. Your file has been successfully uploaded, and a thumbnail has been created.';
echo $tn;
}
?>

配置文件:

<?php  
$final_width_of_image = 300;
$final_height_of_image = 300;
$path_to_image_directory = '';
$path_to_thumbs_directory = '-tn';
?>

最佳答案

在此代码块中,您只允许小写文件扩展名:

if(preg_match('/[.](jpg)$/', $filename)) {
//--lowercase-only--^
$im = imagecreatefromjpeg($filename.$path_to_image_directory);
}else if (preg_match('/[.](gif)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}

您可以通过放置 OR condition 来修复在正则表达式中:

if(preg_match('/[.](jpg|JPG)$/', $filename)) {
// -----uppercase-------^
$im = imagecreatefromjpeg($filename.$path_to_image_directory);
}else if (preg_match('/[.](gif|GIF)$/', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png|PNG)$/', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}

或者您可以使用 i 修饰符添加不区分大小写:

if(preg_match('/[.](jpg)$/i', $filename)) {
// -------modifier--------^
$im = imagecreatefromjpeg($filename.$path_to_image_directory);
}else if (preg_match('/[.](gif)$/i', $filename)) {
$im = imagecreatefromgif($path_to_image_directory . $filename);
} else if (preg_match('/[.](png)$/i', $filename)) {
$im = imagecreatefrompng($path_to_image_directory . $filename);
}

关于php - 上传 JPG 但不是 jpg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35442892/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com