PHP multiple files upload - php

Yes, I know that there are hundreds of questions similar, but I didn't find a working answer...
The problem is: I want upload multiple files...
The correct way should be this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="?u=1">
<input type="file" name="myFile[]" />
<input type="file" name="myFile[]" />
<input type="file" name="myFile[]" />
<input type="submit" value="Upload!" name="submit"/>
</form>
<?
if ($_GET['u']){
foreach ($_FILES["myFile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["myFile"]["tmp_name"][$key];
$name = $_FILES["myFile"]["name"][$key];
// here we move it to a directory called data
// you can move it wherever you want
move_uploaded_file($tmp_name, "/data/$name");
} else {
// an error occurred, handle it here
}
}
}
if (!$_FILES){
echo 'WTF?? No files sent?? There\'s a problem! Let\' hope that stack overflow will solve it!';
}
?>
</body>
</html>
The output is:
Notice: Undefined index: myFile in C:\xampp\htdocs\php\prova.php on line 18
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\php\prova.php on line 18
No files sent?? There's a problem! How can I access files uploaded from an array input tag?

I think using $_POSTOR $_FILES instead of $_GET['u'] to verify from submission, would fix the problem...
Also you can use <input type="file" name="myFile[]" multiple /> once instead of so many <input type="file"> for multiple file selection.
NOTE : Check php.ini for the following settings: (Edit as your needs , save & restart server)
file_uploads = On
upload_max_filesize = 2M (its 2 MB file limit by default !!! Exact error occurs as your's if file size > 2MB)
post_max_size = 8M (8 MB limit for post variable by default. Change as per your requirement...)
upload_tmp_dir = "c:/tmp" (Provide read/write permission to temporary opload directory )
This works ok in my wamp server with the above changes & settings... Good Luck !

Well, the easiest way to upload your files is to act as if you had only one, and repeat the process for every other file you have, all you have to do is give an name to your input. I would recommend using a multiple file input :
<input type="file" name="file[]" id="file" multiple>
Then, you can handle the upload with a simple for :
if(isset($_FILES['file']['tmp_name']))
{
//set upload directory
$target_dir = "uploads/";
$num_files = count($_FILES['file']['tmp_name']);
for($i=0; $i < $num_files;$i++)
{
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i]))
{
$messages[] = 'No file uploaded';
}
else
{
if(#copy($_FILES['file']['tmp_name'][$i],$target_dir.'/'.$form['name']->getData()."/".$_FILES['file']['name'][$i]))
{
$messages[] = $_FILES['file']['name'][$i].' uploaded';
}
else
{
$messages[] = 'Uploading '.$_FILES['file']['name'][$i].' Failed';
}
}
}
}
You can use either copy or move_uploaded_file to move the file to your directory.

I checked your code, and found that changing the line:
move_uploaded_file($tmp_name, "/data/$name"); to
move_uploaded_file($tmp_name, "data/$name");
[Changing absolute path to relative path]
does the trick. Now it works fine, in my local server. That should solve it for you.
Courtesy:http://forums.whirlpool.net.au/archive/788971

Related

PHP move_uploaded_file results in error #1

I try to upload a file to an external server based on this code: https://www.w3schools.com/php/php_file_upload.asp .
On my local machine everything works fine but when uploading the exact same script to an external server it won't work anymore. When debugging with:
$_FILES["fileToUpload"]["error"]
I get an Error #1 in return altough im running the same php.ini as on my local machine. The uploads/ folder exists and the user www-data has also permissions to write it. I proofed this by running file_put_contents("uploads/test.txt", "working");. The only thing I could think of is the PHP Version difference (Local: 7.2.5; External: 7.2.19) or maybe a missing php module?!
It would be great if someone could help me solving this.
Try with full path using $_SERVER['DOCUMENT_ROOT'] also try to create recursively your folders using mkdir with 3rd parameter set to true (if not exists your path), increments your upload_max_filesize as suggested by Andreas into comments... here is a pseudo working example...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form name="form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Upload File: <input type="file" size="30" id="fileToUpload" name="fileToUpload">
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/var/www/html/";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, 0755, true);
}
if ((isset($_FILES['fileToUpload']['name'])) && (!empty($_FILES['fileToUpload']['name']))) {
$temp_name = $_FILES['fileToUpload']['tmp_name'];
$file_name = $_FILES['fileToUpload']['name'];
$file_path = $upload_dir.$file_name;
$upload_process = move_uploaded_file($temp_name, $file_path);
#chmod($file_path,0755);
}
if ((isset($upload_process)) && ($upload_process == TRUE)) {
echo "File Uploaded With Success...";
}
if ((!isset($upload_process)) || ($upload_process == FALSE)) {
echo "Please, Upload some File...";
}
?>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
I hope this helps.
OK, i was dumb. I changed the wrong php.ini file. For anyone who experiences similar issues you can check the location of the php.ini file and if it's loaded by PHP with:
$inipath = php_ini_loaded_file();
if ($inipath) {
echo 'Loaded php.ini: ' . $inipath;
} else {
echo 'A php.ini file is not loaded';
}
Hope this helps.

