Uploading multiple images with random file names - php

Right now, all the images upload fine with their file names, but I want to change the file names to random names (to avoid names with symbols) but when I try to do so, if I upload more than one image, they will all be the same image of the last selected file.
<input type='file' name='file[]'>
And the conditions:
$allowed = array('jpg', 'JPG', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$max_file_size = 2048*1000;
$path = "images/images/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
if ($_FILES['file']['name'] != "") {
foreach ($_FILES['file']['name'] as $f => $name) {
if ($_FILES['file']['error'][$f] == 4) {
continue;
}
if ($_FILES['file']['error'][$f] == 0) {
if ($_FILES['file']['size'][$f] > $max_file_size) {
$errors[] = "$name is too large!";
continue;
}
else if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $allowed) ){
$errors[] = "$name is not a valid format";
continue;
}
else{
if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$name))
$images = array(
'images' => $path.$name,
'ad_id' => $_POST['id']
);
add_images($images);
$count++;
}
}
}
}
}

You can prepend the index to the image name. Try to change
if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$name))
to
if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$f.$name))
(and the same principle for 'images' => $path.$name,)

Related

Renaming files with random string after upload and storing the name in array

I'm trying to process multiple files upload with foreach then rename the files with random string and store the file names in an array, here's my current code:
// this variable stores the id of last inserted row in MySQLi DB
$last_shipment_id = mysqli_insert_id($con);
// Array of valid file formats
$valid_formats = array("jpg", "jpeg", "png");
// the upload path
$path = "../uploads/"; // Upload directory
// count variable for foreach counting
$count = 0;
// variable for generated file names to use them later
$new_file_name = array();
foreach ($_FILES['files']['name'] as $f => $name) {
$ext = pathinfo($name, PATHINFO_EXTENSION);
$new_file_name[] = randomNumber(14)."-".$last_shipment_id.'.'.$ext;
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue;
} else {
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$new_file_name)) {
}
}
}
}
I can't find where the problem is, should I use foreach for every generated file name then use move_uploaded_file inside the foreach?
You are completely wrong. You have initialized $_FILES['files']['name'] in the foreach statement and trying to access $_FILES['files']['error'] and $_FILES["files"]["tmp_name"] in each iteration. Since this is an array it not possible.
So solution is as follows,
foreach($_FILES as $key=>$row){
$ext = pathinfo($row[$key]['files']['name'], PATHINFO_EXTENSION);
$new_file = randomNumber(14)."-".$last_shipment_id.'.'.$ext;
array_push($new_file_name,$new_file);
if ($row[$key]['files']['error'] == 4) {
continue;
}
if ($row[$key]['files']['error'] == 0) {
if( ! in_array($ext, $valid_formats) ){
$error_msg = "The file ". $new_file. " is not a valid format";
array_push($message, $error_msg);
continue;
} else {
if(move_uploaded_file($row[$key]["files"]["tmp_name"], $path.$new_file_name[$key])) {
}
}
}
}
Hope this can help you.

How to fix invalid argument supplied for foreach() php?

i tried to apply some of the existing samples found here in stackoverflow but the problem seems to be unsolved.
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*1000;
$path = "upload/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $name) {
if ($_FILES['files']['error'][$f] == 4) {
continue; // Skip file if any error found}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ) {
$message[] = "$name is not a valid format";
...
As urfusion said, $_FILES['files']['name'] is a string, not an array.
That you can do to iterate over all the filenames of submitted files is something like that:
if(is_array($_FILES['files']) && !empty($_FILES['files'])){ // if1
foreach($_FILES['files'] as $file_index=>$file_value){
if($file_index==='name'){ // if2
echo $file_value; // or do something with that name
} // end if2
} // end foreach
} // end if1

multiples upload rename (while function)

Okay so, the below php upload script already WORK, the part didn't work is only of renaming file if exist.
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $img_name) {
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$img_name est trop lourde !";
continue;
}
elseif( ! in_array(pathinfo($img_name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$img_name est pas valide !";
continue;
}
else{
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$img_name)) {
while(file_exists($path . $img_name)){
$increment++;
$img_name = $name.$increment.'.'.$extension;
$count++;
}
}
}
}
}
}
I have search a lot on php doc, try fews fews way to go but .. when i'm trying a file with a name already uploaded before, it's not changing the actual upload file.
You are determining the filename after you upload the file. determine it before.
Change like:
while(file_exists($path . $img_name)){
$increment++;
$img_name = $name.$increment.'.'.$extension;
$count++;
}
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$img_name)) {
// File Uploaded !!!
}
Edit:
I have changed your code. Comments in code.
$valid_formats = array("jpg", "JPG", "png", "PNG" , "bmp", "BMP");
$max_file_size = 1024*6000; //60 000 kb - 6 mb
$path = "../../../img/final/img_recipes/"; //directory
$count = 0;
$uploaded_image_names = array(); //create a new array
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $img_name) {
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$img_name est trop lourde !";
continue;
}
elseif( ! in_array(pathinfo($img_name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$img_name est pas valide !";
continue;
}
else{
// Moved name and extension initialization to here.
// Here is where you want to determine the actual filename
$name = pathinfo($img_name, PATHINFO_FILENAME);
$extension = pathinfo($img_name, PATHINFO_EXTENSION);
$increment = 0;
while(file_exists($path . $img_name)){
$img_name = $name.$increment.'.'.$extension;
$increment++;
}
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$img_name)) {
$count++;
//Store the uploaded filenames to array here
$uploaded_image_names[] = $path.$img_name;
}
}
}
}
}
foreach ($uploaded_image_names as $uploaded_image_name){
//store the $uploaded_image_name to db
}
Note: I have not tested this, as I don't have PHP available with me now.

php images upload does not work

