I'm having troubles uploading a bunch of files from a form. I need to make the input fields separately, my form is something like this:
<form action="upload.php" method="post" id="form" name="form" enctype="multipart/form-data">
<input type="file" name="upload[]" >
<input type="file" name="upload[]" >
...(more inputs)
<input type="file" name="upload[]" >
<button id="submit-button">Upload</button>
</form>
I'm using jQuery 1.9 for this project for anything else but this upload, I can't seem to find anything that suits what I'm trying to do. I found a lot of multiple input stuff, but in that way I can't differenciate every file from one another, and I need to so save the url of every file to the right column in my DB.
I've used some of the code I've found on other similar questions but they doesn't seem to work. I've tried this one now :
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ((array)$_FILES['upload']['name'] as $f => $name) {
if ($_FILES['upload']['error'][$f] == 4) {
continue; // Skip file if any error found
}
if ($_FILES['upload']['error'][$f] == 0) {
if ($_FILES['upload']['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["upload"]["tmp_name"][$f], $path.$name))
$count++; // Number of successfully uploaded file
}
}
}
}
I just get plain nothing, and the file I'm trying to upload doesn't show up on the server. I've checked with php_info() and it seems that the upload is enabled, and since I'm uploading a .pdf with just "Test" written on it about 7kb, I think the size is not the problem here.
I hope you guys can help me out, thanks.
UPDATE
I've removed the (array) casting and I have the following error:
Warning: Invalid argument supplied for foreach() in path_of_file
You are missing very important element in this which is enctype.
enctype='multipart/form-data'
Use this in your form tag and check again.
<form action="upload.php" method="post" enctype='multipart/form-data' id="form" name="form">
-> For your error, use the following code (updated) to upload multiple images
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['username']['name'] as $f => $name) {
$path = 'uploads'; //path of directory
if ($_FILES['username']['error'][$f] == 4) {
continue; // Skip file if any error found
} else {
if ($_FILES['username']['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
//$name_of_file = $_FILES['username']['name'][$f];
$temp_name = $_FILES['username']['tmp_name'][$f]; //[$count];
move_uploaded_file($temp_name, "$path/"."$name");
$count++; // Number of successfully uploaded file
}
}
}
}
Related
How we can check if the files are empty while uploading multiple files simultaneously in codeigniter?
<input type="file" name = "user_file[]" multiple />
<input type="file" name = "user_file[]" multiple />
Controller Code:
if (empty($_FILES['user_file']['name'])) {
echo'<script>alert("please upload a file or write something")</script>';
exit();
}
But it is not working, empty files also uploading?? please anyone provide solution for this ...
You can use
if (filesize($file_path) == 0){
echo "The file is empty";
}
or also try
if (trim(file_get_contents($file_path)) == false) {
echo "The file is empty";
}
try this
if ($_FILES["fileToUpload"]["size"] == 0) {
echo "Sorry, your file is empty.";
}
Hello! I have file upload that I want to upload only six images not less not more only six images with the PNG and JPG types i have written the below code.
But that is giving this below error please some one check my code and find the mistakes.
"Warning: preg_match() expects parameter 2 to be string, array given in C:\xampp\htdocs\hiddenprocess.php on line 21
Your Images Must Be JPG OR PNG And equal to six images
Warning: preg_match() expects parameter 2 to be string, array given in C:\xampp\htdocs\hiddenprocess.php on line 21
Your Images Must Be JPG OR PNG And equal to six images"
HTML Code:
<form name="myWebForm" action="hiddenprocess.php" method="post" enctype="multipart/form-data">
<input type="file" name="Upload_Property_Images[]" multiple="multiple"/>
<input type="submit" name="submit" value="Upload_Images" style="cursor:pointer;"/>
</form>
Here is the PHP FILE UPLOAD CODE:
<?php
$imagename = $_FILES['Upload_Property_Images']['name'];
$imagetype = $_FILES["Upload_Property_Images"]['type'];
if (empty($imagename))
{
echo 'You have\'nt Entered Value for upload field';
exit();
}
else
{
$whitelist = array(".jpg",".png");
foreach ($whitelist as $item)
{
if(preg_match("/$item\$/i", $imagename) && count($imagename ==6))
{
//code for uploading goes in here
}
else
{
echo 'Your Images Must Be
-JPG OR PNG
-Only six images allowed';
}
}
}
?>
Try following:
// Process files one by one
foreach($_FILES as $file) {
// Allowed file types
$whitelist = array("jpg","png");
// Match uploaded file extension
if ( in_array(end(explode('.', $file['Upload_Property_Images']['name'])), $whitelist ) {
// Count total uploads
if (count($_FILES['Upload_Property_Images']) == 6) {
// Code here
} else {
// Count error
}
} else {
// File extension error
}
}
Here is the form
form action="index.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
I am trying to only run my code when only when if(!empty($_FILES['image'])){ but for some reason the array is not empty upon submitting no files and only clicking submit.
Here is the rest of the code if that will help, thanks.
<html>
Image Upload
<form action="index.php" method="POST" enctype="multipart/form-data" >
<input type="file" name="image[]" multiple="multiple">
<input type="submit" value="upload">
</form>
<?php
include 'connect.php';
if(!empty($_FILES['image'])){
echo $_FILES['image']['error'];
$allowed = array('jpg', 'gif', 'png', 'jpeg');
$count = 0;
foreach($_FILES['image']['name'] as $key => $name){
$image_name = $name;
$tmp = explode('.', $image_name);
$image_extn = strtolower(end($tmp)); //can only reference file
$image_temp = $_FILES['image']['tmp_name'][$count];
$filesize = filesize($_FILES['image']['tmp_name'][$count]);
$count = $count +1;
if(count($_FILES['image']['tmp_name']) > 5){
echo "You can upload a maximum of five files.";
break;
}
else if(in_array($image_extn, $allowed) === false){
echo $name." is not an allowed file type<p></p>";
}
else if($filesize > 1024*1024*0.3){
echo $name." is too big, can be a maximum of 3MB";
}
else{
$image_path = 'images/' . substr(md5($name), 0, 10) . '.' . $image_extn;
move_uploaded_file($image_temp, $image_path);
mysql_query("INSERT INTO store VALUES ('', '$image_name', '$image_path')") or die(mysql_error());
$lastid = mysql_insert_id();
$image_link = mysql_query("SELECT * FROM store WHERE id = $lastid");
$image_link = mysql_fetch_assoc($image_link);
$image_link = $image_link['image'];
echo "Image uploaded.<p></p> Your image: <p></p><a href = $image_link>$image_path</a>";
}
}
}
else{
echo "Please select an image.";
}
?>
This is how $_FILES array looks like when nothing uploaded
Array ( [image] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) )
So it's never empty.
The error code 4 [error] => 4 indicates no file was uploaded and error code 0 indicates no error and file was uploaded so you can check
if($_FILES['image']['error']==0) {
// file uploaded, process code here
}
Here is another answer on SO.
Use the is_uploaded_file PHP function instead:
if(is_uploaded_file($_FILES['image']['tmp_name'])) {
//code here
}
http://php.net/manual/en/function.is-uploaded-file.php
You should first of all take a look into the PHP manual because - you're not the first one with that problem - the solution has been written in there:
If no file is selected for upload in your form, PHP will return $_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name'] as none.
So if you actually want to find out if any file for the image element has has been submitted, check for it:
$noFile = $_FILES['image']['size'][0] === 0
&& $_FILES['image']['tmp_name'][0] === '';
Yes, that simple it is.
The test you used:
empty($_FILE);
will only tell you if the whole form has been submitted or not. So an example in full:
$submitted = empty($_FILE);
if ($submitted) {
$noFile = $_FILES['image']['size'][0] === 0
&& $_FILES['image']['tmp_name'][0] === '';
if ($noFile) {
...
}
}
Check value is not null:
in_array(!null,$_FILES['field_name']['name'])
if($_FILES['image']['error'] === UPLOAD_ERR_OK) {
// Success code Goes here ..
}
UPLOAD_ERR_OK returns value 0 if there is no error, the file was uploaded successfully.
http://php.net/manual/en/features.file-upload.post-method.php
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name']
as none.
You get an array entry per "file" upload field, even if the user didn't select a file to upload.
I have confronted this issue with a multiple file input.
What I found to be working for checking if any file has been selected is:
<?php
$size_sum = array_sum($_FILES['img']['size']);
if ($size_sum > 0) {
// at least one file has been uploaded
} else {
// no file has been uploaded
}
?>
if(!empty($_FILES['image']['name'][0]) || !empty($_FILES['image']['name'][1]) ||
!empty($_FILES['image']['name'][2]))
or
for($1=0;$i<count($_FILES['image']);$i++){
if(!empty($_FILES['image']['name'][$i])){
// do something
}
}
if(isset($_FILES['file'])){//do some thing here}
am having some trouble with PHP on the webserver I am using.
I am sure the answer is obvious but for some reason it is eluding me completely.
I have a php file which uploads two files, a before and an after shot of the client.
The script on my server(localhost) works fine, it uploads the files, renames the files to a timestamp and puts the images into there folders for further sorting by another script.
Yet when I upload it to the webserver, and some files work (i.e mel.jpg, test.jpg) but files like IMG_0042.jpg do not work, Im sure the answer is something simple, but is completely eluding me.
Im thinking the underscore may have something to do with it, but cannot for the life of my figure it out, any help greatly appreciated,
thanks very much.
<?php
if(!isset($_COOKIE['auth'])) {
header("Location: login12.php");
exit();
}
$page_title="test";
include('header.html');
// Upload and Rename File
if (isset($_POST['submitted'])) {
$filenamebef = $_FILES["uploadbef"]["name"];
$filenameaft = $_FILES["uploadaft"]["name"];
$file_basename_bef = substr($filenamebef, 0, strripos($filenamebef, '.'));
$file_basename_aft = substr($filenameaft, 0, strripos($filenameaft, '.'));
// get file extention
$file_ext_bef = substr($filenamebef, strripos($filenamebef, '.'));
$file_ext_aft = substr($filenameaft, strripos($filenameaft, '.'));
// get file name
$filesize_bef = $_FILES["uploadbef"]["size"];
$filesize_aft = $_FILES["uploadaft"]["size"];
$allowed = array('image/pjpeg','image/jpeg','image/JPG','image/X-PNG','image/PNG','image /png','image/x-png');
if ((in_array($_FILES['uploadbef']['type'], $allowed)) && in_array($_FILES['uploadaft']['type'], $allowed)) {
if (($filesize_bef < 200000) && ($filesize_aft < 200000)){
// rename file
$date = date("mdy");
$time = date("His");
$timedate = $time . $date;
$newfilenamebef = $timedate . $file_ext_bef;
$newfilenameaft = $timedate . $file_ext_aft;
if ((file_exists("upload/images/before" . $newfilenamebef)) && (file_exists("uploads/images/after" . $newfilenameaft))) {
// file already exists error
echo "You have already uloaded this file.";
} else {
move_uploaded_file($_FILES["uploadbef"]["tmp_name"], "uploads/images/before/" . $newfilenamebef) && move_uploaded_file($_FILES["uploadaft"]["tmp_name"], "uploads/images/after/" . $newfilenameaft);
echo "File uploaded successfully.";
}
}
} elseif ((empty($file_basename_bef)) && (empty($file_basename_aft))) {
// file selection error
echo "Please select a file to upload.";
} elseif (($filesize_bef > 200000) && ($filesize_aft > 200000)) {
// file size error
echo "The file you are trying to upload is too large.";
} else {
// file type error
echo "Only these file typs are allowed for upload: " . implode(', ',$allowed);
unlink($_FILES["uploadbef"]["tmp_name"]);
unlink($_FILES["uploadaft"]["tmp_name"]);
}
}
echo $newfilenamebef;
echo $newfilenameaft;
?>
<form enctype="multipart/form-data" action="uploading.php" method="post">
<input type="hidden" value="MAX_FILE_SIZE" value="524288">
<fieldset>
<legend>Select a JPEG or PNG image of 512kb or smaller to be uploaded : </legend>
<p><b>Before</b> <input type="file" name="uploadbef" /></p>
<p><b>After</b> <input type="file" name="uploadaft" /></p>
</fieldset>
<div align="center"><input type="submit" name="submit" value="Submit" /></div>
<input type="hidden" name="submitted" value="TRUE" />
</form>
<?php
include('footer.html');
?>
You should but these two lines at the top of your index.php or bootstrap.php :
error_reporting( -1 );
ini_set( "display_errors" , 1 );
And see if some error messages turn up.
It is quite possible that problem is caused by wrong file permissions.
At a quick guess I would say that your localhost is not case sensitive, whereas your webserver is.
In other words, on your localhost IMG_12345.JPG is the same as img_12345.jpg. On your webserver, though, they are treated differently.
Without any actual reported errors, it's hard to be certain, but this is a common problem.
You're not checking for valid uploads properly. Something like the following would be FAR more reliable:
// this value is ALWAYS present and doesn't depend on form fields
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errmsgs = array();
if ($_FILES['uploadbef']['error'] !== UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadebef' failed with code #" . $_FILES['uploadebef']['error'];
}
if ($_FILES['uploadaft']['error'] === UPLOAD_ERR_OK) {
$errs++;
$errmsgs[] = "'uploadeaft' failed wicode #" . $_FILES['uploadeaft']['error'];
}
if (count($errmsgs) > 0) {
print_r($errmsgs);
die();
}
... process the files here ...
}
As well, why re-invent the wheel to split up the file names?
$parts = path_info($_FILES['uploadaft']['name']);
$basename = $parts['basename'];
$ext = $parts['extension'];
There may be a better way of doing this and I'm certainly open to suggestions.
I have a file upload script that will handle multiple uploads. What I want to do is count the number of iterations that the loop makes for each file that was successfully moved and if that number equals the total number of files uploaded, then use an exception to show the user that the files were received.
I thought that I would increment inside the loop then count from there but what I am getting is an array for each file that is uploaded which results in an incorrect total. Is there a better way to do this or successfully count each iteration?
This is the structure I have to work with
foreach($files as $file)
{
if ($file['error'] == UPLOAD_ERR_OK)
{
move_uploaded_file($file['tmp_name'], $filename);
}
else
{
//error
}
}
You pretty much have to do it with a counter.
$success = 0;
foreach($_FILES as $file) {
if(is_uploaded_file($file['tmp_name'])) {
move_uploaded_file($file['tmp_name'], $destination);
$success += 1;
}
}
if($success != count($_FILES)) {
//error message / exception
}
Edit - You can set an error flag, or flags in your error handling... but there's not really a way to do this that is insanely better.
foreach($files as $file)
{
if ($file['error'] == UPLOAD_ERR_OK)
{
move_uploaded_file($file['tmp_name'], $filename);
}
else
{
//error
$upload_errors += 1;
//or, to get a little more info...
//$upload_errors[] = $file
}
}
if( $upload_errors == 0) { //or count($upload_errors) == 0
// tell the user that the upload failed.
}
foreach ($array as &$item)
You can just do count($array)
Just throwing this out there since you know the number of files how but just using a for loop. with two counters one for the loop and one for successes, and unless your script fails mostly ( and you want to not how unusual it is that everything worked) don't throw an exception if everything works.
Here you can see that you can use count($_FILES) to count the number of uploaded files. Mind you, this is not the number of correctly uploaded files.
<?php
if (isset($_FILES) && !empty($_FILES)) {
echo count($_FILES).' files were uploaded<br>';
?><pre><?php
print_r($_FILES);
?></pre><?php
}
?>
<form
action="<?php echo $_SERVER['PHP_SELF'];?>"
method="post"
enctype="multipart/form-data"
>
File 1<input type="file" name="file1"><br>
File 2<input type="file" name="file2"><br>
File 3<input type="file" name="file3"><br>
<input type="submit" value="upload">
</form>