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.
Related
I am trying to upload image to database MySQL. But I have a problem, when I am trying to upload one image, the image inserted twice.
For example:
I have "A.jpg" if I try to upload it
the inserted data will be like "A.jpg,A.jpg"
What I want in database "A.jpg"
and if I try to upload multiple images like "A.jpg,B.jpg and C.jpg"
the inserted data will be like "B.jpg,B.jpg,C.jpg,C.jpg"
What I want in database "A.jpg,B.jpg,C.jpg"
I've tried to search on google but no results, anyone can help me to resolve this problem ? Thanks
Here is my code :
include('koneksi.php');
date_default_timezone_set('Asia/Jakarta');
$id_user = $_POST['id_user'];
$caption = $_POST['caption'];
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {
$name = $_FILES['files']['name'][$i];
$size = $_FILES['files']['size'][$i];
$type = $_FILES['files']['type'][$i];
$tmp = $_FILES['files']['tmp_name'][$i];
$explode = explode('.', $name);
$ext = end($explode);
$updatdName = $explode[0] . time() .'.'. $ext;
$path = 'gallery/';
$path = $path . basename( $updatdName );
if(empty($_FILES['files']['tmp_name'][$i])) {
$errors[] = 'Please choose at least 1 file to be uploaded.';
}else {
$allowed = array('jpg','JPG','jpeg','JPEG','gif','GIF','bmp','BMP','png','PNG');
$max_file_size = 1024*1024*2;; // 2MB
if(in_array($ext, $allowed) === false) {
$errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
}
if($size > $max_file_size) {
$errors[] = 'The file <b>'.$name.'</b> size is too hight.';
}
}
if(empty($errors)) {
// if there is no error then set values
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$errors = array();
if(!file_exists('gallery')) {
mkdir('gallery', 0777);
}
if(move_uploaded_file($tmp, $path)) {
echo '<script>window.history.back()</script>';
}else {
echo 'Something went wrong while uploading
<b>'.$name.'</b>';
}
}else {
foreach($errors as $error) {
echo '<p>'.$error.'<p>';
}
}
}
if(!empty($files)) {
$files['file_name'][] = $updatdName;
$files['size'][] = $size;
$files['type'][] = $type;
$names = implode(',', $files['file_name']);
$sizes = implode(',', $files['size']);
$types = implode(',', $files['type']);
$sql="INSERT into status VALUES(NULL, '$id_user', '$names','$caption','foto',NOW()); ";
mysqli_query($koneksi, $sql);
}
You're setting $files['file_name'][] in the while loop and also right before inserting into the DB. You just need to remove 2nd call to $files['file_name'][] = $updatdName;
Here is a simplified version of what you're doing.
<?php
$_FILES[] = ['name' => 'A'];
$_FILES[] = ['name' => 'B'];
$_FILES[] = ['name' => 'C'];
$files = [];
foreach ($_FILES as $file) {
$updatdName = $file['name'];
// You're setting it here
$files['file_name'][] = $updatdName;
}
if (!empty($files)) {
// And also here.
$files['file_name'][] = $updatdName;
$names = implode(',', $files['file_name']);
echo $names;
}
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.
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;
}
I am uploading multiple images from a single input and rename all uploaded files. My problem is; I need to display all uploaded images with separate variables
For example:
If user upload 3 images, i need to echo as
$upload1 = 1st file name
$upload2 = 2nd file name
$upload3 = 3rd file anme
No of images uploaded (upload number of file)
Here is my current code:
<?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';
}
$desired_dir = "user_data/";
if (empty($errors)) {
if (is_dir($desired_dir) == false) {
mkdir("$desired_dir", 0700); // Create directory if it does not exist
}
if (move_uploaded_file($file_tmp, "$desired_dir/" . $file_name . $sExt)) {
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 1);
} else {
echo "Couldn't upload file " . $_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);
}
}
}
echo $file1;
echo $file2;
echo $file3;
echo $file4;
echo $file5;
?>
I tried this and I get the error
Parse error: syntax error, unexpected 'png' (T_STRING) in C:\Users\logon\Documents\NetBeansProjects\upload file rename single and multiple\multiple file rename\method 2\process.php(43) : eval()'d code on line 1
What am I doing wrong? can some one help me
I think the " = $row[0];" on line 42 might not do what you want it to do. Because of the double quotes, the value of the variable $row[0] will be printed in the code.
The code running through the eval will look something like this:
$file0 = FILENAME.png;
Instead of this:
$file0 = $row[0];
To solve the problem you could simply turn line 42 into the following:
$codestr = '$file' . ($key+1) . ' = $row[0];';
More information about the difference between single and double quotes: http://php.net/manual/en/language.types.string.php
Edit: For the correct names of the files you could change $_FILES['files']['name'][$key] to $file_name . $sExt. Hope it helps!
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++;
}
?>