PHP Post Form, Can't upload files over 25MB - php

So I've changed all these values in php.ini:
Max file upload size = 10000M
post upload size = 11000M
Excecution Max Time = 12000
Input Max Time = 12000
Im also using a PHP form which uploads multiple files at once:
index.php (file upload form, other code on page which requires php backend)
<input type="hidden" value="form" name="<?php echo ini_get('session.upload_progress.name'); ?>">
<div class="upload-btn-wrapper">
<button class="btn">Drag File / Click to upload</button>
<input type="file" name="files[]" multiple="multiple" id="fileToUpload">
</div>
</form>
document.getElementById("fileToUpload").onchange = function() {
startUpload();
setTimeout(function(){document.getElementById("form").submit();}, 1000);
}
</script>
Again, I can upload normal files fine, but large files dont work.
heres the file upload php code:
<?php
session_start();
//boi
$max_file_size = 20000000; //2GB
$path = $_SESSION["directory"]."/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute 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
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}
header("location: index.php");
?>
the site this is live on is: http://simpledrive.duckdns.org/simple
thanks.

Time for me to answer my own question, So turns out it was a couple lines of code in the upload script I had written/coppied from all over the place.
$max_file_size = 20000000;
if ($_FILES['files']['size'][$f] > $max_file_size) {
Turns out the ['files']['size'][$f] here was massivley larger than $max_file_size.
even set at 20000000.
Thanks for your help anyway guys.
to be honest, im kinda retarted (meme image)

Related

how to upload multiple image in php pdo [duplicate]

This question already has an answer here:
How to upload multiple image with rename in php mysql?
(1 answer)
Closed 1 year ago.
I wanted to upload multiple pictures at once using PHP but I am new to PHP so I don't understand how to do it. I want to upload a lot of pictures for one model. Like the picture below:
Here is my PHP code:
<?php
include_once('inc/header.php');
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
$image_file = $_FILES["image"]["name"];
$type = $_FILES["image"]["type"]; //file name "txt_file"
$size = $_FILES["image"]["size"];
$temp = $_FILES["image"]["tmp_name"];
$path="../img/model_images/".$image_file; //set upload folder path
if (empty($name)) {
$errorMsg="Please Enter Name";
} elseif (empty($image_file)) {
$errorMsg="Please Select Image";
} elseif ($type=="image/jpg" || $type=='image/jpeg' || $type=='image/png' || $type=='image/gif') { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "../img/model_images/" .$image_file); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
}
if (!isset($errorMsg)) {
$insert_stmt=$connect->prepare('INSERT INTO tbl_model(model_name,model_category,model_image,model_age,model_height,model_haircolor,model_eyecolor,model_bust,model_waist,model_description) VALUES(:name,:category,:image,:txt_age,:height,:haircolor,:eyecolor,:bust,:waist,:about)'); //sql insert query
$insert_stmt->bindParam(':name', $name);
$insert_stmt->bindParam(':category', $category);
$insert_stmt->bindParam(':image', $image_file);
$insert_stmt->bindParam(':txt_age', $age);
$insert_stmt->bindParam(':height', $height);
$insert_stmt->bindParam(':haircolor', $haircolor);
$insert_stmt->bindParam(':eyecolor', $eyecolor);
$insert_stmt->bindParam(':bust', $bust);
$insert_stmt->bindParam(':waist', $waist);
$insert_stmt->bindParam(':about', $about);
if ($insert_stmt->execute()) {
echo $insertMsg="Model Added Successfully!"; //execute query success message
}
} else {
echo $errorMsg;
}
} catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
But with this code I can only upload one picture but I want to upload many pictures.
This is my html code
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image" class="dropify" multiple>
</div>
In html you miss '[]' after name as you have to send array when you upload images and also make sure you write enctype in form tag as shown below
The form tag must contain the following attributes.
method="post"
enctype="multipart/form-data"
The input tag must contain type="file[]" and multiple attributes.
<form action="/action_page_binary.asp" method="post" enctype="multipart/form-data">
<div class="form-group col-12">
<label for="slideImages" class="col-form-label">Model Image</label>
<input type="file" name="image[]" class="dropify" multiple>
</div>
</form>
after this just you have to write for loop or foreach loop in php file as shown below in your code you use single column to store multiple image so apply this loop after you $about
if (isset($_REQUEST['add'])) {
try {
$name = $_REQUEST['name'];
$category = $_REQUEST['category'];
$age = $_REQUEST['txt_age'];
$height = $_REQUEST['height'];
$haircolor = $_REQUEST['haircolor'];
$eyecolor = $_REQUEST['eyecolor'];
$bust = $_REQUEST['bust'];
$waist = $_REQUEST['waist'];
$about = $_REQUEST['about'];
//$path="../img/model_images/".$image_file; //set upload folder path
$path = '';
if (empty($name)) {
$errorMsg="Please Enter Name";
exit;
}
foreach($_FILES["image"]["name"] as $key => $value){
$image_file = implode(',', $_FILES["image"]["name"]);
$image_name = $_FILES["image"]["name"][$key];
$type = $_FILES["image"]["type"][$key]; //file name "txt_file"
$size = $_FILES["image"]["size"][$key];
$temp = $_FILES["image"]["tmp_name"][$key];
if (empty($image_file)) {
$errorMsg="Please Select Image";
exit;
} else if (
($type=="image/jpg" ||
$type=='image/jpeg' ||
$type=='image/png' ||
$type=='image/gif')
) { //check file extension
if (!file_exists($path)) { //check file not exist in your upload folder path
if ($size < 5000000) { //check file size 5MB
move_uploaded_file($temp, "images/" .$image_name); //move upload file temperory directory to your upload folder
} else {
$errorMsg="Your File To large Please Upload 5MB Size"; //error message file size not large than 5MB
exit;
}
} else {
$errorMsg="File Already Exists...Check Upload Folder"; //error message file not exists your upload folder path
exit;
}
} else {
$errorMsg="Upload JPG , JPEG , PNG & GIF File Formate.....CHECK FILE EXTENSION"; //error message file extension
exit;
}
}
echo $name.$category.$age.$height.$haircolor.$eyecolor.$bust.$waist.$about.$image_file;
exit;
after this just bind above $image_file in your query
when you want to fetch display image use explode
$explode_images = explode(",", $images_file);
its gives you array then use foreach loop and key to access image name url or whatever you store in that column.
Hope this help .
if you need explanation of implode and explode check this out Implode Explode

PHP, Issues with two following move_uploaded_file

I've recently encountered some issues while trying to upload some images with PHP and the move_uploaded_file function.
The first move_uploaded_file works perfectly but not the second one.
I have put this on top of my page but it displaying anything:
ini_set('display_errors', 1);
error_reporting(E_ALL|E_STRICT);
Here is my code:
$folder = 'product/'.$savedProduct -> getId();
//First I create the list of my path, starting with my main picture
$imagePath[0] = '../uploaded_pics/'.$folder.'/'.$_FILES['main_image']['name'];
$thumbnailPath[0] = '../uploaded_pics/'.$folder.'/thumbnail/'.$_FILES['main_image']['name'];
$tmp_path[0] = $_FILES['main_image']['tmp_name'];
for ($cpt = 1; $cpt < 6; $cpt ++) { //Because I only want 5 pics and start at 1 so I won't erase the Main Image datas.
if (isset($_FILES['thumbnail_image_'.$cpt])) { //It refer to the HTML file input name thumbnail_image_someNumber
$imagePath[$cpt] = '../uploaded_pics/'.$folder.'/'.$_FILES['thumbnail_image_'.$cpt]['name'];
$thumbnailPath[$cpt] = '../uploaded_pics/'.$folder.'/thumbnail/'.$_FILES['thumbnail_image_'.$cpt]['name'];
$tmp_path[$cpt] = $_FILES['thumbnail_image_'.$cpt]['tmp_name'];
}
}
//Then I check-create my folders
if (!is_dir('../uploaded_pics/'.$folder)) {
mkdir('../uploaded_pics/'.$folder, 0777, true);
}
if (!is_dir('../uploaded_pics/'.$folder.'/thumbnail')) {
mkdir('../uploaded_pics/'.$folder.'/thumbnail', 0777, true);
}
//And Then I save my pictures
if (count($imagePath) > 1) { //If I have more than just the Main Image
for ($cpt = 0; $cpt < count($imagePath); $cpt ++) {
$image = new Image('', $imagePath[$cpt], $thumbnailPath[$cpt]);
saveImage($image, $bdd); //Save the path in MySQL database, this works fine
move_uploaded_file($tmp_path[$cpt], $imagePath[$cpt]);
move_uploaded_file($tmp_path[$cpt], $thumbnailPath[$cpt]);
//And Here happened the problem
}
}
Only the first move_uploaded_file is working, the next one doesn't make anything. I tried to var_dumped the arrays and they all contains the proper datas. I also tried to invert the two move_uploaded_file and so they works well separatly, just not when they are both "actived".
EDIT/SOLUTION:
Just need to replace the second move_uploaded_file by:
copy($imagePath[$cpt], $thumbnailPath[$cpt]);
I'll try to resize the images later, thanks guys.
This moves the file from $tmp_path[$cpt] to $imagePath[$cpt]
move_uploaded_file($tmp_path[$cpt], $imagePath[$cpt]);
This attempts to move the file from $tmp_path[$cpt] to $thumbnailPath[$cpt]
move_uploaded_file($tmp_path[$cpt], $thumbnailPath[$cpt]);
But you've already moved it in the first line, so there's nothing to move! Instead you have to copy it from its new location:
copy($imagePath[$cpt], $thumbnailPath[$cpt]);
TRY IT
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Multiple File Ppload with PHP</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
<input type="submit" value="Upload!" />
</form>
</body>
</html>
<?php
$valid_formats = array("jpg", "png");
$max_file_size = 1280*1024;
$path = "uploads/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute 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], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}
?>
move_uploaded_file() works like "cut" and "paste". Your first call has already moved the original file.
It's working perfectly with this combo:
move_uploaded_file($tmp_path[$cpt], $imagePath[$cpt]);
copy($imagePath[$cpt], $thumbnailPath[$cpt]);

move_uploaded_file in PHP not working after transfering my site to new hosting server?

So I transferred my website from Godaddy to a rackspace cloud hosting plan ... Now I'm facing an issue with pictures not being able to be uploaded from my website , I checked my script to debug and trace the problem , and the problem arises at the move_uploaded_file built in function , it returns FALSE ... I gave the 777 permission to the upload file , but it still isn't working ... Any idea why .. Below is the uploading function
function upload_file($mid,$image,$folder){
$image_name = false;
if($_FILES[$image]['name']!=""){
$tmpImageName = $_FILES[$image]['name'];
$uploadedfile=$_FILES[$image]['tmp_name'];
$extension=getExtension($_FILES[$image]['name']);
if($extension=="jpg" || $extension=="JPG" || $extension=="jpeg" || $extension=="JPEG" || $extension=="gif" || $extension=="GIF" || $extension=="png" || $extension=="PNG"){
// FIX limit max image file size to 3.5MB - 2012-06-14 10:48
if($_FILES[$image]['size'] > 3200000) {
Set_Display_Message("Invalid image size for file {$tmpImageName}! Please upload file smaller than 3.5MB.");
} else {
// FIX limit max image dimensions to 3500x3500px - 2012-06-14 10:48
list($width, $height, $attr) = getimagesize($uploadedfile);
if(3500 < $width || 3500 < $height) {
Set_Display_Message("Invalid image dimensions for file {$tmpImageName}! Please upload file smaller 3500x3500 px.");
} else {
$image_name=getfileName($_FILES[$image]['name']).$mid.mt_rand(1000,9999).".".$extension; //var_dump($image_name);
$NotVail_files = file_validation('image',$uploadedfile); //var_dump($uploadedfile); var_dump($folder);
if($tmpImageName!="" && $uploadedfile!="" && $image_name!="" && $NotVail_files){
#move_uploaded_file($uploadedfile, $folder."/".$image_name); //var_dump(move_uploaded_file($uploadedfile, $folder."/".$image_name)); var_dump($_FILES); exit;
}
}
}
} else {
Set_Display_Message("Invalid file format! Please upload only image type: .jpg,.jpeg,.gif,.png......");
}
}
return $image_name;
}
<input type="file" id="FileUpload1" style="position:absolute;" name="upload">
<input type="submit" id="Button1" name="image submit" value="Submit" style="position:absolute;width:96px;height:25px;">
That should work for you as I'm using this script on my site.
Just having a problem now after a year the server seems to have upgraded where it's needing tweaks to redirect page once the file uploads.

Cannot upload .mpg files

I've built a rather straightforward file uploader in PHP. So far I've had no troubles uploading images and zip files. However, I can't seem to upload .mpg's. Whenever I try then it after hanging for a moment the page seems like it didn't try to upload anything at all. For example: this
// This is also manually set in php.ini
ini_set("upload_max_filesize", "524288000");
...
print_r($_FILES);
print_r($_POST); // I'm sending along one variable in addition to the file
returns nothing but empty arrays. For completeness, here's the front-end
<form action="uploadVideo.php" method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="524288000"/>
<input type="hidden" name="extravar" value="value" />
<p>
<label for="file">Filename:</label>
<input type="file" name="file" id="file" /><br />
<i>Accepted formats: .mp4, .3gp, .wmv, .mpeg and .mpg. Cannot exceed 500MB.</i>
</p>
<p>Description:</p>
<textarea name="description" rows="4" cols="40"></textarea>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The file I am testing with is only 33MB and I tested a .wmv of similar size and it uploaded just fine.
Edit: Entire PHP file listed below
<?php
// Ensure that the user can upload up to the maximum size
ini_set("upload_max_filesize", "524288000");
ini_set("post_max_size", "524288000");
print_r($_POST);
print_r($_FILES);
if(!$link = mysql_connect($SERVER_LOCATION, $DB_USER, $DB_PASS)) die("Error connecting to server.");
mysql_select_db($DB_NAME);
$eventID = $_POST['event'];
// Select the event this is associated with
$query = "SELECT eventName FROM event WHERE eventID = $eventID";
if(!$res = mysql_query($query, $link)) die("Error communicating with database.");
$path = mysql_fetch_row($res);
$path = "media/$path[0]";
// If this event doesn't have a media folder, make one
if(!file_exists($path)) {
mkdir($path);
}
// If this event doesn't have a GIS subfolder, make one
$path = "$path/videos";
if(!file_exists($path)) {
mkdir($path);
}
// Generate todays date and a random number for the new filename
$today = getdate();
$seed = $today['seconds'] * $today['minutes'];
srand($seed);
$random = rand(0, 999);
$today = $today['mon']."-".$today['mday']."-".$today['year'];
$fileType = $_FILES["file"]["type"];
$fileExtension = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
$isMP4 = ($fileType == "video/mp4" && $fileExtension == "mp4");
$isWMV = ($fileType == "video/x-ms-wmv" && $fileExtension == "wmv");
$isMPG = ($fileType == "video/mpeg" && ($fileExtension == "mpeg" || $fileExtension == "mpg"));
$is3GP = ($fileType == "video/3gp" && $fileExtension == "3gp");
$sizeIsOK = ($_FILES["file"]["size"] < 524288000);
if( ($isMP4 || $isWMV || $isMPG || $is3GP) && $sizeIsOK ) {
if($_FILES["file"]["error"] > 0) {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
die();
} else {
// Ensure that the file get's a unique name
$filename = $today . "-" . $random . "." . $fileExtension;
while(file_exists("$path/$filename")) {
$random = rand(0, 999);
$filename = $today . "-" . $random . "." . $fileExtension;
}
move_uploaded_file($_FILES["file"]["tmp_name"], "$path/$filename");
$description = $_POST['description'];
$query = "INSERT INTO media (eventID,FileName,File,filetype,Description) VALUES ($eventID,'$filename','$path','video','$description')";
if(!$res = mysql_query($query, $link))
echo "<p>Error storing file description. Please contact a system administrator.</p>";
else {
echo "<h3>File: <i>".$_FILES["file"]["name"]."</i></h3>";
if(strlen($description) > 0) {
echo "<h3>Description: <i>".$description."</i></h3>";
}
echo "<p><strong>Upload Complete</strong></p>";
}
echo "<button onclick=\"setTimeout(history.go(-1), '1000000')\">Go Back</button>";
}
} else {
echo "<p>There was a problem with your file. Please check that you submitted a valid .zip or .mxd file.</p>";
echo "<p>If this error continues, contact a system administrator.</p>";
}
?>
You cannot adjust the file upload limits using ini_set() from within the script that the uploads go to - the script does not get executed until after the upload is completed, so the ini_set() overrides cannot take place. The default parameters in PHP will be in place with the lower limit, and will kill the upload if it exceeds the system upload_max_filesize.
You need to override at the .ini level in PHP, or via a php_value directive in a .htaccess file. Those will change PHP's settings as the upload starts.
Ok, the first thing i thougt would be a problem with the filesize but other files with this size are working as you wrote.
But just do get shure it isn't a file size problem:
When you rise the max filesize you hmust also rise the max post size: post_max_size

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