我一直在寻找限制用户上传“5”文件的方法,如果他们上传更多内容,请回复邮件。我想限制5,因为垃圾邮件发送者和用户想要欺骗系统并将超过5个数据库上传到数据库中。 I found this answer
if(isset($_FILES['file']['name'][5])){
// Code
}else{
//exit
}
但是,它不适合我。如果文件大于5,它仍会发送到数据库并跳过检查器。这是我的代码
PHP
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(!empty($_POST['price']) && !empty($_POST['description'])){
if(!ctype_digit($_POST['price'])){
echo "PRICE ENTERED IS NOT AN INTEGER... PLEASE TRY AGAIN!";
exit;
}
$price = addslashes(trim((int)$_POST['price']));
$description = addslashes(trim($_POST['description']));
if(strlen($description) < 15){
echo "Description field needs to be GREATER than 15 characters!";
exit;
}
if(isset($_FILES['file']['name'][5])){
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicsever', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$query = "INSERT INTO test(name, file)VALUES(:file_name, :file_tmp)";
$stmt = $handler->prepare($query);
$errors = array();
foreach($_FILES['file']['tmp_name'] as $key => $error){
if ($error != UPLOAD_ERR_OK) {
$errors[] = $_FILES['file']['name'][$key] . ' was not uploaded.';
continue;
}
$file_name = $key.$_FILES['file']['name'][$key];
$file_tmp = $_FILES['file']['tmp_name'][$key];
try{
$stmt->bindParam(':file_name', $file_name, PDO::PARAM_STR);
$stmt->bindParam(':file_tmp', $file_tmp, PDO::PARAM_STR);
$stmt->execute();
$dir = "devFiles";
if(is_dir($dir)==false){
mkdir($dir, 0700);
}
if(is_file($dir.'/'.$file_name)==false){
move_uploaded_file($file_tmp,$dir.'/'.$file_name);
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
exit;
}
}catch(PDOException $e){
$errors[] = $file_name . 'not saved in db.';
echo $e->getMessage();
}
}
echo "pk";
}else{
echo "tooo big";
exit;
}
}else{
echo '<br><h1 style="color:red;">VALUES MISSING!</h1>';
exit;
}
}
答案 0 :(得分:1)
如果超过5,您要执行代码,要检查是否有不超过5个代码,请使用!
:
if(!isset($_FILES['file']['name'][5])){
但你可能只算数:
if(count($_FILES['file']['name']) < 6){
答案 1 :(得分:1)
您的情况目前正在检查是否存在第6个文件并继续。代替:
if (count($_FILES['file']['name']) <= 5) {
...