【发布时间】:2018-07-19 23:04:36
【问题描述】:
当我想上传文件时遇到问题,脚本对 jpg、png 等类型的图像文件进行验证,当我上传图像文件成功过程时,但当我尝试上传不同的文件类型时,如 doc、pdf 等. 如果文件类型错误但数据文件仍设法进入数据库和文件夹,则出现通知/警报,脚本仅用于宣布类型文件错误但仍保存数据...
这是我的脚本
$image=$_FILES['upload']['name'];
$typeGambar = array('image/bmp', 'image/gif', 'image/jpg', 'image/jpeg', 'image/png');
if(!in_array($_FILES['upload']['type'][$i],$typeGambar)){
echo"<meta http-equiv='refresh' content='0; url=home.php?p=product'>";
}
$sql = mysql_query("INSERT INTO `t_product` (`id_product`,`product`,`category`,`material`,`ink`,`price`,`status`,`date`) VALUES ('$idproduct','$product','$category','$material','$ink','$price','$status',NOW());");
if ($sql) {
$last_id = mysql_insert_id();
foreach ($_POST['size'] as $select){
$sql2 = mysql_query("INSERT INTO `t_productsize` (`id_product`,`id_size`) VALUES ('$last_id','$select');");
}
$total = count($_FILES['upload']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
$fileError = $_FILES['upload']['error'][$i];
$typeGambar = array('image/bmp', 'image/gif', 'image/jpg', 'image/jpeg', 'image/png');
if(!in_array($_FILES['upload']['type'][$i],$typeGambar)){
echo'<script>
alert("Failed insert data!!");
</script>';
}
elseif($fileSize=$_FILES['gambar']['size']< 20000 || $fileError < 20000){
//Make sure we have a filepath
if ($tmpFilePath != ""){
$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["upload"]["name"]));
//Setup our new file path
$newFilePath = "images_product/".$newfilename . $_FILES['upload']['name'][$i];
$nameImage = $newfilename . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
$sql3 = mysql_query("INSERT INTO `t_productimage` (`id_product`,`image`) VALUES ('$last_id','$nameImage');");
}
}
}
}
echo '<script>
window.location="home.php?p=product";
</script>';}
else {
echo'<script>
alert("Failed insert data!!");
</script>';
}
非常感谢您的回复
【问题讨论】:
-
您的脚本发出元刷新,但这并不意味着您的脚本到此结束 - 首先处理整个脚本,然后将结果发送到浏览器。将其他所有内容放在
else分支中,或者在输出元刷新代码后使用 die/exit 退出脚本。顺便提一句。 mysql 扩展已经被弃用很长时间了,你不应该再使用它了。而且您的代码看起来对 SQL 注入开放。 -
是的,你说得对,我现在正在学习mysqli,谢谢你的建议
标签: php mysql image validation file-upload