Could someone please assist as I would like to upload multiple images to the server as well the image names to the database.
The below code works for uploading the images to the server:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post" enctype='multipart/form-data'>
<input type="file" name="file[]" multiple>
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Count total files
$countfiles = count($_FILES['file']['name']);
// Looping all files
for($i=0;$i<$countfiles;$i++){
$filename = $_FILES['file']['name'][$i];
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'][$i], dirname(__DIR__)."/img/".$filename);
}
} else {
// Load view with errors
$this->view('posts/add');
}
}
I am also able to upload the 3 image names when using the below code with 3 separate inputs:
View:
<form action="<?php echo URLROOT; ?>/posts/add" method="post">
<input type="file" name="image1">
<input type="file" name="image2">
<input type="file" name="image3">
<input type="submit" name=submit value="Submit">
</form>
Controller:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// Sanitize POST array
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$data = [
'user_id' => $_SESSION['user_id'],
'image1' => trim($_POST['image1']),
'image2' => trim($_POST['image2']),
'image3' => trim($_POST['image3']),
];
// Validated
if($this->postModel->addPost($data)){
flash('post_message', 'Post Added');
redirect('posts');
} else {
die('Something went wrong');
}
} else {
$data = [
'image1' => '',
'image2' => '',
'image3' => ''
];
$this->view('posts/add', $data);
}
}
Could someone please advise on how I could combine the code, in order to use a single file input for uploading the images to server, as well as the image names to the database?