Upload two different files in the same form - php

The issue here is, when I Upload videos, it works perfectly but not images which is giving me a hard time to figure out what the error may be
This is what the HTML looks like:
<form action="index.php" method="post" enctype="multipart/form-data" >
<h1>Browse for file to upload:</h1>
</div>
<div>
<label for="file"><h1><b>Select Video</b></h1></label>
<input type="file" name="fileToUpload1[]" id="fileToUpload" >
<br><br>
<label for="file"><h2><b>Select Image</b></h2></label>
<input type="file" name="fileToUpload1[]" id="fileToUpload" >
<br><br>
<input type="submit" value="Upload" name="submit">
</form>
The PHP Script looks like this:
$error = null;
$success = null;
$info = [];
$uploadOk = 1;
$allowedMimes = ['video/mp4', 'image/jpg'];
if(isset($_POST["submit"])) {
$counter = 0;
foreach ( $_FILES['fileToUpload1']['name'] as $file ):
$target_file = UPLOAD_DIR . basename($file);
if ( in_array(mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter]), $allowedMimes) ){
if (move_uploaded_file($_FILES['fileToUpload1']["tmp_name"][$counter], $target_file)) {
$info[] = "File ".++$counter."($file) uploaded successfully";
}else {
$info[] = "File ".++$counter."($file) cannot be uploaded";
}
} else {
$info[] = "File ".++$counter. " is not allowed.";
}
endforeach;
} else {
echo "upload a file.";
}
?>
<ul>
<?php foreach($info as $i){ ?>
<li><?=$i;?></li>
<?php }?>
</ul>
<? } ?>

The mimetype of jpg files is actually image/jpeg (and not iamge/jpg), so if you are trying to upload jpg files you should change your $allowedMimes variable to:
$allowedMimes = ['video/mp4', 'image/jpeg'];
Also - if you want to support other image types you can use:
$allowedMimes = ['video/mp4', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp'];
Another option - if you want to support all image/audio/video types you can check only the first part of the string:
$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
array_shift(
explode("/",
mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
)
),
$allowedTypes) )
If you are using php>=5.4 you can use:
$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
explode("/",
mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
)[0],
$allowedTypes) )

Related

Uploading Multiple Files to Location and Updated Database

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>

Warning: Invalid argument supplied for foreach() - uploading photos form

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.

PHP multiple images upload

I know this question is repeated over and over.. But can't seem to find solution for my problem...
How can I create a form which will allow user to upload xy images at once?
Here's my html code:
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
And here's my php code:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>
Is it possible to solve this problem with foreach? If so, how should I do that?
Try this (add as many file fields as you want):
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" /><br />
<input type="file" name="image[]" />
Php:
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if(isset($_FILES['image'])){
for($i=0; $i<count($_FILES['image']['name']); $i++){
if( #is_uploaded_file($_FILES['image']['tmp_name'][$i]) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image']['name'][$i], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'][$i] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image']['tmp_name'][$i], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
echo "<p>$status</p>";
}
}
?>
<form class="pure-form" action="upload.php" enctype="multipart/form-data" method="post">
<div class="upload">
<a onclick="select_file()" class="pure-button">Choose a Image</a>
<input id="image" type="file" name="image[1]" multiple="multiple">
<input id="image" type="file" name="image[2]" multiple="multiple">
</div>
<!--image preview-->
<img src="" style="display:none">
<input class="pure-button pure-button-primary" type="submit" value="Upload!">
</form>
PHP
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$max_size = 2048 * 1024; // max file size (200kb)
$path = 'uploads/'; // upload directory
if ( $_SERVER['REQUEST_METHOD'] === 'POST' )
{
if( #is_uploaded_file($_FILES['image1']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image1']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image1']['tmp_name'], $path))
if( #is_uploaded_file($_FILES['image2']['tmp_name']) )
{
// get uploaded file extension
$ext = strtolower(pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION));
// looking for format and size validity
if (in_array($ext, $valid_exts) AND $_FILES['image2']['size'] < $max_size)
{
// unique file path
$path = $path . uniqid(). '.' .$ext;
// move uploaded file from temp to uploads directory
if (move_uploaded_file($_FILES['image2']['tmp_name'], $path))
{
$status = 'Image uploaded successfully!';
$status = $path;
}
else {
$status = 'Upload Fail: Unknown error occurred!';
}
}
else {
$status = 'Upload Fail: Unsupported file format or It is too large to upload!';
}
}
else {
$status = 'Upload Fail: File not uploaded!';
}
}
else {
$status = 'Bad request!';
}
}}
// echo out json encoded status
echo json_encode(array('status' => $status));
?>

php image file upload and convert to base64 without saving image

