Uploading multiple files and renaming - PHP - php

I'm uploading multiple files.
Main function works fine, but I have to change the names of uploading files Like:
name1.jpg, name2.jps, name3.jpg, ...
$i = 1;
if(move_uploaded_file($_FILES['upl']['tmp_name'], 'uploads/name'.$i++.'.'.$extension)){
echo '{"status":"success"}';
exit;
}
Number $i should grow with amount of uploaded files.
I hope that explained it correctly.

You need a loop:
if(isset($_FILES['files'])){
$name_array = $_FILES['files']['name'];
$tmp_name_array = $_FILES['files']['tmp_name'];
// Number of files
$count_tmp_name_array = count($tmp_name_array);
// We define the static final name for uploaded files (in the loop we will add an number to the end)
$static_final_name = "name";
for($i = 0; $i < $count_tmp_name_array; $i++){
// Get extension of current file
$extension = pathinfo($name_array[$i] , PATHINFO_EXTENSION);
// Pay attention to $static_final_name
if(move_uploaded_file($tmp_name_array[$i], "uploads/".$static_final_name.$i.".".$extension)){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}

Related

Multiple file uploads to a specific folder

I'm attempting to create a plugin on wordpress and I need to upload multiple images to a specific folder on the server...
I currently have
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple="multiple">
<input type="submit" value="Upload">
</form>
And this is the code that reads and should upload the files...
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
$name = $myFile["name"][$i];
$error_msg = $myFile["error"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $photo_dir."/".$name);
if ($success) {
echo $name ." uploaded<br>";
} else {
echo $error_msg;
}
}
}
Is there a way to get it to report an error - at the moment if the file name already exists then it jsut overwrites the old version...
When you do a upload of files PHP store the files in a temporary folder.
You have to move the file from temporary folder to the folder that you want to store the files.
Here is an example using your code:
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
// The folder that you want to store the file
$folderName = 'tmp/';
for ($i = 0; $i < $fileCount; $i++) {
$fileName = $myFile["name"][$i];
$success = move_uploaded_file($myFile["tmp_name"][$i], $folderName . $fileName);
if ($success) {
echo 'File ' . $fileName . ' uploaded!<br>';
}
}
}

Trouble inserting two array values into database

