unable to echo multiple images with multiple variable - php

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!

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){
}

Just Inserting Blank array() inside in mysql error

I want to store image name only inside mysql table but issue is that it's uploading blank array and giving error
array to string conversion.
if(isset($_POST['prd_submit']) && isset($_FILES['prd_image'])){
// Define Input Variables
$name = user_input($_POST['prd_name']);
$detail = user_input($_POST['prd_detail']);
$image = $_FILES['prd_image'];
$buy_link = user_input($_POST['prd_link']);
$price = user_input($_POST['prd_price']);
$category = $_POST['prd_category'];
$country = $_POST['prd_country'];
// Control Error Inputs
if(empty($name)){
$name_err = "Name is missing";
}
if(empty($detail)){
$detail_err = "Detail is missing";
}
if(empty($price)){
$price_err = "Price is missing";
}
if(empty($buy_link)){
$buy_link_err = "Link is missing";
}
// File Upload Function
$OutFiles = array();
foreach($image as $Index=>$Items){
foreach($Items as $Key=>$Item){
$OutFiles[$Key][$Index] = $Item;
}
}
if($OutFiles[0]['error']){
$image_err = $Errors[$OutFiles[0]['error']];
}else{
foreach($OutFiles as $Index=>$File){
$UploadDir = $DocRoot.'/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.',$imageName);
$file_ext = $file_ext[count($file_ext)-1];
//FILE NAME
$filename = (rand()).'-'.(time()).'.'.$file_ext;
//FILE EXTENTION ERROR
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif"){
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
$OutFiles[$Index]['name'] = $filename;
$uploadok++;
}elseif($uploadok == 0){
$error = "Sorry File is Not Upload";
}else{
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
}
// Insert DB
if($name_err == '' && $detail_err == '' && $image_err == '' && $price_err == '' && $buy_link_err == ''){
$Code = 0;
try{
$insert_data = ("INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$image','$price','$buy_link','$category','$date')");
$insert_data = $conn->query($insert_data);
}catch(PDOException $E){
$Code = $E->getCode();
}
if($Code == 0){
$error = "<div class='alert alert-success'>Your Product Registration Request Has Submitted!</div>";
}elseif($Code == 23000){
$error = "<div class='alert alert-info'>Duplicate Entry</div>";
}else{
$error = "Unabel to enter data";
}
}
To much confuse what thing i'm doing wrong in it and if implode array but how i can implode i just need name only.
Change $image To $filename in your INSERT query.
Because, $image = $_FILES['prd_image']; is an array and you wanted to store the file name which is just uploaded to upload folder. So, use $filename which is uploaded using elseif(move_uploaded_file($File['tmp_name'],$UploadDir.$filename)){
Query
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
Uploading Multiple File : Move your INSERT Query inside foreach. It will insert into table on every successful upload.
foreach ($OutFiles as $Index => $File) {
$UploadDir = $DocRoot . '/upload/';
$imageName = $File['name'];
//GETTING FILE EXTENTION
$file_ext = explode('.', $imageName);
$file_ext = $file_ext[count($file_ext) - 1];
//FILE NAME
$filename = (rand()) . '-' . (time()) . '.' . $file_ext;
//FILE EXTENTION ERROR
if ($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg" && $file_ext != "gif") {
$error = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
} elseif (move_uploaded_file($File['tmp_name'], $UploadDir . $filename)) {
$OutFiles[$Index]['name'] = $filename;
$insert_data = "INSERT INTO product (name,country,detail,image,price,buy_link,category,date_posted) VALUES ('$name','$country','$detail','$filename','$price','$buy_link','$category','$date')";
$insert_data = $conn->query($insert_data);
$uploadok++;
} elseif ($uploadok == 0) {
$error = "Sorry File is Not Upload";
} else {
$uploadok--;
$error = "Sorry File is Not Upload";
}
}
And, remove try/catch from below as now it's INSERTING on every UPLOAD.

How to make a case sensitive code for file upload by name

So i have more than one image to upload, each one being a new line in my mysql table:
I use this code for file input with name="profile"
if (isset($_FILES['profile']) === true) {
if (empty($_FILES['profile']['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png')
$file_name = $_FILES['profile']['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $_FILES['profile']['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, 1, $file_temp, $file_extn);
header('Location: galery.php');
exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
(change_image) function makes this MySql query
$sql = "UPDATE `art_$id` SET `path` = \"" . $file_path . "\" WHERE `row` = " . (int)$row;
But i want to repeat this code for profil1, profil2... and change accordingly the row (example : profil4 would change row 4 ), without having to repeat this code for each file='name'.
How would i go about that?
Irrespective of your form have "how many fields as of file and what they are named??" . Following code will upload them one by one ..Check it
$rowid=1;
foreach($_FILES as $key=>$image_uploaded)
{
if (isset($image_uploaded[$key]) === true) {
if (empty($image_uploaded[$key]['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png')
$file_name = $image_uploaded[$key]['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $image_uploaded[$key]['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, $rowid++, $file_temp, $file_extn);
//change as you need
header('Location: galery.php');
exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
}
Thanks for your answer, as i have a specific submit button for each form and don't wont to validate all forms at once i used this code :
for ($row = 1; $row <= 9; $row++) {
if (isset($_FILES["profile" . $row]) === true) {
if (empty($_FILES["profile" . $row]['name']) === true) {
echo 'Please choose a file!';
}else {
$allowed= array('jpg', 'jpeg', 'png');
$file_name = $_FILES["profile" . $row]['name'];
$file_exts = explode('.', $file_name);
$file_extn = strtolower(end($file_exts));
$file_temp = $_FILES["profile" . $row]['tmp_name'];
if (in_array($file_extn, $allowed) === true) {
change_image($session_user_id, $row, $file_temp, $file_extn);
//header('Location: galery.php');
//exit();
}else {
echo 'Incorrect file type . allowed files are : ';
echo implode(", ", $allowed);
}
}
}
}
And for file input i use name="profile1",name="profile2",....,name="profile9"(for this case).
Here is the the code which will add 1,2,3 at end of the image file name
Bellow function will check the file exist in dir or not and return new file name now you can use the function before change_image function call and get new file name and pass new name in change_image for save.
function getFileName($fileName, $file_extn){
$fileNameWithoutExt = pathinfo($fileName, PATHINFO_FILENAME);
$i = 1;
while(!file_exists('image/art/' . $fileName)){
$fileName = $fileNameWithoutExt . $i . "." . $file_extn;
$i++;
}
return $fileName;
}

Insert multiple image names into same database field, separated by comma

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

Categories