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)
Related
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
Sorry I know there's a lot of posts about that but I can't find a solution in those.
Here's my form :
<form id="form1" action="upload.php" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Name : </td>
<td><input type="text" id="name" name="name"/></td>
</tr>
<tr>
<td>Image :</td>
<td><input type="file" name="image"/></td>
</tr>
<tr><td id='submitAdd' colspan='2'><input type="submit"
value= " Add " /></td></tr>
</table>
</form>
And here upload.php :
<?php
$ext = strtolower(substr(strrchr($_FILES['image']['name'], '.'),1));
$ret = move_uploaded_file($_FILES['image']['tmp_name'], 'item_images/'.$_POST['name'].'.'.$ext);
if ($ret) {
echo 'works';
}
else {
echo 'doesnt work'."</br>";
echo $_FILES['image']['error'];
}
?>
The directory's permission are ok, no uploading error, but still it won't move the file.
Am I missing something ?
Thanks in advance
I think you need to be specifying the absolute save path rather than the relative path it looks like you have now.
Ex. dirname(__FILE__).'/item_images/'.$_POST['name'].'.'.$ext
I would move the file under the uploaded file name, and then rename it. Also, some file type checking and security should be added to this.. Sanitize the post ect.. Here is how I would do it.
upload.php
<?php
$fileName = $_FILES["image"]["name"]; // The file name
$fileTmpLoc = $_FILES["image"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["image"]["type"]; // The type of file it is
$fileSize = $_FILES["image"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["image"]["error"]; // 0 for false... and 1 for true
$kaboom = explode(".", $fileName); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
$fname = $kaboom[0];
$exten = strtolower($fileExt);
//now we do some security checks
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
} else if($fileSize > 5242880) { // if file size is larger than 5 Megabytes
echo "ERROR: Your file was larger than xxx Megabytes in size.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if (!preg_match("/.(gif|jpg|png)$/i", $fileName) ) {
// This condition is only if you wish to allow uploading of specific file types
echo "ERROR: Your image was not .gif, .jpg, or .png.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
echo "ERROR: An error occured while processing the file. Try again.";
exit();
}
//give it the new name
$userstring= $_POST['name'];
$string = $fname.$userstring.'.'.$exten;
$image_name = preg_replace('/\s+/', '', $string);
//now we move it.
$moveResult = move_uploaded_file($fileTmpLoc, "item_images/$image_name");
// Check to make sure the move result is true before continuing
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
$imageFile = "item_images/$image_name";
//$imageFile is the variable to use in the rest of your script.
?>
I just how to fix this problem. This worked for me you can give it a try:
Just change
item_images/'.$_POST['name'].'.'.$ext);
to
'item_images/'basename($_FILES["image"]["name"])
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]);
I have a form, upon submission, it will create a new directory, all images submitted along with the form will be upload in the said directory.
this is the shortened code.
mkdir('uploads/'.$name, 0777, true); //create directory
$count = count($_FILES['images']['tmp_name']); //count all uploaded files
for ($i=0; $i<$count; $i++)
{
//formatting
$file = $_FILES['images']['name'][$i];
$filename = strtolower($file);
$random = rand(0, 999); //Random number to be added to name.
$newfile = $random.$filename; //new file name
//upload
if (move_uploaded_file($newfile, "uploads/".$name."/".$newfile))
{
echo "uploaded";
} else {
echo " failed";
}
}
if i echo the directory echo "upload to =" . $teamdir."/".$newfile;
it shows the correct path /uploads/john/567banner_0.jpg
but the image aren't being uploaded.
bool move_uploaded_file ( string $filename , string $destination )
Your first parameter has to be the source so you have to give it the temp name assigned
by php.
In your case : $_FILES['images']['tmp_name'][$i]
I feel you should add
$_SERVER['DOCUMENT_ROOT'].'/path/to/uploads/
in image destination path
Why does the following code echo "Your files have been successfully loaded." when I try to upload a 20mb .gif file, when it actually a)should have been prevented, and b) doesn't actually get uploaded? Basically, I'm trying to limit file upload type, size using php. Page one has a form, which submits up to 10 photos.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$namebase = $_POST['projectID'].'_';
$ProjID = $_POST['projectID'];
$counter = 0;
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if ($_FILES['userfile']) {
$file_ary = reArrayFiles($_FILES['userfile']);
foreach ($file_ary as $file) {
$counter = $counter + 1;
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
if (empty($file['name'])) {
break; /* You could also write 'break 1;' here. */
}
$url_base="";
$max_filesize = 1048576; // Maximum filesize in BYTES (currently 1MB).
$upload_path = '../dev/images/uploaded/'; // The place the files will be uploaded to (currently a 'files' directory).
$allowed_filetypes = array('.jpg','.JPG'); // These will be the types of file that will pass the validation.
$ext = substr($file['name'], strpos($file['name'],'.'), strlen($file['name'])-1);// Get the extension from the filename.
$a='photo'.$counter;
${$a} = 'http:xxxxxxxxx'.$namebase.$counter.$ext;
if(!in_array($ext,$allowed_filetypes))
die('The file type of '.$file['name'].' you attempted to upload is not allowed. <INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($file['tmp_name']) > $max_filesize)
die($file['name'].' you attempted to upload is too large.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.<INPUT TYPE="button" VALUE="Back" onClick="history.go(-1);">');
// Upload the file to your specified path. can rename here.move_uploaded_file(original file name, destination path and filename)
if(move_uploaded_file($file['tmp_name'],$upload_path.$namebase.$counter.$ext)){
echo '<b> '.$file['name'].'</b>'.' Accepted. Renamed '.'<b>'.$namebase.$counter.$ext.'</b>'.'<br>';
// It worked.
}
else
die('There was an error during the file upload. Please try again.'); // It failed :(.
}
}
echo 'Your files have been successfully loaded.<br>';
?>
It's possible that your if ($_FILES['userfile']) is false, so it goes directly to the end of the file ;)
Print out $_FILES array
print_r($_FILES)
if it empty then you will get success message.