PHP uploaded file is not saved and no error is shown

I don't know if my code it's correct, but everything indicates success when sending..
My Form
<form action="upload.php" method="POST" enctype="multipart/form-data">
File: <input type="file" name="file" />
<input type="submit" name="submit" value="Go" />
</form>
My Upload File
<?php
if($_FILES['file']['name'])
{
if(!$_FILES['file']['error'])
{
$valid_file = true;
if($_FILES['file']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
if($valid_file)
{
/
if(move_uploaded_file($_FILES['file']['tmp_name'],'/files')){
echo "Sent";
}else{
echo "~Error~";
}
}
}
//if there is an error...
else
{
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
?>
The message that I get is "Sent", but when I go to check, the folder files is empty :s
My folder structure is:
/files - Here is directory where the files will come
index.php - My form
upload.php - My Logic
One of the issues that I see in your code is that you do not specify a name for your "moved" file:
This line:
move_uploaded_file($_FILES['file']['tmp_name'],'/files')
Should be changed to:
move_uploaded_file($_FILES['file']['tmp_name'],'/files/'.'sampleName'.$extension);// extension is the extension of the file.
I still assume your '/files' path is correct and does not have permission problem.
Same issue arises if your target folder has no write permission.
Use this command to change that:
chmod 775 [folder-name]

how to move uploaded file in php?

Here is my html code for uploading multiple files in php. I want to store the image name in the database and upload the file in folder:
<input name="userfile[]" type="file" multiple="multiple"/><br />
<input name="userfile[]" type="file" multiple="multiple"/><br />
if(isset($_FILES['file']['tmp_name'])){
$num_files = count($_FILES['file']['tmp_name']);
for($i=0; $i < $num_files;$i++){
if(!is_uploaded_file($_FILES['file']['tmp_name'][$i])){
$messages[] = 'No file uploaded';
}
else{
if (file_exists("images/Locations" . $_FILES["file"]["name"]))
{
}
else
{
if ($_FILES["file"]["error"] > 0){
$file = fopen("test.txt","w");
echo fwrite($file,"Not uploaded");
fclose($file);
}
else{
move_uploaded_file($_FILES['file']['tmp_name'][$i],"images/Locations");
}
}
}
}
}
So can anyone tell me where I am making a mistake. I want to store name of image into database so how can i do that when i am writing the error it displays error code 0, so what is error code 0 in it.
The mistakes that I found at the first sight was:
<input name="userfile[]" type="file" multiple/><br />
This should there only once because of the multiple attribute it forms multi-dimensional array according to the number of images selected.
Change your if-conditional to
if(count($_FILES['userfile']['name']> 0)){
That should give you a start. Let me know if you find any problems.
Your input file type name is "userfile"
And you are using in the PHP script as
$_FILES['file']['tmp_name']
And here is the problem.
Change them accordingly to use proper input names on your script processing the upload.

Max_File_Uploads directive php.ini

Im trying to do a simple file upload. I've done it many times before and it's been fine. For some reason this time I keep getting error UPLOAD_ERR_INI_SIZE coming up. Even though i've uploaded bigger files on the same server before. Here is my PHP.INI:
display_errors = On
short_open_tag = On
memory_limit = 32M
date.timezone = Europe/Paris
upload_max_filesize = 10M
post_max_size = 10M
And my HTML form:
<form action="/settings/upload-image" method="POST" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="<?=(1024*1024*1024);?>">
<input name="files[]" id="attachfile" type="file" />
<br /><br />
<input type="submit" class="submit" value="Upload New Profile Image">
</form>
And my code:
foreach($files as $file)
{ $ext = strtolower(pathinfo($file[0], PATHINFO_EXTENSION));
if(in_array($ext,$allowed_upload_ext)===TRUE)
{
if(!$file[3]) { // If no error code
//$newFile = $me['id'].".$ext";
$newFile = $file[0];
resizeImage($file[2],PROFILE_IMAGES."/".$newFile,$ext,500);
genThumbFile($file[2],PROFILE_IMAGES."/thumb/".$newFile);
runSQL("UPDATE `users` SET `image`='{$file[0]}' WHERE `id`='{$me['id']}';");
array_push($msgs,"Image uploaded successfully.");
$me = select("SELECT * FROM `users` WHERE `id`='{$me['id']}';",true);
} else {
array_push($msgs,"!".fileError($file[3]));
}
} else {
array_push($msgs,"!The file ".$file[0]." could not be uploaded as it is the wrong file type.");
}
}
The only difference this time is that I am resizing and genorating thumbs with the temporary upload file instead of copying over the file first. Could that be the problem? I dont think so, because if the image is small it works perfectly fine. But I try anything like 2mb and it throws a fit.
Suggestions?
Thanks for ALL YOUR HELP guys. :P
I solved it - Missing line in PHP.INI:
file_uploads = On
Just for anyone who fins this.

Warning: getimagesize() [function.getimagesize]: Filename cannot be empty warning message?

Up until recently I've been using some PHP to upload photos to a site. But suddenly it's started triggering all sorts of error messages.
I use a form that on action runs the following code:
$uploaddir = "../../user_content/photo/";
$allowed_ext = array("jpeg", "jpg", "gif", "png");
if(isset($_POST["submit"])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
The file upload part of the form has the following elements:
<input name="file" type="file" class="photo_file_upload">
The submit button for uploading has the following attributes:
<button type="submit" name="submit" class="photo_upload">Upload</button>
But whenever I run this, I always get the following warning:
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in (upload PHP file) on line 10
(line 10 is this part: $info = getimagesize($file_temp);)
Anyone have any ideas on what the cause of this is?
You checked if the form was submitted, but didn't check if the file was sent. In some cases, a form could be submitted but the file will not sent (i.e. file size is bigger then file size limit in config).
Use this:
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
} else {
print "File not sent to server succesfully!";
exit;
}
You see && isset($_FILES['file']) is new
Or you can extend it
if(isset($_POST["submit"]) && isset($_FILES['file'])) {
$file_temp = $_FILES['file']['tmp_name'];
$info = getimagesize($file_temp);
}
elseif(isset($_POST["submit"]) && !isset($_FILES['file'])) {
print "Form was submitted but file wasn't send";
exit;
}
else {
print "Form wasn't submitted!";
exit;
}
Change these parameters in your php.ini file; (Currently it allow only 2Mb size to
upload and post). Sometimes it's reason for these errors.
upload_max_filesize = 500M
post_max_size = 500M
max_execution_time = 120
Warning: getimagesize() [function.getimagesize]: Filename cannot be empty in
Verify the MAX_SIZE variable,
example to define it for a 2Mo image:
define('MAX_SIZE', 2000000);
<form enctype="multipart/form-data" method="post" action="upload.php">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE; ?>" />
<input name="fichier" type="file" id="fichier_a_uploader" /> <br>
<input type="submit" name="submit" value="Uploader" />
</form>
you can also verify the Maximum size of POST data that PHP will accept and Maximum allowed size for uploaded files in PHP.ini :
post_max_size = ?
upload_max_filesize = ?
After you upgrade 'upload-max-filesize' , Restart all Services of wamp or xampp ! it will right !
you should change the form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 38
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
Warning: getimagesize(): Filename cannot be empty in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 43
File is not an image.Sorry, file already exists.
Notice: Undefined index: fileToUpload in D:\xampp\htdocs\public_html\php\form_php\application\process_application.php on line 58
Sorry, only JPG, JPEG, PNG & GIF files are allowed.Sorry, your file was not uploaded.
If You Get Errors like this one you should check you have added form enctype to "multipart/form-data"
<form method="post" enctype="multipart/form-data">
....
</form>
Use to catch me out quite a lot to begin with.

Categories