Multiple File upload with dynamic fields - php

Can you please advise/help me with this code? I want to upload multiple files to the server and save the information in database. But this code is uploading only one file, from the first input field.
I have dynamic "upload file" fields, like this:
<form action="uploader.php" method="POST" enctype="multipart/form-data">
<label>Upload</label>
<input type="file" name="file[]">
<label>Description</label>
<input type="text" id="filedesc" name="filedesc[]">
<a href="#" onClick="addUpload('dynamicInputUpload');" >
<img src="../../img/add.png" ></a>
<div id="dynamicInputUpload"></div>
<input type="submit" float= "right" name="add" id="add" value="UPLOAD" >
<input type="hidden" name="pid" id="pid" value="<?php echo $pid; ?>">
<input type="hidden" name="intnumber" id="intnumber" value="<?php echo $int; ?>">
</form>
Bellow is the Javascript that creates dynamic fields:
var counterUpload = 1;
var limit = 10;
function addUpload(divName){
if (counterUpload == limit) {
alert("You have reached the limit of adding " + counterUpload + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <label>File " + (counterUpload + 1) + "</label><input type=\"file\" name=\"file["+counterUpload+"]\" id=\"file["+counterUpload+"]\"> <label>Description " + (counterUpload + 1) + "</label><input type=\"text\" id=\"filedesc["+counterUpload+"]\" name=\"filedesc["+counterUpload+"]\" >"
document.getElementById(divName).appendChild(newdiv);
counterUpload++;
}
}
And the problem is bellow in the uploader.php. I suceed to uplaod only one (the first) file.
<?php
include '../../c/config.php';
include '../../c/opendb.php';
// Settings
$allowedExtensions = array('jpg','gif','bmp','png', 'docx', 'doc','pdf');
$maxSize = 2097152;
$storageDir = '../uploads/';
// Result arrays
$errors = $output = array();
if (!empty($_FILES['file'])){
// Validation loop
foreach($_FILES['file']['name'] as $i=> $value){
$fileName = $_FILES['file']['name'][$i];
$fileSize = $_FILES['file']['size'][$i];
$fileErr = $_FILES['file']['error'][$i];
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Validate extension
if (!in_array($fileExt, $allowedExtensions)) {
$errors[$fileName][] = "Format $fileExt in file $fileName is not accepted";
}
// Validate size
if ($fileSize > $maxSize) {
$errors[$fileName][] = "$fileName excedes the maximum file size of $maxSize bytes";
}
// Check errors
if ($fileErr) {
$errors[$fileName][] = "$fileName uploaded with error code $fileErr";
}
}
// Handle validation errors here
if (count($errors) > 0) {
die("Errors validating uploads: ".print_r($errors, TRUE));
}
// Create the storage directory if it doesn't exist
if (!is_dir($storageDir)) {
if (!mkdir($storageDir, 0755, TRUE)) {
die("Unable to create storage directory $storageDir");
}
}
// File move loop
foreach($_FILES['file']['name'] as $i=> $array_value){
// Get base info
$fileBase = basename($_FILES['file']['name'][$i]);
$fileName = pathinfo($fileBase, PATHINFO_FILENAME);
$fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
$fileTmp = $_FILES['file']['tmp_name'][$i];
// Construct destination path
$fileDst = $storageDir.'/'.basename($_FILES['file']['name'][$i]);
for ($j = 0; file_exists($fileDst); $j++) {
$fileDst = "$storageDir/$fileName-$j.$fileExt";
}
// Move the file
if (move_uploaded_file($fileTmp, $fileDst)) {
$output[$fileBase] = "Stored $fileBase OK";
$sql=mysql_query("INSERT INTO uploaded_files (pid, file_path,file_type)
Values ('$_POST[pid]','$fileDst','$fileExt')")
or die ("Unable to issue query sql: ".mysql_error());
} else {
$output[$fileBase] = "Failure while uploading $fileBase!";
$errors[$fileBase][] = "Failure: Can't move uploaded file $fileBase!";
}
}
// Handle file move errors here
if (count($errors) > 0) {
die("Errors moving uploaded files: ".print_r($errors, TRUE));
} }

This string has an error:
$sql=mysql_query("INSERT INTO uploaded_files (pid, file_path,file_type)
Values ('$_POST[pid]','$fileDst','$fileExt')")
or die ("Unable to issue query sql: ".mysql_error());
Try to comment this string, your script will save all files.
Maybe you did not connected to the database.

Related

php rename uploaded file before upload and overwrite if already exists

Currently using this code for the upload (but happy to use any if suggested)..
<form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select CSV file to upload:</label>
<input type="file" name="files[]" multiple="multiple" /> <input type="submit" value="Upload CSV" name="btnSubmit"/>
</form>
<?php
if(isset($_POST["btnSubmit"]))
{
$errors = array();
$uploadedFiles = array();
$extension = array("csv");
$bytes = 1024;
$KB = 1024;
$totalBytes = $bytes * $KB;
$UploadFolder = "tmp_csv_store";
$counter = 0;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];
if(empty($temp))
{
break;
}
$counter++;
$UploadOk = true;
if($_FILES["files"]["size"][$key] > $totalBytes)
{
$UploadOk = false;
array_push($errors, $name." file size is larger than the 1 MB.");
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext, $extension) == false){
$UploadOk = false;
array_push($errors, $name." invalid file type.");
}
if(file_exists($UploadFolder."/".$name) == true){
$UploadOk = false;
array_push($errors, $name." file already exists.");
}
if($UploadOk == true){
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
}
if($counter>0){
if(count($errors)>0)
{
echo "<b>Errors:</b>";
foreach($errors as $error)
{
echo " ".$error.",";
}
echo "<br/>";
}
if(count($uploadedFiles)>0){
echo "<b>Uploaded:</b>";
echo "=";
foreach($uploadedFiles as $fileName)
{
echo " ".$fileName.",";
}
echo "<br/>";
echo "<big><big>".count($uploadedFiles)." file has been successfully uploaded.</big></big>";
}
}
else{
echo "ERROR: Please press the browse button and select a CSV file to upload.";
}
}
?>
And would like to modify it so that it renames the uploaded file from "any-file-name.csv" to "foobar.csv" before it uploads the file and it should also overwrite the file if it already exists.
As a bonus the code currently allows for multi-file upload but I really only need it for a single file each time so it could also possibly be shortened a bit if changed to only allow a single file.
Thanks in advance :-)
To add your custom name:
if($UploadOk == true){
$name = "foobar.csv";
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
For single file, remove multiple="multiple":
<input type="file" name="files[]" />

PHP - multiple file upload, If not upload some field, it will get error

Hello I do the PHP Upload multiple files, but my form does not require to upload all field (require just at least one field upload) so user may not upload the second input field.
The problem is if user upload only 1 file, user will get the error "Invalid file" (final else statement).
But if user upload all 2 fields, it does not have error, I guess the error come from null upload field. So I use if not empty first, but it's not work. How should I do?
<form action="upload.php" method="post" enctype="multipart/form-data">
Image 1 :
<input type="file" name="images[]" />
<br>
image 2 :
<input type="file" name="images[]" /> <br>
<input type="submit" value="Upload" />
</form>
in upload.php page
if(!empty($_FILES))
{
$count = count($_FILES["images"]["name"]);
for($i=1; $i <= $count; $i++)
{
if ((($_FILES["images"]["type"][$i-1] == "image/gif")
|| ($_FILES["images"]["type"][$i-1] == "image/jpeg")
|| ($_FILES["images"]["type"][$i-1] == "image/png"))
&& ($_FILES["images"]["size"][$i-1] < 2000000)) //2 MB
{
if ($_FILES["images"]["error"][$i-1] > 0)
{
echo "File Error : " . $_FILES["images"]["error"][$i] . "<br />";
}
else
{
if (file_exists("path/to/".$_FILES["images"]["name"][$i-1] ))
{
echo "<b>".$_FILES["images"]["name"][$i-1] . " already exists. </b>";
}
else
{
$newname = date('Y-m-d')."_".$i.".jpg";
move_uploaded_file($_FILES["images"]["tmp_name"][$i-1] , "path/to/".$newname);
}
}
}
else
{
echo "Invalid file" ;
exit();
}
}
}
You can change your first line to:
if(isset($_FILES["images"]["name"][0])) {
With one or multiple files this can work
on line with:
echo "Invalid file" ;
exit();
this can be a problem, because if the first file have a problem you exit aplication and not process the second or others.
i suggest to you this code, too:
<?php
if (isset($_FILES["images"]["name"][0])) {
$path_upload = 'path/upload/';
$count = count($_FILES["images"]["name"]);
$allowed_types = array("image/gif", "image/jpeg", "image/png");
$nl = PHP_EOL.'<br>'; // Linux: \n<br> Window: \r\n<br>
for($i=0; $i < $count; $i++)
{
$file_type = $_FILES["images"]['type'][$i];
$file_name = $_FILES["images"]['name'][$i];
$file_size = $_FILES["images"]['size'][$i];
$file_error = $_FILES["images"]['error'][$i];
$file_tmp = $_FILES["images"]['tmp_name'][$i];
if (in_array($file_type, $allowed_types) && $file_size < 2000000) {
if ($file_error > 0) {
echo 'Upload file:'.$file_name.' error: '.$file_error.$nl;
} else {
$path_new_upload = $path_upload.$file_name;
// verify while filename exists
while (file_exists($path_new_upload)) {
$ext = explode('.', $file_name); // explode dots on filename
$ext = end($ext); // get last item of array
$newname = date('Y-m-d_').$i.'.'.$ext;
$path_new_upload = $path_upload.$newname;
}
move_uploaded_file($file_tmp, $path_new_upload);
}
} else {
echo 'Invalid file type to: '.$file_name.$nl;
// continue the code
}
}
}
Can be better, this verify filename to new creation.

need php code to post below 5 images into one field of db separated by br

Please help me
My html code is as follows:
here image_name is getting through echo from another upload query
My upload script code
$path = "uploads/";
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name)){
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$time = time();
$ip = $_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')");
echo "<img src='uploads/".$actual_image_name."' class='previewOfimgss'> ";
$allimages_name = "$actual_image_name";
echo "$allimages_name";
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
It is working quite good and giving result like
and i want images names in on textbox like
$items=$_POST["post_items"];
$final = "";
foreach($items as $item){
$final .= $item."<br>";
}
echo $final
And you can then pass the $final variable to the column.
There is another way to do it.
$items= $_POST["post_items"];
$final = implode("<br>",$items);
It will work only if $items is array.
Ok I've done a working solution for you. This is a kind of prototype of your system. Hope it helps you in what you are building.
fileForm.php (Where you select file to upload.)
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="uploadFile.php" method="post" enctype="multipart/form-data">
<input type="file" name="photoimg[]" multiple="yes">
<input type="submit" name="fileUploader">
</form>
</body>
</html>
uploadFile.php (Where you upload your files as in your question)
<?php
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$path = "uploads/"; // Upload directory
// Return's files extension
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP"); // Valid formats to upload
$fileCount=count($_FILES["photoimg"]["name"]); // Number of files uploaded
$files=array(); // Initilize an empty array to save names
// Loop through all files and upload them
for ($i=0; $i < $fileCount; $i++) {
$name=$_FILES["photoimg"]["name"][$i];
$tmp=$_FILES["photoimg"]["tmp_name"][$i];
$size=$_FILES["photoimg"]["size"][$i];
// If name is not empty
if(!empty($name)){
$ext = getExtension($name); // Get file extension
// If file is valid to upload
if(in_array($ext,$valid_formats)){
If file is less than 1 MB.
if($size<(1024*1024)){
$actual_image_name = time().substr(str_replace(" ", "_", $name), 5); // Final name of image
// If file uploads successfully
if(move_uploaded_file($tmp, $path.$actual_image_name)){
$time=time();
$ip=$_SERVER['REMOTE_ADDR'];
mysql_query("INSERT INTO uploads(image_name,poster_user,created,cat,status,ip) VALUES('$actual_image_name','$u_id','$time', 'Photos', '1', '$ip')"); // Insert into your table
echo "<img src='uploads/$actual_image_name' class='previewOfimgss'> "; // Show the image
$files[$i] = $actual_image_name; // Save file names
}else{
echo "Fail upload folder with read access.";
}
}else{
echo "Image file size max 1 MB";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
}
}
?>
<form action="toSaveFileName.php" method="post">
<?php
for ($i=0; $i < $fileCount; $i++) {
// Generate input fields
echo "<input type='text' name='post_items[]' value='{$files[$i]}'>";
}
?>
<input type="submit">
</form>
toSaveFileName.php (This is what you originally asked for.)
$items=$_POST["post_items"]; // from input fields
$todb=""; // to send to database
if(is_array($items)){
$todb=implode("<br>",$items);
}else{
$todb=$items;
}
echo $todb; // for output
//save to database
Now implementing it to your system is your job. And I hope you should be able to do it on your own.
Don't forget to mark this as answer and vote up.

Uploading Files and Images with mkdir specific location

What I am trying to put images where my folder is generate from "$tablename", but fail to bring the image there. How do I store the uploaded files ?
I like to upload images from my form.
<input type="file" id="file" name="files" multiple />
No matter which of those upload techniques I use is not good to use, to save the file to a specific location on the server.
If you have an idea how to do this problem please.
here is the mkdir code. The code is works fine.
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die("" . mysql_error() . "" . $qShowStatus);
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string) ("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If (!file_exists($year)) {
$createsyear = mkdir("$year", 0777);
} else {
If (!file_exists("$year/$month")) {
$createsmonth = mkdir("$year/$month", 0777);
} else {
If (!file_exists("$year/$month/$day")) {
$createsday = mkdir("$year/$month/$day", 0777);
} else {
If (!file_exists($year / $month / $day / $tablename)) {
$createsday = mkdir("$year/$month/$day/$tablename", 0777);
} else {
//dada
}
}
}
}
?>
Thank You.
Here I give basic example for file upload.
in HTML
<form action="phpfilename.php" method="post" enctype="multipart/form-data" >
<input type="file" name="files" />
<input type="submit" name="submit" />
</form>
In PHP
<?php
if(isset($_POST['submit']))
{
$path = $_FILES["files"]["name"];
$target = "$year/$month/$day/$tablename/$path"; //this is your path where image need to be saved
move_uploaded_file($_FILES["files"]["tmp_name"], $target);
}
?>
I fix the problem
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "" . mysql_error() . "" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string)("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If(!file_exists($year)){
$createsyear = mkdir("$year", 0777);
}
else
{
If(!file_exists("$year/$month")){
$createsmonth = mkdir("$year/$month", 0777);
}
else
{
If(!file_exists("$year/$month/$day")){
$createsday = mkdir("$year/$month/$day", 0777);
}
else
{
If(!file_exists($year/$month/$day/$tablename)){
$createsday = mkdir("$year/$month/$day/$tablename/", 0777);
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$target = "$year/$month/$day/$tablename/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $target.$name)) {
$count++; // Number of successfully uploaded files
}
}
}
}
}
}
else
{
}
}
}
}
?>

