Upload in files in for loop - php

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>

Related

How to remove image from folder at update phpMysql?

Update query from the database:
<?php
include 'dpconnection.php';
$uid=$_REQUEST['upid'];
if (isset($_POST['update'])) {
$category= $_POST['category'];
$pname= $_POST['pname'];
$parea= $_POST['parea'];
$pPrices= $_POST['pPrices'];
$pAddress= $_POST['pAddress'];
$filename = $_FILES['new_image']['name'] ;
$tempname = $_FILES['new_image']['tmp_name'] ;
$filesize = $_FILES['new_image']['size'] ;
$fileextension = explode('.', $filename) ;
$fileextension = strtolower(end($fileextension));
$newfilename = uniqid().'images'.'.'.$fileextension ;
$path = "media/".$newfilename ;
$sql = mysqli_query($conn,"UPDATE product SET c_id='$category', p_name='$pname', p_area='$parea', p_prices='$pPrices',p_address='$pAddress', p_thumb_image='$path' WHERE p_id='$uid'");
if (move_uploaded_file($tempname, $path) && $sql) {
echo "<script>alert('Record Updated successfully');</script>";
echo "<script>location.href = 'adminViewProduct.php';</script>";
} else {
echo "Error updating record: " . $conn->error;
}
}
?>
Image not deleting from folder, i have two if statement but just one else statement so it looks like i am missing something but i really don't know what i am missing.
This is form:
<div class="form-group">
<label>Address</label>
<input class="form-control" type="text" name="pAddress" value="<?php echo $row1['p_address'];?>">
</div>
<div class="form-group">
<label>Thumb Image</label>
<input type="file" name="new_image" class="form-control">
<input class="form-control" type="hidden" name="pimage" value="<?php echo $row1['p_thumb_image'];?>">
<img class="float-left" src="<?php echo $row1['p_thumb_image'];?>" width="100px;"><br><br>
</div>
<div class="form-group text-center">
<input class="btn btn-primary" type="submit" name="update" value="Update">
</div>
</form>
You don't have a code that delete the files in php there's a function called unlink where you can delete a files but first you need fetch the path or filename and delete it before updating your data.
Here is the link of unlink.
https://www.php.net/manual/en/function.unlink.php

Codeigniter - Upload multiple files and displaying files

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.

Upload multiple files with a php script

