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.
Related
This is my html form
<form action="index.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="userfile[]" type="file" /><br />
<input name="userfile[]" type="file" /><br />
<input type="submit" value="Send files" />
</form>
This is my index.php file
<?php
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo"$error_codes[$error]";
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$_FILES["userfile"]["name"][$key]
) or die("Problems with upload");
}
}
?>
**The code is working properly. But, What I really need is to change the name of the 1st uploaded file to birthcertificate and the name of the 2nd uploaded file into NIC. **
**Example : If I upload a file named 123 or abc (whatever the name) the 1st file's name should be birthcertificate and the 2nd file's name should be NIC. **
There are probably lots of ways to do this.
I thought that making a list of the new file names
might be the way to go.
<?php
// Make a list of the new file names
$newFileNames = ['birthcertificate', 'NIC'];
foreach ($_FILES["userfile"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
echo"$error_codes[$error]";
// Grab new file name
$newFileName = array_shift($newFileNames);
// Make sure we actually got one
if ( $newFileName ) {
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$newFileName)
or die("Problems with upload");
}
}
}
move_uploaded_file(file, location);
You can use file and new name in location parameter like this:
$newname = "yourimg.png";
enter code here
move_uploaded_file($_FILES["userfile"]["tmp_name"][$key], "your location" . $newname);
This is the basic way of renaming, make changes to the loop for renaming both files. If you only upload 2 files at a time, you can use the array index for your logic.
You can rename a file:
Instead of below code inside foreach you have shared
move_uploaded_file(
$_FILES["userfile"]["tmp_name"][$key],
$_FILES["userfile"]["name"][$key]
) or die("Problems with upload");
You can use:
$temp = explode(".", $_FILES["userfile"]["name"]);
$newfilename = 'birthcertificate' . '.' . end($temp);
move_uploaded_file($_FILES["userfile"]["tmp_name"], $newfilename) or die("Problems with upload");
Try giving the file seperate names, in PHP you can receive them and make in one array if you need
You can also refer to this link:
How to rename uploaded file before saving it into a directory?
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.";
}
I'm using a form and a loop to upload multiple image files directly to the file server, but I'm getting a false result with the move_uploaded_file function.
Upload Form:
<body>
<p>
<form action='uploadform.php' method='post' enctype='multipart/form-data'>
Select the files you would like to upload.
<input type='file' name='fileToUpload[]' id='fileToUpload' mozdirectory webkitdirectory directory multiple />
<input type='submit' value='Upload Image' name='submit'>
</form><br>
The files will be uploaded to a folder named '".$_SESSION['filename']."'.<br>
</p>
</body>
Multiple file uploading loop (uploadform.php:
if (isset($_POST["submit"])) {
foreach ($_FILES['fileToUpload']['name'] as $i => $name) {
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"][$i]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (strlen($_FILES['fileToUpload']['name'][$i]) > 1) {
if (move_uploaded_file($_FILES["fileToUpload"]["name"][$i], $target_file)) {
echo basename($_FILES["fileToUpload"]["name"][$i]);
}
else {
echo "Error! File basename: ".basename($_FILES["fileToUpload"]["name"][$i])."<br>";
}
$count++;
}
}
}
When uploading one or multiple files with the form, it goes to the else statement echoing the "ERROR" string.
The Apache Error Log comes up blank, so I have no clue what's wrong with the code.
I tried echoing the variables used in the loop ($_FILES["fileToUpload"]["name"][$i], $target_file and $imageFileType) but these seem to be fine.
I would put entire foreach loop in try-catch block and see what, if any Exception occurs:
try{
// your foreach loop here:
}
catch(\Exception $e)
{
echo $e->getMessage();
}
The $_FILES["fileToUpload"]["name"][$i] variable was not the one that the loop was supposed to use.
By changing all instances of $_FILES["fileToUpload"]["name"][$i] to $name (which is $_FILES["fileToUpload"]["tmp_name"][$i]) the error was gone.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Unable to do File Upload in PHP
I am trying to learn to write file upload script in PHP. I don't know why this doesn't work. Please have a look
<?php
$name=$_FILES["file"]["name"];
if(isset($name)) {
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
?>
It gives an error message Notice: Undefined index: file in
The html part is
<form action="submissions.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" value="Submit" /></form>
I am using wamp on Windows. What may be the cause for the error ?
You need to check if the form was submitted before executing your PHP code:
<?php
if (isset($_POST["submit"]) && $_POST["submit"] === "Submit") {
if (isset($_FILES["file"]["name"])) {
$name = $_FILES["file"]["name"];
if(!empty($name)) {
echo $name;
}
else {
echo 'Please choose a file';
}
}
}
?>
The clue is in the error message. The index 'file' doesn't exist in the FILES array. At a guess because you have this code before you've sumitted the form?
check if it exists first,
if(isset($_FILES['FormFieldNameForFile']) && $_FILES['FormFieldNameForFile']['size']>0){ # will be 0 if no file uploaded
then check your use of the field components.
$_FILES['userfile']['name'] # The original name of the file on the client machine.
$_FILES['userfile']['type'] # The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size'] # The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name'] # The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error'] # The error code associated with this file upload
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