Problems with Uploading Script [duplicate] - php

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

Related

How to move a object(GdImage) to a specific folder?

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

Unable to reduce image file size in php while uploading

I following code can upload multiple image and rename them while upload and it works fine.Then i tried to implement image compress but this doesn't work, can someone help me to solve this issue.
Without compress method
if (!empty($_POST)) {
$newname = md5(rand() * time());
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 = "upload/";
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 "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
}
}
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);
}
}
}
With compress method
if (!empty($_POST)) {
$newname = md5(rand() * time());
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 = "upload/";
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 "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
}
}
function compress($source, $destination, $quality) {
$info = getimagesize($source);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($source);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($source);
} elseif ($info['mime'] == 'image/png') {
$image = imagecreatefrompng($source);
}
imagejpeg($image, $destination, $quality);
return $destination;
}
$source_img = $uploadedFiles;
$destination_img = 'compres/';
$d = compress($source_img, $destination_img, 60);
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);
}
}
}
The problem with your code is that $file_name is the same for all images. Also you did not get the correct image resource. Here is the working solution:
<?php
if (!empty($_POST)) {
$newname = md5(rand() * time());
if (isset($_FILES['files'])) {
$uploadedFiles = array();
foreach ($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$errors = array();
$file_name = md5(uniqid("") . time());
sleep(1);//We give a second for breathing
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
$filename = $_FILES["files"]["name"][$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 = "upload/";
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 "Couldn't upload file " . $_FILES['files']['name'][$key];
$uploadedFiles[$key] = array($_FILES['files']['name'][$key], 0);
}
} else {
print_r($errors);
}
}
function compress($filename, $destination, $quality) {
$info = getimagesize($filename);
if ($info['mime'] == 'image/jpeg') {
$image = imagecreatefromjpeg($filename);
} elseif ($info['mime'] == 'image/gif') {
$image = imagecreatefromgif($filename);
} elseif($info['mime'] == 'image/png') {
$image = imagecreatefrompng($filename);
}else{
$image =null;
}
return imagejpeg($image, $destination, $quality);
}
$compressed = 0;
$destination_img = 'compressed/';
foreach($uploadedFiles as $km=>$val){
$photos = $desired_dir . $val[0];
$compressed += compress($photos, $destination_img.$val[0], 60);
}
if($compressed>=1){
echo $compressed.' Images compresses';
}else{
echo 'No Image Compressed';
}
}
}
?>
<form method="POST" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="file" name="files[]">File 1<br>
<input type="file" name="files[]">File 2<br>
<input type="file" name="files[]">File 3<br>
<input type="submit" name="filesubmit" value="Submit">
</form>
Check the following links to better understand how image processing and generation:
imagejpeg()
getimagesize()
I hope my answer helps you.

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

unable to echo multiple images with multiple variable

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!

Categories