I have been working on a multi-image upload function that I can't seem to make work. It currently will only work if I have a single image uploaded. I can't figure out what is going wrong with this script.
This is the function to upload images:
if(isset($_POST["btnSubmit"])){
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 1000000;
$allowedKB = 10485760000;
$totalBytes = $allowedKB * $bytes;
$imgDir = "assets/users/".$userLoggedIn."/images/";
if(isset($_FILES["files"])==false)
{
echo "<b>Please, Select the files to upload!!!</b>";
return;
}
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size is too big. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename = basename($file_name,$ext);
$newFileName = uniqid().$filename.$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$imgDir.$newFileName);
// current date and time
$date_added = date("Y-m-d H:i:s");
$imagePath = $imgDir.$newFileName;
$query = "INSERT INTO images(date_added, added_by, image, deleted) VALUES('$date_added', '$userLoggedIn','$imagePath', 'no')";
mysqli_query($con, $query);
}
}
header("Location: edit-images.php");
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
?>
I thought the issue might be with size but I cut the condition to prevent it from uploading with no luck. I feel like I might be missing something in the foreach but I am completely stuck. I appreciate your help!
Here is the form I am using to upload:
<form method="post" enctype="multipart/form-data" name="formUploadFile" id="uploadForm" action="edit-images.php">
<div class="form-group">
<label for="exampleInputFile">Select file to upload:</label>
<input type="file" id="exampleInputFile" name="files[]" multiple="multiple">
<p class="help-block"><span class="label label-info">Note:</span> Please, Select the only images (.jpg, .jpeg, .png, .gif)</p>
</div>
<button type="submit" class="btn btn-primary" name="btnSubmit" >Start Upload</button>
</form>
Related
I created a multiple image upload form (the images are stored in a folder, and the informations in a MySQL database). To the images are associated some informations, like a description, a name, etc.
Often, when I upload many images (like 3,4), one/two of them aren't uploaded, and an error message appears (An error has occurred while uploading the file). Then, if I retry to upload the image not uploaded, no error occurs. Sometimes it appends, sometimes not, and I don't understand what the problem is (I think it is not normal).
Here you can see my PHP code and also my HTML form:
When the user clicks on the input type="file", my code just creates another input and hides the old one (so that, if the user wants upload more files, those already uploaded are not deleted).
function boomFunction(obj) {
obj.style.display = 'none';
$(".upload-container").append("<input name='upload[]' type='file' multiple='multiple' id='upload' class='upload' onclick='boomFunction(this)' title='Carica un altro file!'>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="result.php" method="post" enctype="multipart/form-data" class="form-inline" autocomplete="off" novalidate>
<div class="upload-container">
<input name="upload[]" type="file" multiple="multiple" id="upload" class="upload" required="required" aria-required="true" onclick="boomFunction(this)" title="Choose a file!">
</div><br>
<label>Subjects:</label>
<textarea type="text" id="argomenti" name="argomenti" required="required" aria-required="true" placeholder="Subjects..."></textarea><br>
<label for="anno">Year:</label>
<select id="anno" name="anno" required="required" aria-required="true">
<option value="" disabled selected>Choose year</option>
<option value="2016-2017">2016-2017</option>
<option value="2017-2018">2017-2018</option>
<option value="2018-2019">2018-2019</option>
</select><br>
<input type="submit" value="Carica i file" class="upload_button"><br><br><br>
</form>
Then, here is my result.php page.
<?php
$total = count(array_filter($_FILES['upload']['name'])); // Count the number of uploaded files
$timestamp = time();
if ($total==0) {
echo "<h2>You must upload at least one file.</h2>";
$uploadOk = 0;
} else {
for($i = 0; $i < $total; $i++) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != '') {
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
$nomeCompletoFile = basename($_FILES["upload"]["name"][$i]);
$target_file = "uploads/$nomeCompletoFile"; $uploadOk = 1;
$estensione = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
if($estensione != 'jpg' && $estensione != 'png' && $estensione != 'jpeg') {
echo "<h2>Just JPG e PNG files are allowed.</h2>";
$uploadOk = 0;
}
elseif (empty($_POST["argomenti"]) or empty($_POST["anno"])) {
echo "<h2>You cannot leave empty fields</h2>";
$uploadOk = 0;
} else {
$nomeFile = str_replace(".$estensione", '', $nomeCompletoFile);
$string = base64_encode(openssl_random_pseudo_bytes(15)); // Random 15 letters for the new file name
$id = rand(1, 100000); $nomeFinaleFile = 'uploads/'.$string.$id.'.'.$estensione;
if (move_uploaded_file($_FILES["upload"]["tmp_name"][$i], $nomeFinaleFile)) {
$argomenti = stripslashes(htmlspecialchars($_POST['argomenti']));
$anno = $_POST['anno'];
$mysqli = new mysqli('localhost', 'name', '', 'my_name');
$mysqli->query("INSERT INTO uploads (timestamp, file, argomenti, anno, nFile) VALUES ('$timestamp', '$nomeFinaleFile', '$argomenti', '$anno', '$i')");
echo "<h2>The file <i>$nomeFile</i> has been uploaded.</h2>";
} else echo "<h2>An error has occurred while uploading the file</h2>";
}
}
}
}
?>
There seems to be no mistakes, indeed sometimes all works correctly.
Any help will be appreciated
Use base64encode url safe
replace
$string = base64_encode(openssl_random_pseudo_bytes(15)); // Random 15 letters for the new file name
to
$string = rtrim(strtr(base64_encode(openssl_random_pseudo_bytes(15)), ['+' => '-', '/' => '_']), '=');
Hi I'm new to php and keep getting this error: "Warning: Invalid argument supplied for foreach() in /home/site/folder/upload.php on line 61."
I'm trying to build a form in which users can upload one or more photos automatically to a directory to then be displayed else where.
Whenever I use this form I created it functions properly on my website but unfortunately it keeps printing that error out and would like it to go away. Here is my code I'm working with:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
// check if uploads directory exists
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
?>
</div>
Try
if (count($_FILES)) {
foreach($_FILES["images"]["name"] as $k=>$name) {
....
}
}
I tested your script, it works fine. The error message appears because you are not checking that a file got uploaded before starting the foreach. If I land on the page, the PHP code will still be triggered. To fix this, you may use the below:
<div>
<form action="upload.php" enctype="multipart/form-data" method="POST">
<input type="file" name="images[]" multiple="multiple"/>
<input type="submit" name="submit" value="upload images"/>
<form/>
<?php
if( $_POST['submit'] ) {
$dir = "images/";
if(!is_dir($dir))
{
echo "Directory not found, let's create the folder.";
mkdir($dir,"0777", true);
}
$countimg = 0;
$allimg = 0;
foreach($_FILES["images"]["name"] as $k=>$name)
{
$allimg++;
$imgname = $_FILES["images"]["name"][$k];
$sizeimg = $_FILES["images"]["size"][$k];
$tmpname = $_FILES["images"]["tmp_name"][$k];
//2.
$extension = strtolower(pathinfo($dir.$imgname, PATHINFO_EXTENSION));
if($extension=='png' || $extension=='jpg' ||$extension=='jpeg' ||$extension=='gif')
{
if($sizeimg < 2097152){
if(!file_exists($dir.$imgname)){
//1.
if(move_uploaded_file($tmpname,$dir.$imgname))
{
$countimg++;
}
}
}
}
}
echo "You are trying to upload $allimg images".'<br>';
echo "From $allimg image(s) - $countimg was/were uploaded with success".'<br>';
$z = $allimg - $countimg;
echo "$z image(s) were not uploaded: Not an image, over 2MB, or already uploaded.";
}
?>
</div>
if( $_POST['submit'] ) will ensure that the form is submitted prior to running the rest of the PHP code.
I am using $_FILES for multiple file upload the problem is it is not validating the null condition i have two multiple input files and I want to check whether an image has been uploaded to a specific input type file and on the basis of that I am validating if input 1 has no image uploaded then do nothing I went through dozens of examples on the internet but still it is running both blocks. Here's my code:
<form method="post" action="flyers_admin_process.php" enctype='multipart/form-data'>
<h4 style="margin-bottom: 8%;">Add flyers for Canada(You Can Choose multiple Files)</h4>
<div style="margin-top: 2%;margin-bottom: 6%" class="uk-width-large-1 uk-width-medium-1-1">
<input type="file" id="fileName" name="fileName[]" multiple>
</div>
<h4 style="margin-bottom: 8%;">Add flyers for USA(You Can Choose multiple Files)</h4>
<div style="margin-top: 2%;margin-bottom: 6%" class="uk-width-large-1 uk-width-medium-1-1">
<input type="file" id="fileName2" name="fileName2[]" multiple>
</div>
<input type="submit" />
</form>
flyers_admin_process.php file
<?php
include "db.php";
if($_SERVER['REQUEST_METHOD']=="POST") {
if(!empty($_FILES["fileName"]["name"])) {
echo "inside 1";
$path = "flyers_canada/"; // Upload directory
$count = 0;
foreach ($_FILES['fileName']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["fileName"]["tmp_name"][$f], $path.$name))
$filetmp = $_FILES["fileName"]["tmp_name"][$f];
$filename = $_FILES["fileName"]["name"][$f];
$filepath = "flyers_canada"."/".$filename;
$query="INSERT INTO `flyers_canada`(`path`) VALUES (?)";
$stmt = $db->prepare($query);
if($stmt){
$stmt->bind_param("s",$filepath);
$stmt->execute();
$stmt->close();
}
$count++; // Number of successfully uploaded file
}
}
if(!empty($_FILES["fileName2"]["name"])) {
echo "inside 2";
$path = "flyers_usa/"; // Upload directory
$count = 0;
foreach ($_FILES['fileName2']['name'] as $f => $name) {
if(move_uploaded_file($_FILES["fileName2"]["tmp_name"][$f], $path.$name))
$filetmp = $_FILES["fileName2"]["tmp_name"][$f];
$filename = $_FILES["fileName2"]["name"][$f];
$filepath = "flyers_usa"."/".$filename;
$query="INSERT INTO `flyers_usa`(`path`) VALUES (?)";
$stmt = $db->prepare($query);
if($stmt){
$stmt->bind_param("s",$filepath);
$stmt->execute();
$stmt->close();
}
$count++; // Number of successfully uploaded file
}
}
?>
<script language="javascript">
// alert('Flyer has been added succesfully!');
// location.href = "flyers-admin.php";
</script>
<?php
}
?>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
i want to upload multi images in my database just url images the code is work fine but i can upload just one image i need to upload 3 images i have in database table e_img - e_img2 - e_img3 how can upload images url in 3 columns
this my class upload :
<?php
class Upload {
private $allowedExts = array('doc','docx','pdf','txt','jpg','png');
private $maxSize;
private $file;
private $uploadsDirecotry;
private $fileUrl;
private $filenames = array();
function __construct($file,$allowedExts,$uploadsDirecotry,$maxSize){
if(is_array($allowedExts) AND is_int($maxSize)){
$this->file = $file;
$this->allowedExts = $allowedExts;
$this->maxSize = $maxSize;
$this->uploadsDirecotry = $uploadsDirecotry;
}else{
throw new Exception("File extension must be in an array and max size value must be intger value.");
}
}
function uploadFiles(){
$file = $this->file;
$allowedExts = $this->allowedExts;
$maxsize = $this->maxSize;
$uploadsDir = $this->uploadsDirecotry;
for($i = 0; $i < count($file['name']); $i++){
$errors = array();
// print_r($_FILES);
$filename = $file['name'][$i];
$fileext = strtolower(end(explode('.',$filename)));
$filesize = $file['size'][$i];
$filetmpname = $file['tmp_name'][$i];
if(in_array($fileext, $allowedExts) === FALSE){
$errors[] = "Extension in sot allowed";
}
if($filesize > $maxsize){
$errors[] = "File size must be less than {$maxsize} KB !";
}
if(empty($errors)){
$random = rand(0,199);
$this->fileUrl = $random . "_" . date("d-m-Y") . "_" . $filename;
$destination = $uploadsDir. $random."_".date("d-m-Y") . "_" . $filename;
move_uploaded_file($filetmpname, $destination);
$this->filenames[] = $this->fileUrl;
}else{
foreach($errors as $error){
throw new Exception($error);
}
}
} // end for
return TRUE;
}
function getFileUrl()
{
return $this->fileUrl;
}
function getFilesNames()
{
return $this->filenames;
}
}
?>
and this html php file
<?php include 'header.php';
if(isset($_POST['add']))
{
$e_title = $_POST['e_title'];
$e_user = $userRow['user_name'];
try{
include 'models/Upload.php';
$file = $_FILES['e_img'];
$allowedExts = array('jpg','png','gif','jpeg');
$uploadsDirectory = "imgupload/";
$maxSize = 4000000;
$upload = new Upload($file, $allowedExts, $uploadsDirectory, $maxSize);
$upload->uploadFiles();
$e_img = $uploadsDirectory.$upload->getFileUrl();
}catch(Exception $exc){
echo'<div class="alert alert-block alert-danger">fail image uploaded</div>';
exit;}
$insert = $user->insert($e_title,$e_img,$e_user);
echo"<div class='alert alert-block alert-success'>Save success</div>";
exit;
}
?>
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
<?php include 'footer.php'; ?>
i try this but But it did not succeed
<form action='newads.php' method="POST" enctype="multipart/form-data">
<p>إضافة صور </p>
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img2[]' id="exampleInputFile">
<input type="file" name='e_img3[]' id="exampleInputFile">
<input type="submit" name='add' class='btn btn-primary' value='add' />
</form>
You do not need to increment the field names in your file fields. That will break the array when PHP receives it. Change to this: (they should all be e_img[]
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">
<input type="file" name='e_img[]' id="exampleInputFile">
I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php