I've been modify this php script but it won't work, it always fail. It managed to create the folder, but it fails to move the files from the temporary folder to the right one, the function move_uploaded_file return always false. This is the code:
<?php
include 'connection.php';
include '../empty.html';
session_start();
if(isset($_FILES['filearray'])){
$name_array = $_FILES['filearray']['name'];
$tmp_name_array = $_FILES['filearray']['tmp_name'];
$type_array = $_FILES['filearray']['type'];
$size_array = $_FILES['filearray']['size'];
$error_array = $_FILES['filearray']['error'];
$titlealbum=$_POST['titoloalbum'];
$username=$_SESSION['username'];
$path="../users/".$username."/".$titlealbum."/";
echo $path;
mkdir($path,0777);
$total=count($tmp_name_array);
for($i=0; $i<$total; $i++){
$rightpath=$path.$name_array[$i];
if(move_uploaded_file($tmp_name_array[$i], $rightpath)){
echo $name_array[$i]." upload is complete<br>";
echo "upload completato";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]." into".$path."<br>";
}
}
}
else
echo "Files not found";
?>
This is the html form:
<form id="albumform" style="display:none" enctype="multipart/form-data" action="scripts/albumupload.php" multiple="multiple" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000">
Name: <input name="titoloalbum" type="text" required><br><br>
Cover: <input name="userfile" type="file">
<br><br>Select your songs:<br />
<input name="filearray[]" type="file" value="10000000" /><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input name="filearray[]" type="file" value="10000000"/><br />
<input type="submit" value="Send files" />
</form>
I know that this form kinda sucks, but i don't like the multiple selection with a signle "input". Thanks in advice
You have error in your code :
$total=count($tmp_name_array);
change this to
$total=count($name_array);
You are using count function with wrong variable.
Also remove so many file types with same name from the form. Either name them different.
<input name="filearray[]" type="file" value="10000000"/><br />
You could use the following commented algorithm for Multiple-Files upload:
PHP
<?php
// FILENAME: albumupload.php
include 'connection.php';
include '../empty.html';
session_start();
$filesArray = isset( $_FILES['filesArray'] ) ? $_FILES['filesArray'] : null;
$titleAlbum = isset($_POST['titoloalbum']) ? isset($_POST['titoloalbum']) : null;
$arrFilesData = array();
if( $filesArray && !empty($filesArray) ){
$arrFilesKeys = array_keys($filesArray['name']);
$arrFilesNames = $filesArray['name'];
$arrFilesTypes = $filesArray['type'];
$arrFilesTmpNames = $filesArray['tmp_name'];
$arrFilesErrors = $filesArray['error'];
$arrFilesSizes = $filesArray['size'];
foreach($arrFilesKeys as $intKey=>$strKeyName){
$tempFileData = new stdClass();
$tempFileData->key = $strKeyName;
$tempFileData->name = $arrFilesNames[$strKeyName];
$tempFileData->type = $arrFilesTypes[$strKeyName];
$tempFileData->tmp_name = $arrFilesTmpNames[$strKeyName];
$tempFileData->error = $arrFilesErrors[$strKeyName];
$tempFileData->error = $arrFilesSizes[$strKeyName];
$arrFilesData[$strKeyName] = $tempFileData;
}
// UPLOAD THE FILES:
if($titleAlbum){
$username = trim($_SESSION['username']);
$path = __DIR__ . "/../users/" . $username . "/" . $titleAlbum;
//CREATE UPLOAD DIRECTORY IF IT DOESN'T ALREADY EXIST...
if(!file_exists($path)){
mkdir($path, 0777, TRUE);
}
// LOOP THROUGH THE FILES OBJECT ARRAY AND PERFORM FILE-UPLOAD
foreach($arrFilesData as $fileKey=>$objFileData){
$rightPath = $path . DIRECTORY_SEPARATOR . $objFileData->name;
if(move_uploaded_file($objFileData->tmp_name, $rightPath)){
echo $objFileData->name . " upload is complete<br>";
echo "upload completato";
} else {
echo "move_uploaded_file function failed for ". $objFileData->name ." into". $path . "<br>";
}
}
}
}
In this case, your HTML Form is expected to look like this:
HTML
<form id="albumform" style="" enctype="multipart/form-data" action="scripts/albumupload.php" method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000">
Name: <input name = "titoloalbum" type="text" required><br><br>
Cover: <input name = "filesArray[userfile]" type="file">
<br><br>Select your songs:<br />
<input name="filesArray[file_1]" type="file" value="" /><br />
<input name="filesArray[file_2]" type="file" value=""/><br />
<input name="filesArray[file_3]" type="file" value=""/><br />
<input name="filesArray[file_4]" type="file" value=""/><br />
<input type="submit" value="Send files" />
</form>

How to add multiple images using browse button

