我的网站上有一个表单,除了其他所有功能外,用户还可以将图像上传到网站。 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!=&#39;&#39; ,它仍会上传。当用户根本没有填写文件输入字段时,如果声明(是的,我知道,我不知道正确的术语......),代码不应该输入文件上传,但是& #34;上传文件时出错了#34;仍然显示。当提交不允许格式的图像时,它仍然被上传但路径看起来像这个/ url / folder / img。 - 没有文件扩展名。
答案 0 :(得分:1)
试试这个......
<?php
IF (isset($_POST['submit'])) {
$err = "";
$mimetypes = array('image/gif', 'image/jpeg', 'image/pjpeg', 'image/jpg', 'image/png', 'image/x-png');
$imgexts = array('gif', 'jpeg', 'jpg', 'png');
IF (!empty($_FILES['file']['name'])) {
$img = $_FILES['file']['name'];
$temp = $_FILES['file']['tmp_name'];
$ext = strtolower(substr(strrchr($_FILES['file']['name'], '.'), 1));// file ext.
$info = @getimagesize($_FILES['file']['tmp_name']);
$imgw = $info[0]; // width
$imgh = $info[1]; // height
$mime = image_type_to_mime_type($info[2]);
IF (!in_array($ext, $imgexts)) {
$err .="<li>File type (".$ext.") is not supported. (Only ".implode(", ",$imgexts).")</li>"; // Non-supported file type
}ELSE{
//
IF (!in_array($mime, $mimetypes)) {
$err .="<li>Mime type (".$mime.") is not supported. (Only ".implode(", ",$mimetypes).")</li>"; // Non-supported mime type
}
}
}ELSE{
$err ="<li>Select a file to upload (".implode(", ",$imgexts).")</li>";
}
IF (!empty($err)) {
echo '<p>Errors:</p><ul>'.$err.'</ul>';
}ELSE{
// good to go
}
}ELSE{
// form not sumbitted
}
?>