I know how to upload image file and save to other location by using the following code. However, I need to do in such a way that user upload image and automatically convert to base64 without saving that image in my location. How should I do?
<?php
//print_r($_FILES);
if(isset($_FILES['image']))
{
$errors=array();
$allowed_ext= array('jpg','jpeg','png','gif');
$file_name =$_FILES['image']['name'];
// $file_name =$_FILES['image']['tmp_name'];
$file_ext = strtolower( end(explode('.',$file_name)));
$file_size=$_FILES['image']['size'];
$file_tmp= $_FILES['image']['tmp_name'];
echo $file_tmp;echo "<br>";
$type = pathinfo($file_tmp, PATHINFO_EXTENSION);
$data = file_get_contents($file_ext);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "Base64 is ".$base64;
if(in_array($file_ext,$allowed_ext) === false)
{
$errors[]='Extension not allowed';
}
if($file_size > 2097152)
{
$errors[]= 'File size must be under 2mb';
}
if(empty($errors))
{
if( move_uploaded_file($file_tmp, 'images/'.$file_name));
{
echo 'File uploaded';
}
}
else
{
foreach($errors as $error)
{
echo $error , '<br/>';
}
}
// print_r($errors);
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<p>
<input type="file" name="image" />
<input type="submit" value="Upload">
</p>
</form>
There is a mistake in your code:
$data = file_get_contents( $file_ext );
This should be:
$data = file_get_contents( $file_tmp );
This should solve your problem.

PHP Multiple File Array

I have the following code which works and uploads but it will not cycle through the array to upload every file, just the first file.
<form method="post" enctype="multipart/form-data" action="http://<?php echo $pageURL;?>">
<input class="new" multiple="multiple" name="documents[]" type="file" />
<input class="new" multiple="multiple" name="documents[]" type="file" />
<input type="submit" class="button" name="addMaterials" value="Add" />
<?php
foreach($_FILES['documents']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['documents']['name'][$key];
$file_size =$_FILES['documents']['size'][$key];
$file_tmp =$_FILES['documents']['tmp_name'][$key];
$file_type=$_FILES['documents']['type'][$key];
move_uploaded_file($file_tmp,"files/".time().$file_name);
}
?>
I need it to cycle through my documents[] file array.
Example print_r() of the documents array:
Array (
[name] => Array ( [0] => AcroRd32.exe )
[type] => Array ( [0] => application/x-msdownload )
[tmp_name] => Array ( [0] => C:\xampp\tmp\phpE8BD.tmp )
[error] => Array ( [0] => 0 )
[size] => Array ( [0] => 1343112 )
)
Any help appreciated.
you can use my updated code and as per my demo it is working perfect for multiple file upload
<?php
if(isset($_FILES['documents'])){
foreach($_FILES['documents']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['documents']['name'][$key];
$file_size =$_FILES['documents']['size'][$key];
$file_tmp =$_FILES['documents']['tmp_name'][$key];
$file_type=$_FILES['documents']['type'][$key];
move_uploaded_file($file_tmp,"galleries/".time().$file_name);
}
}else{
echo "<form enctype='multipart/form-data' action='test1.php' method='POST'>";
echo "File:<input name='documents[]' multiple='multiple' type='file'/><input type='submit' value='Upload'/>";
echo "</form>";
}
?>
For anyone trying to do it with a single file php function (i`m using classes, but you can change to a function):
html:
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
<input type="file" name="foto[]" />
php:
if (isset($_FILES['foto'])) {
$arquivo = array();
foreach ($_FILES['foto']["name"] as $file=>$key) {
// the empty input files create an array index too, so we need to
// check if the name exits. It means the file exists.
if (!empty($_FILES['foto']["name"][$file])) {
$arquivo ["name"] = $_FILES['foto']["name"][$file];
$arquivo ["type"] = $_FILES['foto']["type"][$file];
$arquivo ["tmp_name"] = $_FILES['foto']["tmp_name"][$file];
$arquivo ["error"] = $_FILES['foto']["error"][$file];
$arquivo ["size"] = $_FILES['foto']["size"][$file];
$foto = new foto(); // create an obj foto
// $arquivo means file, it`s our file format as a single $_file['file']
if ($foto -> upload($arquivo)) { // if its uploaded than save
$foto -> save();
}
}
}
}
on my foto class:
public function upload($foto) {
$upload_dir = "D:/xampp/htdocs/prova/fotos/";
$file_dir = $upload_dir . $foto["name"];
$move = move_uploaded_file($foto["tmp_name"], $file_dir);
$this -> arquivo = $foto["name"]; // use this to save to db later
// this serves to return true if the file is uploaded
$retorno = ($move) ? 1 : 0;
return $retorno;
}
Try with this code for multifile upload
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
In PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
To show the file name using javascript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
it's easy to upload multiple files, follow these steps.
use array notation means square brackets with the name of the input like this
<input type="file" id="indtbl_logo[]" name="indtbl_logo[]" multiple />
you can loop throught this using $_FILES Global Variable
foreach ($_FILES['indtbl_logo']['tmp_name'] as $key => $tmp_name) {
$file_name = $key . $_FILES['indtbl_logo']['name'][$key];
$file_size = $_FILES['indtbl_logo']['size'][$key];
$file_tmp = $_FILES['indtbl_logo']['tmp_name'][$key];
$file_type = $_FILES['indtbl_logo']['type'][$key];
echo $file_name;
echo "<br>";
}
Try this way of loop your documents array()
<?php
foreach($_FILES['documents']['tmp_name'] as $key => $tmpName) {
$file_name = $_FILES['documents']['name'][$key];
$file_type = $_FILES['documents']['type'][$key];
$file_size = $_FILES['documents']['size'][$key];
$file_tmp = $_FILES['documents']['tmp_name'][$key];
move_uploaded_file($file_tmp,"files/".time().$file_name);
}
?>
File upload using multiple input fields.
HTML
<form action="" method="post" enctype="multipart/form-data">
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<p><input type="file" name="file_array[]"></p>
<input type="submit" value="Upload all files">
</form>
PHP
<?php
if(isset($_FILES['file_array'])){
$name_array = $_FILES['file_array']['name'];
$tmp_name_array = $_FILES['file_array']['tmp_name'];
$type_array = $_FILES['file_array']['type'];
$size_array = $_FILES['file_array']['size'];
$error_array = $_FILES['file_array']['error'];
for($i = 0; $i < count($tmp_name_array); $i++){
if(move_uploaded_file($tmp_name_array[$i], "test_uploads/".$name_array[$i])){
echo $name_array[$i]." upload is complete<br>";
} else {
echo "move_uploaded_file function failed for ".$name_array[$i]."<br>";
}
}
}
?>

Categories