Here is the code I am using for multiple image upload for every entry in the database; id, image, name, date. By using this code, the image name is inserting correctly but I have a problem with the name field. I want to insert the name using $product_name= $_POST['pro_name']; but it only inserts 'array' in name field.
<?php
include('../config.php');
if (isset($_POST['submit'])) {
$product_name = $_POST['pro_name'];
$j = 0; // Variable for indexing uploaded image.
$target_path = "uploads/"; // Declaring Path for uploaded images.
for ($i = 0; $i < count($_FILES['file']['name']) && $product_name < count($product_name); $i++) {
// Loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); // Extensions which are allowed.
$ext = explode('.', basename($_FILES['file']['name'][$i])); // Explode file name from dot(.)
$file_extension = end($ext); // Store extensions in the variable.
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1]; // Set the target path with a new name of image.
$j = $j + 1; // Increment the number of uploaded images according to the files in array.
if (($_FILES["file"]["size"][$i] < 100000000) // Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
$finel_name = explode('/', $target_path);
$image_name_final = $finel_name[1];
$jajsj = "insert into spec_product set image='$image_name_final', name='$product_name'";
$janson = mysql_query($jajsj) or die(mysql_error());
// If file moved to uploads folder.
echo $j . ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else { // If File Was Not Moved.
echo $j . ').<span id="error">please try again!.</span><br/><br/>';
}
} else { // If File Size And File Type Was Incorrect.
echo $j . ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
The value is inserting as array because the variable $product_name is not a string but an array. Whenever an array is used where a string was expected e.g.: concatenation of a string or in your case the query statment: insert into spec_product set image='$image_name_final', name='$product_name'"; PHP will automatically convert the array into its default string value "Array".
Make sure that $product_name is not an array but a string which contains name of the product you want to insert in the table.
Regards,
Nitin Thakur
replace in your code
for ($i = 0; $i < count($_FILES['file']['name']); $i++)
{
and add this before your query execute
$product_name_final= $product_name[$i];

php zip archive is adding the files with no size

I got this working but when i look into the zip folder all the files size is 0. I tryed not adding the files to the zip and that worked, but when i try to add them to a zip the size goes to 0. Why is this.
here is my php
if(isset($_FILES['file'])){
$file_folder = "uploads/";
$zip = new ZipArchive();
$zip_name = time().".zip";
$open = $zip->open("zip/".$zip_name, ZipArchive::CREATE);
if($open === true){
for($i = 0; $i < count($_FILES['file']['name']); $i++)
{
$filename = $_FILES['file']['name'][$i];
$tmpname = $_FILES['file']['tmp_name'][$i];
move_uploaded_file($tmpname, "uploads/".$filename);
$zip->addFile($file_folder, $filename);
}
$zip->close();
if(file_exists("zip/".$zip_name)){
// zip is in there, delete the temp files
echo "Works";
for($i = 0; $i < count($_FILES['file']['name']); $i++)
{
$filenameu = $_FILES['file']['name'][$i];
unlink("uploads/".$filenameu);
}
} else {
// zip not created, give error
echo "something went wrong, try again";
}
}
}
Your problem lies with this line: $zip->addFile($file_folder, $filename);
Currently that passes a path to the /uploads/ directory as the first argument.
According to Zip::addFile documentation you should be passing the path to the file to add (this includes the file and extension).
So change your code to include the file name (you already have it as a variable $filename which is handy).
$zip->addFile($file_folder.$filename, $filename);

php zipArchive unzip only certain extensions

I'm in need of unziping uploaded content. But for security purposes must verify the files are only image files so that somebody can't add a php into the zip and then run it later.
While doing the unzip I need to preseverve the file structure as well.
$zip->extractTo($save_path . $file_name, array('*.jpg','*.jpeg','*.png','*.gif') );
doesn't return null. Is there a parameter I can use for this or must I iterate with a loop through the zip file using regex to match extensions and create the folders and save the files with code??
Thanks
from php.net, handling .txt files
<?php
$value="test.zip";
$filename="zip_files/$value";
$zip = new ZipArchive;
if ($zip->open($filename) === true) {
echo "Generating TEXT file.";
for($i = 0; $i < $zip->numFiles; $i++) {
$entry = $zip->getNameIndex($i);
if(preg_match('#\.(txt)$#i', $entry))
{
////This copy function will move the entry to the root of "txt_files" without creating any sub-folders unlike "ZIP->EXTRACTO" function.
copy('zip://'.dirname(__FILE__).'/zip_files/'.$value.'#'.$entry, 'txt_files/'.$value.'.txt');
}
}
$zip->close();
}
else{
echo "ZIP archive failed";
}
?>
for anyone who would need this in the future here is my solution. Thanks Ciro for the post, I only had to extend yours a bit. To make sure all folders are created I loop first for the folders and then do the extarction.
$ZipFileName = dirname(__FILE__)."/test.zip";
$home_folder = dirname(__FILE__)."/unziped";
mkdir($home_folder);
$zip = new ZipArchive;
if ($zip->open($ZipFileName ) === true)
{
//make all the folders
for($i = 0; $i < $zip->numFiles; $i++)
{
$OnlyFileName = $zip->getNameIndex($i);
$FullFileName = $zip->statIndex($i);
if ($FullFileName['name'][strlen($FullFileName['name'])-1] =="/")
{
#mkdir($home_folder."/".$FullFileName['name'],0700,true);
}
}
//unzip into the folders
for($i = 0; $i < $zip->numFiles; $i++)
{
$OnlyFileName = $zip->getNameIndex($i);
$FullFileName = $zip->statIndex($i);
if (!($FullFileName['name'][strlen($FullFileName['name'])-1] =="/"))
{
if (preg_match('#\.(jpg|jpeg|gif|png)$#i', $OnlyFileName))
{
copy('zip://'. $ZipFileName .'#'. $OnlyFileName , $home_folder."/".$FullFileName['name'] );
}
}
}
$zip->close();
} else
{
echo "Error: Can't open zip file";
}

Multiple file upload in php

I want to upload multiple files and store them in a folder and get the path and store it in the database... Any good example you looked for doing multiple file upload...
Note: Files can be of any type...
Some further explanation might be useful for someone trying to upload multiple files. Here is what you need to do:
Input name must be be defined as an array i.e.
name="inputName[]"
Input element must have multiple="multiple" or just multiple
In your PHP file use the syntax "$_FILES['inputName']['param'][index]"
Make sure to look for empty file names and paths, the array might contain empty strings. Use array_filter() before count.
Here is a down and dirty example (showing just relevant code)
HTML:
<input name="upload[]" type="file" multiple="multiple" />
PHP:
//$files = array_filter($_FILES['upload']['name']); //something like that to be used before processing files.
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for( $i=0 ; $i < $total ; $i++ ) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
Multiple files can be selected and then uploaded using the
<input type='file' name='file[]' multiple>
The sample php script that does the uploading:
<html>
<title>Upload</title>
<?php
session_start();
$target=$_POST['directory'];
if($target[strlen($target)-1]!='/')
$target=$target.'/';
$count=0;
foreach ($_FILES['file']['name'] as $filename)
{
$temp=$target;
$tmp=$_FILES['file']['tmp_name'][$count];
$count=$count + 1;
$temp=$temp.basename($filename);
move_uploaded_file($tmp,$temp);
$temp='';
$tmp='';
}
header("location:../../views/upload.php");
?>
</html>
The selected files are received as an array with
$_FILES['file']['name'][0] storing the name of first file.
$_FILES['file']['name'][1] storing the name of second file.
and so on.
this simple script worked for me.
<?php
foreach($_FILES as $file){
//echo $file['name'];
echo $file['tmp_name'].'</br>';
move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}
?>
HTML
create div with id='dvFile';
create a button;
onclick of that button calling function add_more()
JavaScript
function add_more() {
var txt = "<br><input type=\"file\" name=\"item_file[]\">";
document.getElementById("dvFile").innerHTML += txt;
}
PHP
if(count($_FILES["item_file"]['name'])>0)
{
//check if any file uploaded
$GLOBALS['msg'] = ""; //initiate the global message
for($j=0; $j < count($_FILES["item_file"]['name']); $j++)
{ //loop the uploaded file array
$filen = $_FILES["item_file"]['name']["$j"]; //file name
$path = 'uploads/'.$filen; //generate the destination path
if(move_uploaded_file($_FILES["item_file"]['tmp_name']["$j"],$path))
{
//upload the file
$GLOBALS['msg'] .= "File# ".($j+1)." ($filen) uploaded successfully<br>";
//Success message
}
}
}
else {
$GLOBALS['msg'] = "No files found to upload"; //No file upload message
}
In this way you can add file/images, as many as required, and handle them through php script.
Here is a function I wrote which returns a more understandable $_FILES array.
function getMultiple_FILES() {
$_FILE = array();
foreach($_FILES as $name => $file) {
foreach($file as $property => $keys) {
foreach($keys as $key => $value) {
$_FILE[$name][$key][$property] = $value;
}
}
}
return $_FILE;
}
It's not that different from uploading one file - $_FILES is an array containing any and all uploaded files.
There's a chapter in the PHP manual: Uploading multiple files
If you want to enable multiple file uploads with easy selection on the user's end (selecting multiple files at once instead of filling in upload fields) take a look at SWFUpload. It works differently from a normal file upload form and requires Flash to work, though. SWFUpload was obsoleted along with Flash. Check the other, newer answers for the now-correct approach.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$max_no_img=4; // Maximum number of images value to be set here
echo "<form method=post action='' enctype='multipart/form-data'>";
echo "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
for($i=1; $i<=$max_no_img; $i++){
echo "<tr><td>Images $i</td><td>
<input type=file name='images[]' class='bginput'></td></tr>";
}
echo "<tr><td colspan=2 align=center><input type=submit value='Add Image'></td></tr>";
echo "</form> </table>";
while(list($key,$value) = each($_FILES['images']['name']))
{
//echo $key;
//echo "<br>";
//echo $value;
//echo "<br>";
if(!empty($value)){ // this will check if any blank field is entered
$filename =rand(1,100000).$value; // filename stores the value
$filename=str_replace(" ","_",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "upload/$filename"; // upload directory path is set
//echo $_FILES['images']['type'][$key]; // uncomment this line if you want to display the file type
//echo "<br>"; // Display a line break
copy($_FILES['images']['tmp_name'][$key], $add);
echo $add;
// upload the file to the server
chmod("$add",0777); // set permission to the file.
}
}
?>
</body>
</html>
Simple is that, just count the files array first, then in while loop you can easily do this like
$count = count($_FILES{'item_file']['name']);
now you got total number of files right.
In while loop do like this:
$i = 0;
while($i<$count)
{
Upload one by one like we do normally
$i++;
}
I run foreach loop with error element, look like
foreach($_FILES['userfile']['error'] as $k=>$v)
{
$uploadfile = 'uploads/'. basename($_FILES['userfile']['name'][$k]);
if (move_uploaded_file($_FILES['userfile']['tmp_name'][$k], $uploadfile))
{
echo "File : ", $_FILES['userfile']['name'][$k] ," is valid, and was successfully uploaded.\n";
}
else
{
echo "Possible file : ", $_FILES['userfile']['name'][$k], " upload attack!\n";
}
}
Just came across the following solution:
http://www.mydailyhacks.org/2014/11/05/php-multifile-uploader-for-php-5-4-5-5/
it is a ready PHP Multi File Upload Script with an form where you can add multiple inputs and an AJAX progress bar. It should work directly after unpacking on the server...
We can easy to upload multiple files using php by using the below script.
Download Full Source code and preview
<?php
if (isset($_POST['submit'])) {
$j = 0; //Variable for indexing uploaded image
$target_path = "uploads/"; //Declaring Path for uploaded images
for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array
$validextensions = array("jpeg", "jpg", "png"); //Extensions which are allowed
$ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.)
$file_extension = end($ext); //store extensions in the variable
$target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext) - 1];//set the target path with a new name of image
$j = $j + 1;//increment the number of uploaded images according to the files in array
if (($_FILES["file"]["size"][$i] < 100000) //Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if (move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {//if file moved to uploads folder
echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';
} else {//if file was not moved.
echo $j. ').<span id="error">please try again!.</span><br/><br/>';
}
} else {//if file size and file type was incorrect.
echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';
}
}
}
?>
$property_images = $_FILES['property_images']['name'];
if(!empty($property_images))
{
for($up=0;$up<count($property_images);$up++)
{
move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
}
}
This is what worked for me. I had to upload files, store filenames and I had additional inof from input fields to store as well and one record per multiple file names.
I used serialize() then added that to the main sql query.
class addReminder extends dbconn {
public function addNewReminder(){
$this->exdate = $_POST['exdate'];
$this->name = $_POST['name'];
$this->category = $_POST['category'];
$this->location = $_POST['location'];
$this->notes = $_POST['notes'];
try {
if(isset($_POST['submit'])){
$total = count($_FILES['fileUpload']['tmp_name']);
for($i=0;$i<$total;$i++){
$fileName = $_FILES['fileUpload']['name'][$i];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);
$newFileName = md5(uniqid());
$fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
$justFileName = $newFileName.'.'.$ext;
if($ext === 'pdf' || 'jpeg' || 'JPG'){
move_uploaded_file($_FILES['fileUpload']['tmp_name'][$i], $fileDest);
$this->fileName = array($justFileName);
$this->encodedFileNames = serialize($this->fileName);
var_dump($this->encodedFileNames);
}else{
echo $fileName . ' Could not be uploaded. Pdfs and jpegs only please';
}
}
$sql = "INSERT INTO reminders (exdate, name, category, location, fileUpload, notes) VALUES (:exdate,:name,:category,:location,:fileName,:notes)";
$stmt = $this->connect()->prepare($sql);
$stmt->bindParam(':exdate', $this->exdate);
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':category', $this->category);
$stmt->bindParam(':location', $this->location);
$stmt->bindParam(':fileName', $this->encodedFileNames);
$stmt->bindParam(':notes', $this->notes);
$stmt->execute();
}
}catch(PDOException $e){
echo $e->getMessage();
}
}
}
extract($_POST);
$error=array();
$extension=array("jpeg","jpg","png","gif");
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(in_array($ext,$extension))
{
if(!file_exists("photo_gallery/".$txtGalleryName."/".$file_name))
{
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$file_name);
}
else
{
$filename=basename($file_name,$ext);
$newFileName=$filename.time().".".$ext;
move_uploaded_file($file_tmp=$_FILES["files"]["tmp_name"][$key],"photo_gallery/".$txtGalleryName."/".$newFileName);
}
}
else
{
array_push($error,"$file_name, ");
}
}
and you must check your HTML code
<form action="create_photo_gallery.php" method="post" enctype="multipart/form-data">
<table width="100%">
<tr>
<td>Select Photo (one or multiple):</td>
<td><input type="file" name="files[]" multiple/></td>
</tr>
<tr>
<td colspan="2" align="center">Note: Supported image format: .jpeg, .jpg, .png, .gif</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Create Gallery" id="selectedButton"/></td>
</tr>
</table>
</form>
Nice link on:
PHP Single File Uploading with vary basic explanation.
PHP file uploading with the Validation
PHP Multiple Files Upload With Validation Click here to download source code
PHP/jQuery Multiple Files Upload With The ProgressBar And Validation (Click here to download source code)
How To Upload Files In PHP And Store In MySql Database (Click here to download source code)

Categories