PHP multiple file Upload (Array) Issue - php

I use Multiple File upload with foreach loop. But my files are not move to folder,
Here Is My Code.
foreach ($_FILES['image']['name'] as $file)
{
print_r($file);
echo "<br>";
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
echo $file = $baseMODULES."/upload/".$_FILES['image']['name'];
echo "<br><br>";
$clogo = $_FILES['image']['name'];
move_uploaded_file($_FILES['image']['tmp_name'],$file);
//File Loading Successfully
}
And Here Is an output.

<?php
$i = 0 ;
foreach ($_FILES['image']['name'] as $file)
{
print_r($file);
echo "<br>";
$errors= array();
$file_name = $_FILES['image']['name'][$i];
$file_size =$_FILES['image']['size'][$i];
$file_tmp =$_FILES['image']['tmp_name'][$i];
$file_type=$_FILES['image']['type'][$i];
echo $file = $baseMODULES."/upload/".$_FILES['image']['name'][$i];
echo "<br><br>";
$clogo = $_FILES['image']['name'][$i];
move_uploaded_file($_FILES['image']['tmp_name'][$i],$file);
//File Loading Successfully
$i++;
}
?>
Try this
or
<?php
$i = 0;
foreach ($_FILES['image']['name'] as $key=>$file)
{
print_r($file);
echo "<br>";
$errors= array();
$file_name = $_FILES['image']['name'][$key];
$file_size =$_FILES['image']['size'][$key];
$file_tmp =$_FILES['image']['tmp_name'][$key];
$file_type=$_FILES['image']['type'][$key];
echo $file = $baseMODULES."/upload/".$_FILES['image']['name'][$key];
echo "<br><br>";
$clogo = $_FILES['image']['name'][$key];
move_uploaded_file($_FILES['image']['tmp_name'][$key],$file);
//File Loading Successfully
$i++;
}
?>

You should change your foreach loop to something like this:
foreach($_FILES['image'] as $image) {
Then do the move with something like
move_uploaded_file($image['tmp_name'], $file);
As specified in the comments :-)

<?php
$i = 0;
foreach ($_FILES['image']['name'] as $file)
{
$file_name = $file;
$file_size = $_FILES['image']['size'][$i];
$file_tmp = $_FILES['image']['tmp_name'][$i];
$file_type = $_FILES['image']['type'][$i];
$file = $baseMODULES."/upload/".$file;
move_uploaded_file($file_tmp,$file);
$i++;
}
?>

Related

PHP fileupload giving all filenames from array