I am trying to figure out why i am getting a bunch of errors when trying to upload multiple images
the input is <input type='file' name='file[]' multiple>
the check is:
if (!empty($_FILES['file'])){
if ($_FILES['file']['name'] != "") {
$count = 0;
foreach ($_FILES['file']['name'] as $filename) {
$allowed = array('jpg', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
$img_name = $filename;
$img_extn = strtolower(end(explode('.', $img_name)));
$img_temp = $_FILES['file']['tmp_name'][$count];
$count = $count + 1;
if(in_array($img_extn, $allowed) === true){
$img_path = 'images/images/' . substr(md5(time()), 0, 10) . '.' . $img_extn;
move_uploaded_file($img_temp, $img_path);
$images = array(
'images' => $img_path,
'post_id' => $_POST['id']
);
add_images($images);
}else{
$errors[] = ''.$filename.' - file type is not allowed. Only: ' . implode(', ', $allowed) . '';
}
}
}
}
only one image is being uploaded to the temp folder
and how can i connect the post_id to the database?
Why don't you use $filename inside the foreach instead of $_FILES['file']['name']?
$img_name = $_FILES['file']['name'];
should be
$img_name = $filename;
since you are using for-each
foreach ($_FILES['file']['name'] as $filename) {
}
Multiple images. it has to be $_FILES['file']['name'][0]
Use indexes to access it. Since I see that you haven't used indexes. explode() throws a warning because it's trying to break an array.

how can I add imaging handling got this script effectively

hopefully someone can help me here. been up all night browsing and nothing I try seems to work, but im new to php so im slow. I need to upload 6 images, and this works great. but then I realized you can upload not only images but all other file types. Im trying to be able to limit it to just images under 100kb each. heeeeelllllllpppppp!!!! please!
function findexts ($filename) { $filename = strtolower('$filename') ;
$exts = preg_split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}
$ext = findexts ($_FILES['images']['name']) ;
$ran = rand ();
$ran2 = $ran.".";
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
See the answer to both your questions here:
https://stackoverflow.com/a/9153419/723855
Add this function to your script (modified from link):
function acceptFileUpload($thefile){
if(isset($_FILES[$thefile])) {
$errors = array();
$maxsize = 2097152;
$acceptable = array(
'application/pdf',
'image/jpeg',
'image/jpg',
'image/gif',
'image/png'
);
if(($_FILES[$thefile]['size'] >= $maxsize) || ($_FILES[$thefile]["size"] == 0)) {
$errors[] = 'File too large. File must be less than 2 megabytes.';
}
if(!in_array($_FILES[$thefile]['type'], $acceptable)) && (!empty($_FILES[$thefile]["type"]))) {
$errors[] = 'Invalid file type. Only PDF, JPG, GIF and PNG types are accepted.';
}
if(count($errors) !== 0) {
return true;
} else {
foreach($errors as $error) {
echo '<script>alert("'.$error.'");</script>';
return false;
}
die(); //Ensure no more processing is done
}
}
}
Then in your script change your while loop to use this function to check for a valid file:
while(list($key,$value) = each($_FILES['images']['name']))
{
if(!empty($value))
{
if(acceptFileUpload('images'))
{
$filename = $ran.$value;
$filename=str_replace(" "," _ ",$filename);// Add _ inplace of blank space in file name, you can remove this line
$add = "media/".$ran."$filename";
$insert_query = "INSERT INTO ....VALUES ...";
//echo $_FILES['images']['type'][$key];
// echo "<br>";
copy($_FILES['images']['tmp_name'][$key], $add);
chmod("$add",0777);
mysql_query($insert_query);
}
}
}
I might not have that parameter right that is getting passed to acceptFileUpload().
Four functions to run on the processing script on each file, if all tests pass then the file meets your conditions and can be safely stored (png / jpg / gif + non-zero + 10Kb limit + is uploaded file)
//Example Call: checkFileExtension($_FILES['fieldname']['name']);
function checkFileExtension($filename) {
$filename = strtolower($filename) ;
$filenamePartsArray = preg_split("[/\\.]", $filename) ;
$extension = $filenamePartsArray[count($filenamePartsArray) - 1];
if (($extension == 'gif') || ($extension == 'jpeg') || ($extension == 'jpg') || ($extension == 'png')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileMIME($_FILES['fieldname']['type']);
function checkFileMIME($filetype) {
if (($filetype == 'image/png') || ($filetype == 'image/jpeg') || ($filetype == 'image/gif')) {
return true;
} else {
return false;
}
}
//Example Call: checkFileSize($_FILES['fieldname']['size'], 10);
function checkFileSize($filesize, $limitKb = 0) {
if ($filesize == 0) {
return false;
}
if ($limitKb != 0) {
if ($filesize > ($limitKb * 1024)) {
return false;
}
}
return true;
}
//Native Call: is_uploaded_file($_FILES['fieldname']['tmp_name']);
Edit: pseudo example use
foreach ($_FILES as $fieldname => $file) {
if ((checkFileExtension($file['name'])) && (checkFileMIME($file['type'])) && (checkFileSize($file['size'], 10)) && (is_uploaded_file($file['tmp_name']))) {
//Move the image with move_uploaded_file
//Save the file location with DB insert
}
}
you can check the file type with
$_FILES['image']['type']
or if you want to check the extension too
$extension = explode('.',(string)$_FILES['image']['name']);
//then check if its "jpg", "gif" or "png"
the file size can be checked with
$_FILES['image']['size']
so your script should be like this for each of your image updates:
$extension = explode('.',$_FILES['image']['name']);
$imgextensions = array();
$size = $_FILES['image']['size'];
if(($extension == 'jpg' || $extension == 'gif' || $extension == 'png') &&
$size < 100000 ){
// upload your file to your filesystem
}else{
//inform the user
}

Categories