PHP video upload and checking video type

I created my upload file with video size and type validation. Only webm, mp4 and ogv file types are allowed and 2gb file size max. My php code:
if (isset($_POST['submit']))
{
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$allowed_extensions = array("webm", "mp4", "ogv");
$file_name_temp = explode(".", $file_name);
$extension = end($file_name_temp);
$file_size_max = 2147483648;
if (!empty($file_name))
{
if (($file_type == "video/webm") || ($file_type == "video/mp4") || ($file_type == "video/ogv") &&
($file_size < $file_size_max) && in_array($extension, $allowed_extensions))
{
if ($_FILES['file']['error'] > 0)
{
echo "Unexpected error occured, please try again later.";
} else {
if (file_exists("secure/".$file_name))
{
echo $file_name." already exists.";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "secure/".$file_name);
echo "Stored in: " . "secure/".$file_name;
}
}
} else {
echo "Invalid video format.";
}
} else {
echo "Please select a video to upload.";
}
}
My html code:
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br />
<input type="submit" name="submit" value="Submit">
</form>
I'am always getting "Invalid video format.". I downloaded webm, mp4 and ogv video files from flowplayer website to test my little upload script.
http://stream.flowplayer.org/bauhaus/624x260.webm
http://stream.flowplayer.org/bauhaus/624x260.mp4
http://stream.flowplayer.org/bauhaus/624x260.ogv
Your extensions were not correctly being validated.. try this
if (isset($_POST['submit']))
{
$file_name = $_FILES['file']['name'];
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
$allowed_extensions = array("webm", "mp4", "ogv");
$file_size_max = 2147483648;
$pattern = implode ($allowed_extensions, "|");
if (!empty($file_name))
{ //here is what I changed - as you can see above, I used implode for the array
// and I am using it in the preg_match. You pro can do the same with file_type,
// but I will leave that up to you
if (preg_match("/({$pattern})$/i", $file_name) && $file_size < $file_size_max)
{
if (($file_type == "video/webm") || ($file_type == "video/mp4") || ($file_type == "video/ogv"))
{
if ($_FILES['file']['error'] > 0)
{
echo "Unexpected error occured, please try again later.";
} else {
if (file_exists("secure/".$file_name))
{
echo $file_name." already exists.";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "secure/".$file_name);
echo "Stored in: " . "secure/".$file_name;
}
}
} else {
echo "Invalid video format.";
}
}else{
echo "where is my mojo?? grrr";
}
} else {
echo "Please select a video to upload.";
}
}
function fileSelected() {
var inputs = document.getElementsByClassName('myclass');
var input = inputs[0];
var file = input.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
//alert("type: "+type);
if(type!="video/mp4")
{
alert("NOT SUITABLE EXTENSION SELECTED");
}
filesArray.push({ name: name, size: size });
}
<input type="file" accept="video/*" class=" form-control btn btn-primary myclass" required name="file1" id="file1" onchange="fileSelected();">

Categories