【发布时间】:2015-05-20 07:16:00
【问题描述】:
我的网站上有一个表格,除此之外,它还允许用户将图像上传到网站。 HTML 和 PHP:
<html>
<body>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$error = '';
// Checking other input fields...
// If anything else is valid, try to upload file (to avoid uploading useless c**p)
if(isset($_FILES['file']) && $error == '' && $_FILES['file']){
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = '';
echo $file . $file_name . $file_tmp . $file_size;
$file_ext = pathinfo($file_name, PATHINFO_EXTENSION);
if($file_ext != 'png' && $file_ext != 'jpg' && $file_ext != 'jpeg' && $file_ext != 'gif' && $file_ext != 'bmp'){
$file_error .= "<br>Only png, jpg, jpeg, gif and bmp formats allowed!";
}
if($file_size > 1048576){ // << 1MB in bytes
$file_error .= "<br>Maximum size is 1MB.";
}
if(empty($file_error)){
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = 'img/usr/' . $file_name_new;
if(rename($file_tmp, $file_destination)){
// echo '<br>' . $file_destination;
} else{$file_error .= '<br>Something went wrong while uploading file';}
}
echo $file_error;
}
}
?>
<form method="post" action="" enctype="multipart/form-data">
<fieldset>
<legend>Form</legend>
<!-- Other input fields -->
<div id="form_element">Upload image:</div>
<input type="file" name="file"><span id="error"><small><?php echo $file_error;
//echo $file . '<br>' . $_FILES['file'] . '<br>' . $file_name . $file['name'];
//echo '<br>' . $file_tmp . '<br>' . $file['tmp_name'] . '<br>' . $file_size . '<br>' . $file['size'];
?></small></span>
<div id="form_element">
<input type="submit" value="Postita" id="submit">
</div>
</fieldset>
</form>
存在多个问题。当用户上传不符合要求(大小、格式等)的文件时,即使 $error != '' 仍然会上传。当用户根本不填写文件输入字段时,代码不应该输入文件上传if语句(是的,我知道,我不知道正确的术语......),但是“上传文件时出错了"仍然显示。当提交了不允许格式的图像时,它仍然被上传,但路径看起来像这样/url/folder/img。 - 没有文件扩展名。
【问题讨论】:
标签: php html forms file-upload