Unspecified error with a file upload loop - php

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.

Related

Upload file to server using PHP and HTML

I have a problem loading the file to the server in PHP and HTML using move_uploaded_file () when I put PHP files in this way http://mydomin.com/uploadfile.php succeed the process and if this way http://mydomin.com/uploadfiles/uploadfile.php The the process fails
code php
<?php
if (isset($_FILES['image'])) {
$idApp = uniqid();
$uploadDir = '../images/';
$uploadedFile = $uploadDir . $idApp . ".jpg";
if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadedFile)) {
echo"Success: ".$_FILES['image']['tmp_name']. $uploadedFile;
} else {
echo"error 2";
}
} else {
echo"error 3";
}
?>
code html
<form action="add.php" method="POST" enctype="multipart/form-data">
<input type='file' name='image' id='image'>
<div align='center''><input type='submit' id='myButton' value='add'></div>";
</form>
check your upload path
$uploadDir = '../images/';
Try to use this path './images/' or best use absolute path.
check your script location by using
var_dump(__DIR__)
this will show you where is your .php file is ( also called as absolute path ). Thus simply you can see where you made a mistake to assign a folder for file uploading(image in your case ).

How to rename and save files in php

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?

Upload Multiple Files HTML5 / PHP

I'm trying to build a basic upload form to add multiple files to a folder, which is processed by PHP.
The HTML code I have is:
<form id="form" action="add-files-php.php" method="POST" enctype="multipart/form-data">
<div class="addSection">Files To Add:<br><input type="file" name="files[]" multiple /></div>
<div class="addSection"><input type="submit" name="submit" value="Add Files" /></div>
</form>
And the PHP to process is:
$file_path = "../a/files/article-files/$year/$month/";
foreach ($_FILES['files']['files'] as $file) {
move_uploaded_file($_FILES["file"]["name"],"$file_path");
}
I can run the PHP without any errors, but the files don't get added to the path folder.
Where am I going wrong with this?
I have a similar code actually in one of my projects. Try it.
foreach ($_FILES['files']['name'] as $f => $name) {
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path);
}
Look at the following page:
http://php.net/manual/en/function.move-uploaded-file.php
EDIT:
Nowhere in the code you provided, does it show that you actually give your file a filename, you simply refer to a path, rather than a path+filename+extension
move_uploaded_file($_FILES["files"]["tmp_name"][$f], $file_path . $name);
modifying my original code sample to be like the second one, should work.
Iterate the $_FILES['files']['error'] array and check if the files are actually uploaded to the server:
$dest_dir = "../a/files/article-files/$year/$month";
foreach ($_FILES["files"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
// The temporary filename of the file stored on the server
$tmp_name = $_FILES["files"]["tmp_name"][$key];
$name = basename($_FILES["files"]["name"][$key]);
// Handle possible failure of the move_uploaded_file() function, too!
if (! move_uploaded_file($tmp_name, "$dest_dir/$name")) {
trigger_error("Failed to move $tmp_name to $dest_dir/$name",
E_USER_WARNING);
}
} else {
// Handle upload error
trigger_error("Upload failed, key: $key, error: $error",
E_USER_WARNING);
}
}
The biggest issue with your code is that you are trying to move $_FILES['files']['name'] instead of $_FILES['files']['tmp_name']. The latter is a file name of temporary file uploaded into the temporary directory used for storing files when doing file upload.
P.S.
Using relative paths is error-prone. Consider using absolute paths with the help of a constant containing path to the project root, e.g.:
config.php
<?php
define('MY_PROJECT_ROOT', __DIR__);
upload.php
<?php
require_once '../some/path/to/project/root/config.php';
$dest_dir = MY_PROJECT_ROOT . "/a/files/article-files/$year/$month";

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.

How to get the total number of iterations in a foreach

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>

Categories