Reputation: 512
I've been searching for ways to limit users to "5" file uploads and if they upload more, echo a message. I want to limit 5 because just in case of spammers and users that want to cheat the system and upload more than 5 into he database. I found this answer
if(isset($_FILES['file']['name'][5])){
// Code
}else{
//exit
}
But, it's not working for me. It still sends to the database and skips the, if file is greater than 5, checker. Here is my code
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;
}
}
Upvotes: 0
Views: 296
Reputation: 15374
Your condition is currently checking for the existence of a 6th file and continuing. Instead:
if (count($_FILES['file']['name']) <= 5) {
...
Upvotes: 1
Reputation: 78994
You are executing the code if there ARE more than 5, you want to check that there are NOT more than 5 so use !
:
if(!isset($_FILES['file']['name'][5])){
But you could probably just count:
if(count($_FILES['file']['name']) < 6){
Upvotes: 1