multiples upload rename (while function) - php

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.

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.

rename uploaded file some error?

Below is the code I used in order to upload files into a directory. It works fine. My main question is:
I have tried to do so below:
function get_unique_filename($name) {
$imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$date = new DateTime();
$date= $date->getTimestamp();
$newname ="bogen_". substr(hash('ripemd160',$date),0,12) .".".$imgExt;
return $newname;
}
function upload(){
$valid_formats = array("jpg", "png");
$max_file_size = 1024*3000;
$path = "../uploads/images/";
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
foreach ($_FILES['files']['name'] as $f => $name){
if ($_FILES['files']['error'][$f] == 4) {
continue;
}
if ($_FILES['files']['error'][$f] == 0) {
if ($_FILES['files']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
continue;
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
// No error found! Move uploaded files
else{
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$this->get_unique_filename($name))){
$count++; // Number of successfully uploaded file
// save name to database
$this->name = $newname;
if($this->create()){
// successfully added to databaes
}
}
}
}
}
}
}
when upload Multi files i'll get same filename and files...how can fix it:
You have to check if file exists with same name and if exists then you have to rename the file.
function get_unique_filename($name) {
$imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$date = new DateTime();
$date = $date->getTimestamp();
$dir = "../uploads/images/";
$i = 0;
do {
$newname ="bogen_". substr(hash('ripemd160',$date),0,12);
$image_name = $newname . ($i > 0 ? "_($i)" : "") . "." . $imgExt;
$i++;
$path = $dir . $image_name;
} while(file_exists($path));
return $newname;
}
in get_unique_filename($name)
+add : sleep(1);
function get_unique_filename($name) {
sleep(1);
$imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION));
$date = new DateTime();
$date= $date->getTimestamp();
$newname ="bogen_". substr(hash('ripemd160',$date),0,12) .".".$imgExt;
return $newname;
}

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

Yii multiple row insert

I have a problem with this code.. When I post 3 images, the script inserts just last one in database.. How can i solve this?
Here's my code:
<?php
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
$valid_formats = array("jpg", "png", "gif", "bmp");
$max_file_size = 1024*2220; //100 kb
$path = "galerija/"; // Upload directory
$count = 0;
$key = generateRandomString();
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to execute all files
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[] = "Slika $name je pre velika!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "Ekstenzija $name nije valjana!";
continue; // Skip invalid file formats
} else { // No error found! Move uploaded files
if (move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$key.$name)){
$model->naziv = $key.$name;
$model->save();
}
}
}
}
}
?>
I think I should probably put some code after } else { //No error found, but i don't know what :S
You need to create an instance each time like below:
$model=new ModelName();
$model->naziv = $key.$name;
$model->save();

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