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

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;
}

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.

Problems with Uploading Script [duplicate]

This question already has an answer here:
Multiple Picture Upload Problems
(1 answer)
Closed 6 years ago.
I have a simple script that can upload files on my server and insert the details into database.
With code below I am getting two errors..
"Notice: Undefined variable: sExt in" ..
I tried to fix the issue with if empty statement, but without sucess..
Script import numbers (1,2,3...) into Mysql if the upload filed is empty....
I tried to fix the issue with the code below, but also without success..
"if($_FILES['files']['name']!="")"...
Any advice?
Thank you..
My code:
<?php
include_once('db.php');
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
if ($file_size > 2097152000) {
$errors[] = 'File size must be less than 2 MB';
}
$query = "INSERT into user_pics (`person_id`,`pic_name`,`pic_type`) VALUES('1','$file_name','$sExt')";
$result = mysqli_query($link,$query);
$desired_dir = "user_data/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700);
}
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
echo "Files Uploaded !" . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
print_r($errors);
}
}
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key+1) . ' = $row[0];';
eval ($codestr);
} else {
$codestr = '$file' . ($key+1) . ' = NULL;';
eval ($codestr);
}
}
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" accept="image/*"> <br/>
<input type="file" name="files[]" accept="image/*"> <br/><br/>
<input type="submit"/>
</form>
instead of this
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}
if (!in_array($sExt, array('.gif','.jpg','.png'))) {
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
You should do
if($file_type == "image/gif"){
$sExt = ".gif";
} elseif($file_type == "image/jpeg" || $file_type == "image/pjpeg"){
$sExt = ".jpg";
} elseif($file_type == "image/png" || $file_type == "image/x-png"){
$sExt = ".png";
}else{
$errors[] = "Image types alowed are (.gif, .jpg, .png) only!";
}
Checking the extension you are setting is redundant, and this avoids the error when your varible $sExt is not set, by providing a default ( with else ). This should give you the desired behaviour.
I would also move these lines
$query = "INSERT into user_pics (`person_id`,`pic_name`,`pic_type`) VALUES('1','$file_name','$sExt')";
$result = mysqli_query($link,$query);
$desired_dir = "user_data/";
if (empty($errors)) {
To the inside of this code block
if (empty($errors)) {
$query = "INSERT into user_pics (`person_id`,`pic_name`,`pic_type`) VALUES('1','$file_name','$sExt')";
$result = mysqli_query($link,$query);
$desired_dir = "user_data/";
That way you don't do the insert when you have something in errors...
Not sure the purpose of this
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$codestr = '$file' . ($key+1) . ' = $row[0];';
eval ($codestr);
} else {
$codestr = '$file' . ($key+1) . ' = NULL;';
eval ($codestr);
}
}
But eval can be very very bad, I would suggest doing this another way such as using an array, however this probably could be accomplished in the first loop. For example the null or false value could be in the else part of the check for empty($errors) so that if there is an error, that one is put in false like.
$files = array();
foreach ($uploadedFiles as $key => $row) {
if (!empty($row[1])) {
$files['$file' . ($key+1)] = $row[0];
} else {
$files['$file' . ($key+1)] = false; //id use false instead of null in an array
}
}
You should also be careful of sql injection, although it looks like you are setting the variables, its still wise to use a prepared query just in case changes are made latter, that could open you up to SQL injection attacks.
and:
// double slash
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
// file was successfuly moved
echo "Files Uploaded !" . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($file_name . $sExt, 1);
} else {
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
foreach ($uploadedFiles as $key => $row) {
if ($row[1]) { // $row[1] is never empty
${'file' . ($key+1)} = $row[0];
} else {
${'file' . ($key+1)} = NULL;
}
}
better will be:
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
echo "Files Uploaded !" . $_FILES['files']['name'][$key];
$uploadedFiles[] = $file_name . $sExt;
}
//instead of variable $file1 etc..
foreach($uploadedFiles as $filename){
}

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>';

multi image upload wrong quantity on file-upload

i like to upload some images to a directory with the help of arrays. therefore i have this code:
$allowedExtensions = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$maxSize = 2097152;
$Dir = "a/b/c/d";
$storageDir = "a/b/c/d/tmp_images";
//Arrays
$errors2 = $output = array();
if(!empty($_FILES['image'])){
// Validation loop (I prefer for loops for this specific task)
for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {
$fileName = $_FILES['image']['name'][$i];
$fileSize = $_FILES['image']['size'][$i];
/*$fileErr = $_FILES['image']['error'][$i];*/
$fileExt = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
// Dateiendung überprüfen
if (!in_array($fileExt, $allowedExtensions)) {
$errors2[$fileName][] = "format $fileExt in $fileName is not accepted";
}
// check filesize
if ($fileSize > $maxSize) {
$errors2[$fileName][] = "maxsize of 2MB exceeded";
}
}
/*// Handle validation errors here
if (count($errors) > 0) {
echo "Fehler beim Upload des Bildmaterials:";
echo ($errors); ->gibt "Array" aus
}*/
if (is_dir($Dir)){
mkdir($storageDir, 0755);
}else{
mkdir($Dir, 0755);
mkdir($storageDir, 0755);
}
// Fileupload
for ($i = 0; isset($_FILES['image']['name'][$i]); $i++) {
// Get base info
$fileBase = basename($_FILES['image']['name'][$i]);
$fileName = pathinfo($fileBase, PATHINFO_FILENAME);
$fileExt = pathinfo($fileBase, PATHINFO_EXTENSION);
$fileTmp = $_FILES['image']['tmp_name'][$i];
// Construct destination path
$fileDst = $storageDir.'/'.basename($_FILES['image']['name'][$i]);
for ($j = 0; file_exists($fileDst); $j++) {
$fileDst = "$storageDir/$fileName-$j.$fileExt";
}
// Move the file
if (count($errors2) == 0) {
if (move_uploaded_file($fileTmp, $fileDst)) {
...
}
}
the problem with that code is the following: in case of uploading two or more files with an accepted ending it will echo out:
Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access abc2.png in /a/b/xxx.php on line xxx
which refers to that line:
if (move_uploaded_file($fileTmp, $fileDst)) {
this message will be shown for each picture except the first one. so i have no clue what i do wrong. i would really appreciate if there is someone who could help me out. i really would appreciate. thanks a lot.
First of, I would name the uploaded fields seperatly. E.g. name the first field <input name="image_1" type="file" /> and the second <input name="image_2" type="file" />. Then you can iterate over the $_FILES array instead:
foreach($_FILES as $fileId => $file){
//make sure it's a file you want (optional)
if(!preg_match("/^image\_\d+$/",$fileId){
continue;
}
//the rest of your code from the for loop
}
Secondly, you need to make sure that your form's enctype is multipart/form-data.
Does any of this help?
Your code is very similar to my answer at limiting the checking condition while uploading swf files
This is how you should implement such ..
FULL Script
<?php
error_reporting ( E_ALL );
$allowedExtensions = array (
'jpg',
'jpeg',
'png',
'bmp',
'tiff',
'gif'
);
$maxSize = 2097152;
$dirImage = "photos/tmp_images";
$errors = $output = array ();
if (isset ( $_FILES ['image'] )) {
foreach ( $_FILES ['image'] ['tmp_name'] as $key => $val ) {
$fileName = $_FILES ['image'] ['name'] [$key];
$fileSize = $_FILES ['image'] ['size'] [$key];
$fileTemp = $_FILES ['image'] ['tmp_name'] [$key];
$fileExt = pathinfo ( $fileName, PATHINFO_EXTENSION );
$fileExt = strtolower ( $fileExt );
if (empty ( $fileName ))
continue;
// Dateiendung überprüfen
if (! in_array ( $fileExt, $allowedExtensions )) {
$errors [$fileName] [] = "format $fileExt in $fileName is not accepted";
}
if ($fileSize > $maxSize) {
$errors [$fileName] [] = "maxsize of 2MB exceeded";
}
if (! mkdir_recursive ( $dirImage, 0777 )) {
$errors [$fileName] [] = "Error Creating /Writing Directory $dirImage ";
}
// Construct destination path
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $fileName;
$filePrifix = basename ( $fileName, "." . $fileExt );
$i = 0;
while ( file_exists ( $fileDst ) ) {
$i ++;
$fileDst = $dirImage . DIRECTORY_SEPARATOR . $filePrifix . "_" . $i . "." . $fileExt;
}
// Move the file
if (count ( $errors ) == 0) {
if (move_uploaded_file ( $fileTemp, $fileDst )) {
// ...
$output [$fileName] = "OK";
}
}
}
}
function mkdir_recursive($pathname, $mode) {
is_dir ( dirname ( $pathname ) ) || mkdir_recursive ( dirname ( $pathname ), $mode );
return is_dir ( $pathname ) || mkdir ( $pathname, $mode );
}
if (! empty ( $errors )) {
echo "<pre>";
foreach ( $errors as $file => $error ) {
echo $file, PHP_EOL;
echo "==============", PHP_EOL;
foreach ( $error as $line ) {
echo $line, PHP_EOL;
}
echo PHP_EOL;
}
echo "</pre>";
}
if (! empty ( $output )) {
echo "<pre>";
echo "Uploaded Files", PHP_EOL;
foreach ( $output as $file => $status ) {
echo $file, "=", $status, PHP_EOL;
}
echo "</pre>";
}
?>
<form method="post" enctype="multipart/form-data">
<label for="file">Filename 1:</label> <input type="file" name="image[]"
id="file" /> <br /> <label for="file">Filename 2:</label> <input
type="file" name="image[]" id="file" /> <br /> <label for="file">Filename
3:</label> <input type="file" name="image[]" id="file" /> <br /> <input
type="submit" name="submit" value="Submit" />
</form>
Why are you accessing the $_FILES superglobal array as a three dimensional array?
if you want the file name of the file uploaded from an <input type="file" name="image"/> all you have to do is $name = $_FILES[ 'image' ][ 'name' ] there is no need for the [ $i ] at the end.
You need to loop over the entries in $_FILES like this:
foreach ( $_FILES as $inputName => $fileData )
{
// $inputName is be 'image` for the first input and so on,
// $fileData will be an array of the attributes [ 'name', 'tmp_name', ... ]
}
I'm not sure if this may solve it for you, but you can try to convert these into "normal" $_FILES values.
$arr_files = #$_FILES['image'];
$_FILES = array();
foreach(array_keys($arr_files['name']) as $h)
$_FILES["image_{$h}"] = array( 'name' => $arr_files['name'][$h],
'type' => $arr_files['type'][$h],
'tmp_name' => $arr_files['tmp_name'][$h],
'error' => $arr_files['error'][$h],
'size' => $arr_files['size'][$h]);
And then run the loop like normal.
See previous related answer

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