Codeigniter - Upload multiple files and displaying files - php

My web app only allows for one file upload which is an issue because users want to be able to submit 2 or more files when necessary.
Please how do I allow multiple file uploads and displaying those files to be downloaded by another type of users?
MODEL
public function upload_docs($data)
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$q = $this->db->get('submit_assignment');
if ( $q->num_rows() > 0 )
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$this->db->update('submit_assignment',$data);
} else {
$this->db->insert('submit_assignment',$data);
}
}
CONTROLLER
public function upload_docs()
{
$homework_id = $_REQUEST['homework_id'];
$student_id =$_REQUEST['student_id'];
$data['homework_id'] = $homework_id;
$data['student_id'] = $student_id;
$data['message'] = $_REQUEST['message'];
// $data['id']=$_POST['assigment_id'];
$is_required=$this->homework_model->check_assignment($homework_id,$student_id);
$this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required|xss_clean');
$this->form_validation->set_rules('file', $this->lang->line('attach_document'), 'trim|xss_clean|callback_handle_upload['.$is_required.']');
if ($this->form_validation->run() == FALSE) {
$msg=array(
'message'=>form_error('message'),
'file'=>form_error('file'),
);
$array = array('status' => 'fail', 'error' => $msg, 'message' => '');
}else{
if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {
$time = md5($_FILES["file"]['name'] . microtime());
$fileInfo = pathinfo($_FILES["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($_FILES["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$_FILES["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
public function handle_upload($str,$is_required)
{
$image_validate = $this->config->item('file_validate');
if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {
$file_type = $_FILES["file"]['type'];
$file_size = $_FILES["file"]["size"];
$file_name = $_FILES["file"]["name"];
$allowed_extension = $image_validate['allowed_extension'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$allowed_mime_type = $image_validate['allowed_mime_type'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mtype = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
if (!in_array($mtype, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'File Type Not Allowed');
return false;
}
if (!in_array($ext, $allowed_extension) || !in_array($file_type, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'Extension Not Allowed');
return false;
}
if ($file_size > $image_validate['upload_size']) {
$this->form_validation->set_message('handle_upload', $this->lang->line('file_size_shoud_be_less_than') . number_format($image_validate['upload_size'] / 1048576, 2) . " MB");
return false;
}
return true;
} else {
if($is_required==0){
$this->form_validation->set_message('handle_upload', 'Please choose a file to upload.');
return false;
}else{
return true;
}
}
}
VIEW
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="upload_docs">
<div class="modal-body pt0">
<div class="row">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" id="homework_id" name="homework_id">
<input type="hidden" id="assigment_id" name="assigment_id">
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('message'); ?></label>
<textarea type="text" id="assigment_message" name="message" class="form-control "></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('attach_document'); ?></label>
<input type="file" id="file" name="file" class="form-control filestyle">
</div>
</div>
<p id="uploaded_docs"></p>
</div>
</div>
<div class="box-footer">
<div class="" id="footer_area">
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text='Please wait...'><?php echo $this->lang->line('save'); ?></button>
</div>
</div>
</form>
This is displayed like this
controller
public function assigmnetDownload($doc)
{
$this->load->helper('download');
$name = $this->uri->segment(5);
$ext = explode(".", $name);
$filepath = "./uploads/homework/assignment/" . $doc;
$data = file_get_contents($filepath);
force_download($name, $data);
}
view
<table class="table table-hover table-striped table-bordered example">
<thead>
<tr>
<th><?php echo $this->lang->line('name') ?></th>
<th><?php echo $this->lang->line('message') ?></th>
<th class="text-right"><?php echo $this->lang->line('action') ?></th>
</tr>
</thead>
<tbody id="homework_docs_result">
</tbody>
</table>
Thanks to all helping me out. I did as you guys directed. However, I noticed I'm able to select multiple files now but gets stuck on the save button.
When I click, nothing happens. Data is not submitted.
This is what I have done so far
controller
if (isset($_FILES["file"])){
foreach($_FILES["file"] as $file){
if(!empty($file["name"])){
$time = md5($file["file"]['name'] . microtime());
$fileInfo = pathinfo($file["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($file["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$file["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
}
}
view
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="uploaded_docs">
<input type="file" multiple="" id="file" name="file[]" class="form-control filestyle">
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text=' Please wait'><?php echo $this->lang->line('save'); ?></button>
</form>

HTML
<input type="file" id="file" name="file[]" class="form-control filestyle">
Setting name to file[] will accept array of files
PHP
if (isset($_FILES["file"]){
foreach($_FILES["file"] as $file){ //this loop will get one file from 'file[]' array at a time
if(!empty($file["name"])){
//your alreay written code
//replace $_FILES["file"] with $file
}
}
}
Hope this helpful :)

Some tips, if help. Do not forget the vote to strengthen. Let's go...
<form method="post" action="upload_docs" enctype="multipart/form-data">
<input name="filesToUpload[]" type="file" multiple="" />
</form>
On your controller it's simple ...
if(isset($_FILES['filesToUpload'])) {
foreach ($_FILES['filesToUpload'] as $fileUp) {
$time = md5($fileUp["file"]['name'].microtime());
$fileInfo = pathinfo($fileUp["file"]["name"]);
$img_name = "{$time}.{$fileInfo['extension']}";
$data['docs'] = $img_name;
move_uploaded_file($fileUp["file"]["tmp_name"], "./uploads/homework/assignment/{$data['docs']}");
$data['file_name']=$fileUp["file"]['name'];
$this->homework_model->upload_docs($data);
}
}
To display multiple files you need to use the same concept as uploading working with
foreach($files as $file){ ... }
I hope I helped. Success!

Setting attribute multiple will allow selecting multiple files at once by pressing ctrl, setting the name as an array(file[]) will allow more than files name to be stored.
<input type="file" id="file" name="file[]" class="form-control filestyle" multiple>
However, if you don't want the user to upload multiple files at once then you'll have to make multiple input fields with the same name as an array(file[])
<input type="file" id="file" name="file[]" class="form-control filestyle">
<input type="file" id="file1" name="file[]" class="form-control filestyle">
...
...
In your controller, you'll have to traverse through each element as it is now an array.
foreach($_FILES["file"]['name'] as $file){ //single element
echo $file; // returns the name of file
// your-logic-to-upload
}
If you're having trouble uploading multiple files, see here, here and here.
Hope it helps you.

Related

Is it possible to have multiple enctypes on an html form?

I'm very new to any web development issues and I couldn't find a solution to this problem. I have a form for uploading files so I use the enctype="multipart/form-data". However, I was also trying to take the fields from the form and encode them in a JSON file and read those out in a table in my html on my webpage. With the default enctype, the JSON encoding works great but obviously the file upload functionality doesn't work and vice versa. I followed a lot of W3Schools tutorials but I'm still lost. Is it possible to use two enctypes or what is the work around to this problem? I'm only uploading my files to localhost, no databases used. I apologize if I give too much info here but my form html looks like:
<form class="modal-content animate" enctype="multipart/form-data" method="post">
<div class="imgcontainer">
<span onclick="document.getElementById('id01').style.display='none'" class="close" title="Close Modal">×</span>
</div>
<div class="container">
<label for="artist"><b>Artist Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of artist" name="artist" required>
<label for="song"><b>Song Name</b></label>
<input class="form-control" type="text" placeholder="Enter name of song." name="song" required>
<label for="instrument"><b>Instrument Type</b></label>
<input class="form-control" type="text" placeholder="Enter type of instrument for tab." name="instrument" required>
<label for="myfile"><b>Tablature</b></label>
<input class="form-control" type="file" placeholder="Select your file." name="myfile" id="myfile" required>
<input type="submit" name="submit" value="Upload Tab PDF" class="w3-hover-purple" style="color:black; background-color:#A9A9A9"></input>
</div>
<div class="container" style="background-color:#f1f1f1">
<button type="button" onclick="document.getElementById('id01').style.display='none'" class="cancelbtn">Cancel</button>
</div>
</form>
My php code is structured as such:
<?php
$message = '';
$error = '';
if(isset($_POST["submit"])) {
if(empty($_POST["artist"])) {
$error = "<label class='text-danger'>Enter artist</label>";
}
else if(empty($_POST["song"])) {
$error = "<label class='text-danger'>Enter song name</label>";
}
else if(empty($_POST["instrument"])) {
$error = "<label class='text-danger'>Enter instrument</label>";
}
else if(empty($_POST["myfile"])) {
$error = "<label class='text-danger'>Enter file to upload</label>";
}
else {
if(file_exists('tablature.json')) {
$current_data = file_get_contents('tablature.json');
$array_data = json_decode($current_data, true);
$extra = array(
'artist' => $_POST['artist'],
'song' => $_POST['song'],
'instrument' => $_POST['instrument'],
'myfile' => $_POST['myfile']
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('tablature.json', $final_data)) {
$message = "<label class='text-success'>File Appended Successfully.</label>";
}
else {
$error = 'JSON File does not exist';
}
}
}
$target_dir = "Tablature/";
$target_file = $target_dir . basename($_FILES["myfile"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($target_file)) {
$error = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error = "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["myfile"]["tmp_name"], $target_file)) {
$message = "The file has been uploaded.";
} else {
$error = "Sorry, there was an error uploading your file.";
}
}
}
?>
Finally, on my page I print out my JSON contents on my page like so:
<table style="width:100%">
<tr>
<th>Artist</th>
<td>Song Name</td>
<td>Instrument Type</td>
<td style="float:right; margin-right:100px;">File</td>
</tr>
<?php
$read_data = file_get_contents("tablature.json");
$read_data = json_decode($read_data, true);
print("Working<br>");
foreach($read_data as $row) {
print('<tr><th>'.$row["artist"].'</th><td>'.$row["song"].'</td><td>'.$row["instrument"].'</td><td style="float:right">'.$row["myfile"].'</td></tr>');
}
?>
</table><br>
Any help would be greatly appreciated. Thank you in advance.

Users can't upload files using mobile phones

I have a form where parents can upload files (their child's completed homework) to be received by teachers.
However, I have been getting a lot of complaints that they can't upload files when they use their mobile phones. When they click on the save button, nothing happens.
Thing is when I (superadmin) and teachers upload from our pages using either pc or mobile phones, it uploads without hitches.
Why can't parents upload files, especially with their mobile phones.
I don't know if this is a coding issue or a server issue.
For now, I use a shared cloud hosting with 4 CPU Cores, 4GB DDR4 RAM, Unlimited Bandwidth and Unlimited SSD Space.
model
public function upload_docs($data)
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$q = $this->db->get('submit_assignment');
if ( $q->num_rows() > 0 )
{
$this->db->where('homework_id',$data['homework_id']);
$this->db->where('student_id',$data['student_id']);
$this->db->update('submit_assignment',$data);
} else {
$this->db->insert('submit_assignment',$data);
}
}
// public function upload_docs($data)
// {
// if (isset($data['id']) && $data['id'] != null) {
// $this->db->where("id", $data["id"])->update("submit_assignment", $data);
// return $data['id'];
// } else {
// $this->db->insert("submit_assignment", $data);
// return $this->db->insert_id();
// }
// }
controller
public function upload_docs()
{
$homework_id = $_REQUEST['homework_id'];
$student_id =$_REQUEST['student_id'];
$data['homework_id'] = $homework_id;
$data['student_id'] = $student_id;
$data['message'] = $_REQUEST['message'];
// $data['id']=$_POST['assigment_id'];
$is_required=$this->homework_model->check_assignment($homework_id,$student_id);
$this->form_validation->set_rules('message', $this->lang->line('message'), 'trim|required|xss_clean');
$this->form_validation->set_rules('file', $this->lang->line('attach_document'), 'trim|xss_clean|callback_handle_upload['.$is_required.']');
if ($this->form_validation->run() == FALSE) {
$msg=array(
'message'=>form_error('message'),
'file'=>form_error('file'),
);
$array = array('status' => 'fail', 'error' => $msg, 'message' => '');
}else{
if (isset($_FILES["file"]) && !empty($_FILES['file']['name'])) {
$time = md5($_FILES["file"]['name'] . microtime());
$fileInfo = pathinfo($_FILES["file"]["name"]);
$img_name = $time . '.' . $fileInfo['extension'];
$data['docs'] = $img_name;
move_uploaded_file($_FILES["file"]["tmp_name"], "./uploads/homework/assignment/" . $data['docs']);
$data['file_name']=$_FILES["file"]['name'];
$this->homework_model->upload_docs($data);
}
$array = array('status' => 'success', 'error' => '', 'message' => $this->lang->line('success_message'));
}
echo json_encode($array);
}
public function handle_upload($str,$is_required)
{
$image_validate = $this->config->item('file_validate');
if (isset($_FILES["file"]) && !empty($_FILES['file']['name']) && $_FILES["file"]["size"] > 0) {
$file_type = $_FILES["file"]['type'];
$file_size = $_FILES["file"]["size"];
$file_name = $_FILES["file"]["name"];
$allowed_extension = $image_validate['allowed_extension'];
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$allowed_mime_type = $image_validate['allowed_mime_type'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mtype = finfo_file($finfo, $_FILES['file']['tmp_name']);
finfo_close($finfo);
if (!in_array($mtype, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'File Type Not Allowed');
return false;
}
if (!in_array($ext, $allowed_extension) || !in_array($file_type, $allowed_mime_type)) {
$this->form_validation->set_message('handle_upload', 'Extension Not Allowed');
return false;
}
if ($file_size > $image_validate['upload_size']) {
$this->form_validation->set_message('handle_upload', $this->lang->line('file_size_shoud_be_less_than') . number_format($image_validate['upload_size'] / 1048576, 2) . " MB");
return false;
}
return true;
} else {
if($is_required==0){
$this->form_validation->set_message('handle_upload', 'Please choose a file to upload.');
return false;
}else{
return true;
}
}
}
view
<td class="mailbox-date pull-right">
<a onclick="upload_docs('<?php echo $homework['id']; ?>', '<?php echo $upload_docsButton; ?>');" class="btn btn-default btn-xs" data-toggle="tooltip" data-original-title="<?php echo $this->lang->line('homework') . " " . $this->lang->line('assignments'); ?>">
<i class="fa fa-upload"></i></a>
<a class="btn btn-default btn-xs" onclick="evaluation('<?php echo $homework['id']; ?>','<?php echo $hw;?>');" title="" data-target="#evaluation" data-toggle="modal" data-original-title="Evaluation">
<i class="fa fa-reorder"></i></a>
</td>
<div class="modal fade" id="upload_docs" tabindex="-1" role="dialog" aria-labelledby="evaluation" style="padding-left: 0 !important">
<div class="modal-dialog" role="document">
<div class="modal-content modal-media-content">
<div class="modal-header modal-media-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="box-title"><?php echo $this->lang->line('homework'); ?> <?php echo $this->lang->line('assignments'); ?></h4>
</div>
<form id="upload" method="post" class="ptt10" enctype="multipart/form-data">
<div class="modal-body pt0">
<div class="row">
<input type="hidden" name="student_id" value="<?php echo $student_id; ?>">
<input type="hidden" id="homework_id" name="homework_id">
<input type="hidden" id="assigment_id" name="assigment_id">
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('message'); ?></label>
<textarea type="text" id="assigment_message" name="message" class="form-control "></textarea>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="pwd"><?php echo $this->lang->line('attach_document'); ?></label>
<input type="file" id="file" name="file" class="form-control filestyle">
</div>
</div>
<p id="uploaded_docs"></p>
</div>
</div>
<div class="box-footer">
<div class="" id="footer_area">
<button type="submit" class="btn btn-info pull-right" id="submit" data-loading-text="<i class='fa fa-spinner fa-spin '></i> Please wait"><?php echo $this->lang->line('save'); ?></button>
</div>
Your view is mess.
First add form action then add button form attribute like this:
<button type="submit" form="upload" class="btn btn-info pull-right" id="submit" data-loading-text='SOME TEXT'> Please wait<?php echo $this->lang->line('save'); ?></button>
<form id="upload" role="form" method="post" class="ptt10" enctype="multipart/form-data" action="upload_docs">

How to upload multiple file and move into folder in php?

code:
<?php
if(isset($_POST['submit']))
{
if(isset($_FILES['img_url']['name']))
{
for($i=0; $i<count($_FILES['img_url']['name']); $i++)
{
$tmpFilePath = $_FILES['img_url']['tmp_name'][$i];
if ($tmpFilePath != "")
{
$path = "../images/hotel_images/";
$name = $_FILES['img_url']['name'][$i];
$size = $_FILES['img_url']['size'][$i];
list($txt, $ext) = explode(".", $name);
$file= time().substr(str_replace(" ", "_", $txt), 0);
$info = pathinfo($file);
$filename = $file.".".$ext;
$filepath_upload = $path.$filename;
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
$j2 = $i+1;
$msg = "<div class='alert alert-success'>Sorry, ".$j2." Image files Extension .".$ext." are not Uploaded & Other files Uploaded Successfully <br/>.</div>" ;
}
else if(move_uploaded_file($_FILES['img_url']['tmp_name'][$i], $filepath_upload))
{
$banner_image_source_file = $filepath_upload;
$banner_image_save_file = $filepath_upload;
list($width_orig, $height_orig) = getimagesize($banner_image_source_file);
$img_url_name.=$filename."|";
}
}
$filepath = rtrim($img_url_name, '|');
}
if(!empty($filepath))
{
$query = mysqli_query($con, "INSERT INTO `hotel`(`img_url`, `status`) VALUES ('".$filepath."')");
if($query)
{
$msg .= "<div class='alert alert-success'>Hotel Record Added Successfully</div>";
}
else
{
$msg = "<div class='alert alert-success'>Unbale to Add Hotel Record Please Try Again !!!</div>";
}
}
else
{
$msg = "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
}
else
{
$msg = "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
}
?>
<form action="" method="POST" enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url[]" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img1" name="img_url2[]" multiple>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</form>
In the following code I have create a simple form where I have two input field type='file' where I am able to upload only first one i.e. <label for="hotel">Upload Hotel Images</label> and move into the folder successfully but I also want to upload and move second input field i.e. <label for="room">Upload Room Images</label>. I don't have any idea about this. So, How can I do this? Please help me.
Thank You
Your Room Image input is called img_url2, which you never interact with in code.
For best practice, move the bulk of your PHP code into a file upload function, then call it once with img_url $_FILE input, and once with img_url2.
Example:
<?php
error_reporting(E_ALL);
ini_set("display_errors", true);
ini_set("display_startup_errors", true);
function uploadFile($file, $path)
{
$img_url_name = "";
if(is_array($file) && isset($file['name']) && isset($file['tmp_name']) && isset($file['size']))
{
$tmpFilePath = isset($file['tmp_name'][0]) ? $file['tmp_name'][0] : "";
$name = isset($file['name'][0]) ? $file['name'][0] : "";
list($txt, $ext) = explode(".", $name);
$file = time().substr(str_replace(" ", "_", $txt), 0);
$filename = $file.".".$ext;
$filepath_upload = $path.$filename;
$imageFileType = strtolower(pathinfo($filename,PATHINFO_EXTENSION));
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" )
{
return "<div class='alert alert-success'>Sorry, ".$name." Image files Extension .".$ext." are not Uploaded & Other files Uploaded Successfully <br/>.</div>" ;
}
else if(move_uploaded_file($tmpFilePath, $filepath_upload))
{
$img_url_name .= $filename."|";
}
$filepath = rtrim($img_url_name, '|');
if(!empty($filepath))
{
if(!isset($con))
{
global $con;
}
$query = mysqli_query($con, "INSERT INTO `hotel`(`img_url`, `room_url`) VALUES ('".$filename."','".$filepath."')");
if($query)
{
return "<div class='alert alert-success'>Hotel Record Added Successfully</div>";
}
}
}
return "<div class='alert alert-success'>Unable to Add Please Try Again !! </div>";
}
if(isset($_POST['submit']))
{
if(isset($_FILES['img_url']['name']))
{
echo uploadFile($_FILES['img_url'], "../images/hotel_images/");
}
if(isset($_FILES['img_url2']['name']))
{
echo uploadFile($_FILES['img_url2'], "../images/room_img/");
}
}
?>
<form action="" method="POST" enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img1" name="img_url2" multiple>
</div>
<input type="submit" class="btn btn-primary" name="submit" value="Submit">
</form>
I use FormData() to upload multiple images from multiple fields. Please take a look at this code:
<head>
<title>Example</title>
</head>
<body>
<form enctype="multipart/form-data" id="add-hotel-form">
<div class="form-group col-md-12">
<label for="hotel">Upload Hotel Images</label>
<input type="file" class="form-control-file" id="upload_hotel_img1" name="img_url" multiple>
</div>
<div class="form-group col-md-12">
<label for="room">Upload Room Images</label>
<input type="file" class="form-control-file" id="upload_room_img2" name="img_url2" multiple>
</div>
<input type="button" class="btn btn-primary" name="submit" value="Submit" onclick="myfunction();">
</form>
</body>
<script>
function myfunction(){
var form_data = new FormData();
var image = document.getElementById('upload_hotel_img1').files.length;
var images = document.getElementById('upload_room_img2').files.length;
for (var x = 0; x < image; x++) {
form_data.append("image", document.getElementById('upload_hotel_img1').files[x]);
}
for (var x = 0; x < images; x++) {
form_data.append("images[]", document.getElementById('upload_room_img2').files[x]);
}
}
</script>
We can retrieve these images in the backend using the follwing : $_FILES["image"]['name'] and $_FILES["images"]['name'] respectively.

PHP FileUpload is not working

I am on Ubuntu. I am trying to take user file upload of small images. I checked the $_FILES it's filled with data. I tried to debug the move command but it doesnot echo anything.
if ($_SERVER['REQUEST_METHOD'] == 'POST' ){
//Now handle everything
if(isset($_POST["submit"])) {
print_r($_FILES);
//Store the image
if(!empty($_FILES['uploaded_file']))
{
$path = "/neel/public/img/";
$path = $path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo 'Its working';
} else{
echo 'I am done!!!';
die();
}
}
createnewEvent($conn);
header('Location:/neel/index.php');
}
}
You can check if the file exists by checking its name.
if(!empty($_FILES['file']['name']))
Where file is the name of input field for file.
P. G above here is correct.
Instead of checking, if $_POST['submit']
You should check this:
if(isset($_FILES['uploaded_file']['name']))
Try this code it's a complete sign up form with PHP , Bootstrap
HTML
<div class="container">
<div class="row">
<br>
<h1 class="text-center">Create new account</h1>
<br>
<div class="col-lg-4 col-md-6 col-sm-12">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="name" placeholder="Your Name">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-lg" name="username" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control form-control-lg" name="password" placeholder="Password">
</div>
<div class="form-group text-center">
<div class='file-input'>
<input type='file' name="profile-img">
<span class='button label' data-js-label>Choose your profile image</span>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-success form-control form-control-lg" name="signup" value="Signup">
</div>
</form>
</div>
</div>
</div>
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors;
if (empty($_POST['name'])) {
$errors[] = "Name field is empty";
}
if (empty($_POST['username'])) {
$errors[] = "Username field is empty";
}
if (empty($_POST['password'])) {
$errors[] = "Password field is empty";
}
if (empty($_FILES['profile-img'])) {
$errors[] = "You should upload profile image";
} else{
$img = $_FILES['profile-img'];
$ext = end(explode('.', $img['name']));
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$max_size = 4; //MegaBytes
if (! in_array($ext, $allowed_extensions)) {
$errors[] = "Please , Choose a valid image";
}
$img_size = $img['size'] / 1000000; // By Megabyte
if ($img_size > $max_size) {
$errors[] = "This picture is so large";
}
}
if (!empty($errors)) {
echo '<div class="container">';
foreach ($errors as $error) {
echo '
<div class="alert alert-danger" role="alert">
' . $error . '
</div>
';
}
echo "</div>";
} else {
$username = filter_var(htmlentities(trim($_POST['username'])), FILTER_SANITIZE_STRING);
$name = filter_var(htmlentities(trim($_POST['name'])), FILTER_SANITIZE_STRING);
$password = sha1(filter_var(htmlentities(trim($_POST['password'])), FILTER_SANITIZE_STRING));
// Profile Picture :-
$imgname = uniqid(uniqid()) . #date("Y-m-d") . "." . $ext;
$target_bath = "uploads/imgs/";
$target_bath = $target_bath . basename($imgname);
$orginal_img = $img['tmp_name'];
if (move_uploaded_file($orginal_img, $target_bath)) {
$sql = "INSERT INTO users(name, username, password,profile_picture, r_d) VALUES ('$name', '$username', '$password', '$target_bath', NOW())";
$result = mysqli_query($conn, $sql);
header('location: ./login.php');
}
}
}
The script you've shown shown will only "not echo anything" if $_SERVER['REQUEST_METHOD'] is not "POST". Assuming your description of events is accurate, then the problem is in the form #halojoy has asked that you show here.
I do hope that you are not redirecting the script back to itself. Also you shouldn't attempt to do a redirect after an echo.

Upload in files in for loop

I am using this upload script http://www.dropzonejs.com
The upload php part is:
foreach($_POST["id"] as $key=>$value)
{
$id = trim(mysqli_real_escape_string($mysqli, $value));
$pre_set = trim(mysqli_real_escape_string($mysqli, $_POST['pre_set'][$key]));
$keep_filename = trim(mysqli_real_escape_string($mysqli, $_POST['keep_filename'][$key]));
$ds = DIRECTORY_SEPARATOR;
$storeFolder = '../uploads';
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
if($keep_filename == 'yes')
{
$targetFile = $targetPath. $pre_set.'_'.$id.'_'.$_FILES['file']['name'];
}
else
{
$targetFile = $targetPath. $pre_set.'_'.$id.'.'.pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
}
move_uploaded_file($tempFile,$targetFile);
}
}
When using this with an standard form as shown below the file is correctly uploaded and renamed:
<form action="includes/upload.php" class="dropzone">
<input type="hidden" class="form-control" id="id[]" name="id[]" value="'.$row['id'].'">
<input type="hidden" class="form-control" id="pre_set[]" name="pre_set[]" value="logo">
<input type="hidden" class="form-control" id="keep_filename[]" name="keep_filename[]" value="no">
</form>
But when using a for loop situation an image is shown in the upload window but the file is not uploaded.
I am not getting any errors (or not using the correct parameter to see it)
while($row = mysqli_fetch_array($res))
{ $i++;
echo'
<div class="container">
<form action="includes/upload.php">
<div class="form-group col-md-3">';
if($i == 1) { echo '<label>Voeg foto toe</label>'; } echo'
<div class="dropzone dropzone_small" id="myId'.$i.'">
<div class="fallback">
<input type="hidden" class="form-control" id="id[]" name="id[]" value="xxxx">
<input type="hidden" class="form-control" id="pre_set[]" name="pre_set[]" value="toolbox_">
<input type="hidden" class="form-control" id="keep_filename[]" name="keep_filename[]" value="yes">
</div>
</div>
</div>
</form>';
}
Any suggestions to change the code to get this working?
Help is much appreciated.
You must start your form with
<form action="includes/upload.php"> method="post" enctype="multipart/form-data">
// your form attributes here
</form>

Categories