I have a following code where I can upload a single image. This image gets stored in both database and folder. Now what I want is to add multiple images. How can I do that. Help me to come out of this.
<?php
$uploadDir ="C:/wamp/www/dragongym/customers/";
if(isset($_POST['submit']))
{
$intime =DATE("H:i", STRTOTIME($_POST['intime']));
$outtime =DATE("H:i", STRTOTIME($_POST['outtime']));
date_default_timezone_set('Asia/Calcutta');
$today = date("Y-m-d");
$msg="";
$res = "SELECT customer_id FROM customer ORDER by customer_id DESC LIMIT 1";
$qur = mysql_query($res);
while($row = mysql_fetch_array($qur, MYSQL_BOTH))
{
$last_id = $row['customer_id'];
$plus_id = 1;
}
if( $last_id !="")
{
$cust_id = $last_id + $plus_id;
}
$filePath="";
if($_FILES['cimage']['size'] > 0)
{
// echo $cust_id;
// Temporary file name stored on the server for pdf
$filename = basename($_FILES['cimage']['name']);
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$new = $cust_id.'.'.$extension;
$tmpName1 = $_FILES['cimage']['tmp_name'];
$fileSize = $_FILES['cimage']['size'];
$fileType = $_FILES['cimage']['type'];
$filePath = $uploadDir . $new;
$resultes = move_uploaded_file($tmpName1, $filePath);
if (!$resultes)
{
echo "Error uploading file";
exit;
}
if(!get_magic_quotes_gpc())
{
$new = addslashes($new);
$filePath = addslashes($filePath);
}
}
$sql = 'INSERT INTO customer(customer_name,roll_no,customer_number,customer_address,tariff_id,intime,outtime,customer_image,active,joining_date) VALUES("'.$_POST['name'].'","'.$_POST['roll'].'","'.$_POST['number'].'","'.$_POST['address'].'","'.$_POST['tariff'].'","'.$intime.'","'.$outtime.'","'.$filePath.'","1","'.$today.'")';
$msg="<p style=\"color:#99CC00; font-size:13px;\"> Successfully!</p>";
if (!mysql_query($sql, $link))
{
die('Error: ' . mysql_error());
}
}
?>
<form action="#" method="post" enctype="multipart/form-data">
<h2>Registration Form</h2><?php echo $msg; ?>
<label>Name</label>
<input type="text" value="" name="name" id="name" required class="txtfield">
<label>Roll Number</label>
<input type="text" value="" name="roll" id="roll" required class="txtfield">
<label>Mobile Number</label>
<input type="text" value="" name="number" required class="txtfield" id="mobnum">
<label>Address</label>
<textarea name="address" class="txtfield"></textarea>
<label>Upload Photo</label>
<input type="file" value="" name="cimage" class="txtfield">
<!-- <label style="display: block">Timing</label>
<input type="text" value="" name="intime" placeholder="Intime" required class="timefield timepicker">
<input type="text" value="" name="outtime" placeholder="Outtime" required class="timefield timepicker">-->
<input type="submit" value="Save" name="submit" class="btn buttonside1">
</form>
You can use jquery plugin for that..
there is lots of plugin available on google..try this one http://blueimp.github.io/jQuery-File-Upload/
to do multiple file upload you should first have multiple="true" in your tab like so
<input type="file" name='files[]' multiple='true'/>
then use foreach loop to upload files.

File upload not posting data to iframe

I have a simple file upload form which posts to an iframe and the i retrieve the value from the iframe and redirect to another page.
The problem is the form isnt posting to the iframe (i dont think) so none of the php is being executed and null is being return to the javascript.
HTML Code
<form id="upload" name="upload" enctype="multipart/form-data" method="post" action="index.php" target="upload_target">
<input name="folder" type="hidden" value="<?php echo $folder ?>" />
<input name="filename" type="hidden" value="<?php echo $filename ?>" />
<input name="uploaded_file" type="file" size="5120" id="uploaded_file" accept="image/jpeg" />
<input id="sent" name="sent" type="submit" value="Upload" />
</form>
<iframe id="upload_target" name="upload_target" style="width:10px; height:10px; display:none"></iframe>
Javascript to get the value from iframe
$('form#upload').submit(function(){
$('#upload_wrapper').hide();
$('#loading').show();
// get the uploaded file name from the iframe
$('#upload_target').unbind().load( function()
{
var img = $('#upload_target').contents().find('#filename').html();
alert(img); //returning null
$('#loading').hide();
});
});
And the PHP at the top of the page to upload the file
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$targetFolder = $_POST['folder'] . "/";
$filename2 = $_POST['filename'];
if (!is_dir($targetFolder))
{
mkdir($targetFolder, 0777);
}
$tempFile = $_FILES['uploaded_file']['tmp_name'];
$targetPath = dirname(__FILE__) . '/' . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['uploaded_file']['name'];
$uploadfile = $targetFolder. basename($filename2 .".jpg");
move_uploaded_file($tempFile,$uploadfile);
$fileName = $uploadfile;
echo "<div id='filename'>$fileName</div>";
}
This code has been working before so im unsure at why it has stopped now please help.

Categories