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>';
Related
I'm working on a image converter that convert jpg and png to webp and webp to jpg and png and i've been trying to make that the converted files go to a specific folder instead of my working folder but it doesn't go on my convert forlder
here's my code
<?php
require "db.php";
$pdo = new \PDO(DSN, USER, PASS);
if (!empty($_FILES['files']['name'][0])) {
$files = $_FILES['files'];
$fileName = $_POST['name'];
$fileTag = $_POST['tag'];
$fileDescription = $_POST['description'];
$convert = $_POST['convert'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'jpeg', 'png', 'webp');
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $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 <= 2097152) /* 2mb */ {
$file_name_new = uniqid('IMG-', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
$query = "INSERT INTO images(name, tag, description, images) VALUES (:name, :tag, :description,:images)";
$statement = $pdo->prepare($query);
$statement->bindValue(':name', $fileName, \PDO::PARAM_STR);
$statement->bindValue(':tag', $fileTag, \PDO::PARAM_STR);
$statement->bindValue(':description', $fileDescription, \PDO::PARAM_STR);
$statement->bindValue(':images', $file_name_new, \PDO::PARAM_STR);
$statement->execute();
$upload = $statement->fetchAll();
} else {
$failed[$position] = "[{$file_name}] failed to upload.";
}
} else {
$failed[$position] = "[{$file_name}] is too large.";
}
} else {
$failed[$position] = "[{$file_name}] failed to upload {$file_error}.";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
} else {
echo 'no files';
}
if (exif_imagetype($file_destination) == IMAGETYPE_PNG && $convert ==='webp') {
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
move_uploaded_file($file_destination, 'convert/');
} elseif (exif_imagetype($file_destination) == IMAGETYPE_JPEG && $convert ==='webp') {
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
} elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='png') {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
}elseif (exif_imagetype($file_destination) == IMAGETYPE_WEBP && $convert ==='jpg') {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'jpg', $file_name_new));
move_uploaded_file($file_tmp, 'convert/');
}else {
echo "can't convert it";
}var_dump($image);
I tried changing the variable in the move_uploaded_file but still won't let me
I'm making an image converter and I wanted to make a condition to check the file extension et change it to another one, ex: if it's jpg/png change it to webp
I keep having the warning on the line 85, 90 and 95
<?php
require "db.php";
$pdo = new \PDO(DSN, USER, PASS);
if (!empty($_FILES['files']['name'][0])) {
$files = $_FILES['files'];
$fileName = $_POST['name'];
$fileTag = $_POST['tag'];
$fileDescription = $_POST['description'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'jpeg', 'png', 'webp');
foreach ($files['name'] as $position => $file_name) {
$file_tmp = $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 <= 2097152) /* 2mb */ {
$file_name_new = uniqid('IMG-', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$uploaded[$position] = $file_destination;
$query = "INSERT INTO images(name, tag, description, images) VALUES (:name, :tag, :description,:images)";
$statement = $pdo->prepare($query);
$statement->bindValue(':name', $fileName, \PDO::PARAM_STR);
$statement->bindValue(':tag', $fileTag, \PDO::PARAM_STR);
$statement->bindValue(':description', $fileDescription, \PDO::PARAM_STR);
$statement->bindValue(':images', $file_name_new, \PDO::PARAM_STR);
$statement->execute();
$upload = $statement->fetchAll();
} else {
$failed[$position] = "[{$file_name}] failed to upload.";
}
} else {
$failed[$position] = "[{$file_name}] is too large.";
}
} else {
$failed[$position] = "[{$file_name}] failed to upload {$file_error}.";
}
} else {
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if (!empty($uploaded)) {
print_r($uploaded);
}
if (!empty($failed)) {
print_r($failed);
}
} else {
echo 'no files';
}/*
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
$image = imagecreatefromwebp($file_destination);
imagejpeg($image, str_replace('webp', 'jpg', $file_name_new));
*/
if (exif_imagetype($file_name_new) == IMAGETYPE_PNG) {
$image = imagecreatefrompng($file_destination);
imagewebp($image, str_replace('png', 'webp', $file_name_new));
} elseif (exif_imagetype($file_name_new) == IMAGETYPE_JPEG) {
$image = imagecreatefromjpeg($file_destination);
imagewebp($image, str_replace('jpg', 'webp', $file_name_new));
} elseif (exif_imagetype($file_name_new) == IMAGETYPE_WEBP) {
$image = imagecreatefromwebp($file_destination);
imagepng($image, str_replace('webp', 'png', $file_name_new));
}
It's not the best but i'll be working on making it better once the warning is gone
I tried to change the condition but kept having this warning
It also appeared when I made the converted file go to a folder
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 this script:
UPLOAD MULTIPLE FILES - PIECE OF CODE
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 0) {
}
else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
$dest = $path . $uniq_name; //FULL DESTINATION
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
$count++;
}
}
}
Please tell me how to insert into my mysql database all the photo names, in the PHOTOS field, separated by a comma.
When I'm writing the 2 lines code:
$a = "INSERT INTO dbu.dbu_data(photos) VALUES ('$uniq_name')";
mysql_query($a);
IT INSERTS A TABLE ROW FOR EACH PHOTO THAT WAS UPLOADED AND I DON'T WANT THAT.
$delimiter = ",";
$str = '';
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 0) {
// surely your move logic needs to go here
} else{ // No error found! Move uploaded files
$ext = pathinfo($_FILES['files']['name'][$f], PATHINFO_EXTENSION);
$uniq_name = uniqid() . '.' .$ext;
$dest = $path . $uniq_name; //FULL DESTINATION
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $dest)) {
$count++;
if (strlen($str)) {
$str .= $delimiter;
}
$str .= $dest;
}
}
}
if (strlen($str)){
$a = "INSERT INTO dbu.dbu_data(photos) VALUES ('" . mysql_real_escape_string($str) . "')";
mysql_query($a);
}