I've been looking in this for a day or two now.
When I upload multiple files to this script, "$finalfilename" give's me back multiple filenames from the second file.
Here's my code:
include ($_SERVER['DOCUMENT_ROOT'] . "/config/config.php");
$valid_extensions = array(
'jpeg',
'jpg',
'png',
'gif',
'bmp'
); // valid extensions
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; // upload directory
$uploadOK = 1;
$album = strip_tags($_POST['newPostForm-Album']);
$i = 0;
foreach($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file)
{
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$imgname = "";
$tmpname = "";
$timestamp = "";
$extension = "";
$newfilename = "";
$finalfilename = "";
$i++;
}
As you can see, I tried resetting all the strings at the end before adding $i.
UPDATE
I tried using $file instead of $_FILES (echo $file['name'][$i];)
This gives me back this warning:
Illegal string offset 'name' in
also the output of the second file ($finalfilename) gives me 'filename'.extention'filename'.extention
ea5816965b01dae0b19072606596c01efc015334.jpeg21aa3008f90c89059d981bdc51b458ca1954ab46.jpg
Wich need to be separated.
I need to only get the filename of each file seperatly.
Thank you!
Problem is in $path variable.
Put $path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/'; into the loop. You can remove variable reseting from the end too.
foreach ($_FILES['NEW-POST-FORM_IMAGES']['name'] as $file) {
$path = $_SERVER['DOCUMENT_ROOT'] . '/assets/uploads/';
$imgname = $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
$tmpname = $_FILES['NEW-POST-FORM_IMAGES']['tmp_name'][$i];
$timestamp = time();
$extension = strtolower(pathinfo($imgname, PATHINFO_EXTENSION));
$newfilename = sha1(time() . $i);
$finalfilename = $newfilename . "." . $extension;
if ($_FILES['NEW-POST-FORM_IMAGES']["size"][$i] > 500000)
{
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
if ($uploadOK)
{
if (in_array($extension, $valid_extensions))
{
$path = $path . strtolower($finalfilename);
if (move_uploaded_file($tmpname, $path))
{
// mysqli_query($con, "INSERT INTO posts VALUES('', '$album', '$finalfilename', '$timestamp')");
echo $_FILES['NEW-POST-FORM_IMAGES']['name'][$i];
}
else
{
echo "error!";
}
}
}
$i++;
}
There are more thing to update, instead of foreach for/while would be better here, or using foreach in else way (use $file in the loop body), etc. Moving $path into loop is easiest way how to fix your problem.

move_upload_file not work for upload video

I want to upload video (like mp4, wvm, flv) with form submit but move_file_upload() not working.
This is my code :
<?php
if (isset($_POST['submit'])) {
$errors = array();
$allowed_e = array('mp4', 'flv', 'wmv');
$file_name = $_FILES['video2']['name'];
$file_e = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$file_s = $_FILES['video2']['size'];
$file_tmp = $_FILES['video2']['tmp_name'];
$t_name = #$_POST['topic_name'];
$content = #$_POST['content'];
$date = date("y-m-d");
if (in_array($file_e, $allowed_e) == false) {
$errors[] = 'ext not allowed';
}
if ($file_s > 20097152) {
$errors[] = 'File must be under 20mb';
}
if (empty($errors)) {
$rawBaseName = pathinfo($file_name, PATHINFO_FILENAME );
$extension = pathinfo($file_name, PATHINFO_EXTENSION );
$counter1 = 1;
$counter2 = 1;
while(file_exists('video/'.$file_name)) {
$file_name = $rawBaseName . $counter1 . $counter2 .'.' . $extension;
$counter1++;
$counter2++;}
move_uploaded_file($file_tmp, 'video/'.$file_name);
$video2_up = 'video/'.$file_name;
if ($posttopic = "INSERT INTO topics (topic_id, topic_name, topic_content, topic_creator, date, video)
VALUES ('', '".$t_name."', '".$content."', '".$_SESSION["username"]."', '".$date."', '".$video2_up."')" ){
$conn->exec($posttopic);
}header("Location: index.php");
}else{
foreach ($errors as $error) {
echo $error, '</br>';
}
}
}
?>
But when I remove that extension allowed and upload some image it works
please give me solution.
I think the problem is with the file size. Check your php.ini file and increase the limit for following php directives:
post_max_size = 20M
upload_max_filesize = 20M
After making the above changes, restart you web server.

Insert multiple file names in database column

I have this file uploading code which is working fine. The only issue I have is when i upload multiple files, it creates multiple rows in database for each file. For instance, if I upload 5 files, it will create 5 new rows with same message but with different file name. It's not binding all files in one message and not creating a single row for message with multiple files in database.
if(!empty($_FILES['files']['name'][0])){
$files = $_FILES['files'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'jpeg','gif','png','txt', 'doc','docx', 'xls', 'xlsx', 'zip','rar','gz','7zip','ppt', 'pptx','rtf','pdf','svg','sav','csv');
foreach ($files['name'] as $position => $file_name) {
$file_temp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if(in_array($file_ext, $allowed)){
if($file_error === 0){
if($file_size <= 20000000){
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = '../files/wcfiles/'.$file_name_new;
$file_destination = '../files/wcfiles/'.strtolower($file_name);
$file_db_path_array = array();
array_push($file_db_path_array, strtolower($file_name));
$file_db_path = 'msg_files/'. $file_db_path_array;
if(move_uploaded_file($file_temp, $file_destination)){
$uploaded[$position] = $file_destination;
} else {
$failed[$position] = "[{$file_name}] failed to upload";}
} else {
$failed[$position] = "[{$file_name}] is too large.";}
} else {
$failed[$position] = "[{$file_name}] errored with code {$file_error}";}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";}
}
$ins_message = $conn->prepare("INSERT INTO conversation (msg_date, msg_id, msg_from, msg_to, msg_message, msg_files) VALUES (?,?,?,?,?,?)");
$ins_message->bind_param("ssssss", $msg_date, $msg_id, $msg_from, $msg_to, $msg_message, $file_db_path);
$ins_message->execute();
$ins_message->close();
File code
echo '<ul>';
foreach (explode(',', $msg_rows['msg_files']) as $file ) {
echo '<li><a href="../files/wcfiles/"'.$file.'>'.$file.'</a></li>';}
echo '</ul>';
I think the best approach here is to push the file path values into an array in your foreach loop. Then, after the loop, join each file path array element into a string with a comma in between each, to get your complete file paths string to insert into the database.
First instantiate an array, to hold the file path values, before the foreach loop.
$file_db_path_array = [];
foreach ($files['name'] as $position => $file_name) {
// ...
Next move your database insertion code to after your foreach loop closes:
} // end of foreach $files['name']
$ins_message = $conn->prepare("INSERT INTO conversation (msg_date, msg_id, msg_from, msg_to, msg_message, msg_files) VALUES (?,?,?,?,?,?)");
$ins_message->bind_param("ssssss", $msg_date, $msg_order_id, $msg_from, $msg_to, $msg_message, $file_db_path);
$ins_message->execute();
$ins_message->close();
Then replace the $file_db_path assignment line with:
array_push($file_db_path_array, 'msg_files/'.strtolower($file_name_new));
Finally, in the database insertion code, change $file_db_path to join(',', $file_db_path_array).
$ins_message->bind_param("ssssss", $msg_date, $msg_order_id, $msg_from, $msg_to, $msg_message, join(',', $file_db_path_array));
And here's the complete foreach loop and database insertion:
$file_db_path_array = [];
foreach ($files['name'] as $position => $file_name) {
$file_temp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if(in_array($file_ext, $allowed)){
if($file_error === 0){
if($file_size <= 20000000){
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = '../files/wcfiles/'.$file_name_new;
array_push($file_db_path_array, 'msg_files/'.strtolower($file_name_new));
if(move_uploaded_file($file_temp, $file_destination)){
$uploaded[$position] = $file_destination;
} else {
$failed[$position] = "[{$file_name}] failed to upload";
}
} else {
$failed[$position] = "[{$file_name}] is too large.";
}
} else {
$failed[$position] = "[{$file_name}] errored with code {$file_error}";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
$file_db_path = join(',', $file_db_path_array);
$ins_message = $conn->prepare("INSERT INTO conversation (msg_date, msg_id, msg_from, msg_to, msg_message, msg_files) VALUES (?,?,?,?,?,?)");
$ins_message->bind_param("ssssss", $msg_date, $msg_order_id, $msg_from, $msg_to, $msg_message, $file_db_path);
$ins_message->execute();
$ins_message->close();
Later, when you want to display the list of files with each message, for each message, explode the file list, using comma, to get an array, then loop over the array to display each file.
// this is inside your messages display loop,
// assuming the files field is assigned to variable $files_string
echo '<ul>';
foreach ( explode(',', $files_string) as $file ) {
echo '<li>'.$file.'</li>';
}
echo '</ul>';

Acess array data in elseif ( ) {..} condition from if ( ) {…} condition

I have two form submitting buttons in one form, and I want to use $uploaded array in elseif() {...} like this $data ['pic_path'] = $uploaded;, but it doesn't work. I can only print out $uploaded inside of if () {...}, or inside the html body. What should I do to save the $uploaded in $data array? Thanks!
Here's the code:
<?php
if (isset($_POST[submit_image])) {
if (!empty($_FILES["files"]["name"][0])) {
$files = $_FILES["files"];
//arrarys to include files uploaded successfully and failed
$uploaded = array();
$failed = array();
//access tmp_name arrary
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files["tmp_name"][$position];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$file_name_new = uniqid("", true) . "." . $file_ext;
$file_destination = "uploads/" . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
} else {
$failed[$position] = "error";
}
}
print_r($uploaded);
}
} elseif (isset($_POST[submit_post])) {
$data = array();
$data['comments'] = $_POST['comments'];
//$data ['pic_path'] = $uploaded;
//print_r($uploaded);
}
?>
<!DOCTYPE html>
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="files[]" multiple />
<input type="submit" name="submit_image"/>
<textarea name="comments"></textarea>
<button type="submit" name="submit_post">Submit Your Post</button>
</form>
</body>
</html>
That's because $uploaded only exists in the if statement you declared it in. You will need to loop through files again in the elseif or move your declaration of $uploaded and $failed as well as the for loop that populates them out of that if block so the variables are accessible in both paths.
Edit - Try this:
if (!empty($_FILES["files"]["name"][0]) ) {
$files = $_FILES["files"];
//arrarys to include files uploaded successfully and failed
$uploaded = array();
$failed = array();
//access tmp_name arrary
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $files["tmp_name"][$position];
$file_ext = explode(".", $file_name);
$file_ext = strtolower(end($file_ext));
$file_name_new = uniqid("", true) . "." . $file_ext;
$file_destination = "uploads/" . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
} else {
$failed[$position] = "error";
}
}
print_r($uploaded);
}
if (isset($_POST[submit_post])) {
$data = array();
$data['comments'] = $_POST['comments'];
$data ['pic_path'] = $uploaded;
}

how to display an error message in an array

i have this code:
$allowed_extension = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$errors = array();
$output = array();
if(!empty($_FILES['image']['tmp_name'])){
foreach($_FILES['image']['name'] as $key => $array_value){
if(!in_array(pathinfo($_FILES['image']['name'][$key], PATHINFO_EXTENSION), $allowed_extension)){
die("Die!");
}
}
foreach($_FILES['image']['name'] as $key => $array_value){
$file_name = $_FILES['image']['name'][$key];
$file_size = $_FILES['image']['size'][$key];
$file_tmp = $_FILES['image']['tmp_name'][$key];
$file_extension = pathinfo($file_name, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
if (!in_array($file_extension, $allowed_extension)){
$errors[$file_name][] = "format $file_extension in image $file_name is not accepted";
continue;
}
if ($file_size > 2097152){
$errors[$file_name][] = "maxsize of 2MB on $file_name has reached";
}
if (count($errors) == 0){
$dir = "a/b/c";
if (is_dir($dir)){
mkdir("a/b/c/tmp_images", 0755);
}else{
mkdir("a/b/c", 0755);
mkdir("a/b/c/tmp_images", 0755);
}
$path = "a/b/c/tmp_images";
$prifix = basename($file_name, "." . $file_extension);
//var_dump ($prifix);
$uploadfile = $path . "/" . $file_name;
$x = 0;
while (file_exists($uploadfile)){
$x ++;
$uploadfile = "{$path}/{$prifix}-{$x}.{$file_extension}";
}
if (move_uploaded_file($file_tmp, $uploadfile)){
$file_name = basename($uploadfile);
$output [$file_name] = "OK";
}else{
$output[$file_name] = "Failure while Uploading!";
$errors[$file_name][] = "Failure: Can't move uploaded pictures!";
}//else...
}//if(count($errors))...
}//foreach($_FILES['image']['name']...
}//if(!empty($_FILES['image']['tmp_name'])...
and my problem is, that i dont know how to display the error messages that should be shown, when the array
$errors
is given. up to now, it just will be displayed:
array
instead of:
maxsize of 2MB on abc.jpg has reached
in the html i have this code:
<?php if(isset($errors)):?>
<div class="form-error-message" id="signup-error-message" style="display": none;">
<div class="arrow-wrapper">
<div class="border-wrapper">
<?php foreach($errors as $error):?>
<p class="layer-content">
<?php echo $error;?>
</p>
<?php endforeach;?>
</div>
</div>
</div>
if there is someone who could be that friendly and help me out i really would appreciate. thanks a lot.
Maybe save each error like this:
$errors = array();
$errors[] = $file_name . ": this is the error message.";
And display like this:
if(count($errors) > 0){
foreach($errors as $e){
echo $e . "<br />";
}
}
You've wrote $errors as 2-dimensional array:
$errors[$file_name][] = 'your message';
So to correctly display it use two foreach's instead of one:
<?php foreach($errors as $errorsOnFile):?>
<?php foreach($errorsOnFile as $error):?>
<p class="layer-content">
<?php echo $error;?>
</p>
<?php endforeach;?>
<?php endforeach;?>
How about?
echo implode(', ', $errors[$filename]);
You have to print_r an array, not echo it:
print_r($errors);
Alternatively, you can show each of the errors individually, like so:
foreach( $errors as $innerErrors )
{
foreach( $innerErrors as $anError )
{
echo $anError ."\n";
}
}
You can't just echo an array. You can, however, loops through the elements of the array.
foreach($errors[file_name] as $error_message) {
echo $error_message."<br>";
}
This code echos the errors one at a time.

Categories