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
Related
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.
I have 3 inputs :
1. application name
2. Background photo
3. logo photo
After I got help from #mith. The code is great. Images always go into correct folder. I adapt the code to change image's name after submit it into folder. But i don't know what wrong with this condition
$fieldname = ($key == 'image[]') ? 'image' : 'logo';
$filename = $applicationName . '_' . $fieldname . '.' .
pathinfo($upload["tmp_name"], PATHINFO_EXTENSION);
$filename always be logo. I don't know why the condition always false.
So, 2 images always named applicationName_logo. please help me find out.
HTML form :
<form action="yong.php" method="POST" enctype="multipart/form-data">
<h3>App name</h3>
<input type="text" id="applicationName" name="applicationName">
<h3>Background image</h3>
<input type="file" id="image" name="image[]" multiple="multiple" accept="image/*" />
<h3>Logo image</h3>
<input type="file" id="logo" name="logo[]" multiple="multiple" accept="image/*" />
<br>
<br>
<input type="submit">
</form>
PHP code :
<?php
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 5000*100; //100 kb
$path = "home_dir/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
$applicationName = $_POST['applicationName'];
$sql_field_list = ['applicationName'];
$sql_value_list = [$applicationName];
foreach ($_FILES['image']['name'] as $f => $name) {
if ($_FILES['image']['error'][$f] == 4) {
continue; // Skip file if any error found
echo "Skip file if any error found";
}
if ($_FILES['image']['error'][$f] == 0) {
if ($_FILES['image']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
echo "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
echo "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
$tmp_name = $upload["tmp_name"];
$parts = explode('/', $upload['tmp_name']);
$tmpName = array_pop($parts);
$fieldname = ($key == 'image[]') ? 'image' : 'logo';
$filename = $applicationName . '_' . $fieldname . '.' . pathinfo($upload["tmp_name"], PATHINFO_EXTENSION);
}
//if(move_uploaded_file($_FILES["image"]["tmp_name"][$f], $path.$filename.png))
if(move_uploaded_file($_FILES["image"]["tmp_name"][$f], $path.'applicationName_bg/'.$filename.png))
$count++; // Number of successfully uploaded file
$message[] = "$name is uploaded";
echo "$filename is uploaded";
}
}
foreach ($_FILES['logo']['name'] as $f => $name) {
if ($_FILES['logo']['error'][$f] == 4) {
continue; // Skip file if any error found
echo "Skip file if any error found";
}
if ($_FILES['logo']['error'][$f] == 0) {
if ($_FILES['logo']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
echo "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
echo "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
$tmp_name = $upload["tmp_name"];
$parts = explode('/', $upload['tmp_name']);
$tmpName = array_pop($parts);
$fieldname = ($key == 'image[]') ? 'image' : 'logo';
$filename = $applicationName . '_' . $fieldname . '.' . pathinfo($upload["tmp_name"], PATHINFO_EXTENSION);
}
//if(move_uploaded_file($_FILES["logo"]["tmp_name"][$f], $path.$filename.png))
if(move_uploaded_file($_FILES["logo"]["tmp_name"][$f], $path.'applicationName_logo/'.$filename.png))
$count++; // Number of successfully uploaded file
$message[] = "$name is uploaded";
echo "$filename is uploaded";
}
}
}
Try the following code to save logo and image files separately:
HTML:
<form action="yong.php" method="POST" enctype="multipart/form-data">
<h3>App name</h3>
<input type="text" id="applicationName" name="applicationName">
<h3>Background image</h3>
<input type="file" id="image" name="image[]" multiple="multiple" accept="image/*" />
<h3>Logo image</h3>
<input type="file" id="logo" name="logo[]" multiple="multiple" accept="image/*" />
<br>
<br>
<input type="submit">
</form>
PHP
<?php
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 5000*100; //100 kb
$path = "home_dir/"; // Upload directory
$count = 0;
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
// Loop $_FILES to exeicute all files
foreach ($_FILES['image']['name'] as $f => $name) {
if ($_FILES['image']['error'][$f] == 4) {
continue; // Skip file if any error found
echo "Skip file if any error found";
}
if ($_FILES['image']['error'][$f] == 0) {
if ($_FILES['image']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
echo "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
echo "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["image"]["tmp_name"][$f], $path.'applicationName_bg/'.$name))
$count++; // Number of successfully uploaded file
$message[] = "$name is uploaded";
echo "$name is uploaded";
}
}
}
foreach ($_FILES['logo']['name'] as $f => $name) {
if ($_FILES['logo']['error'][$f] == 4) {
continue; // Skip file if any error found
echo "Skip file if any error found";
}
if ($_FILES['logo']['error'][$f] == 0) {
if ($_FILES['logo']['size'][$f] > $max_file_size) {
$message[] = "$name is too large!.";
echo "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
echo "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["logo"]["tmp_name"][$f], $path.'applicationName_logo/'.$name))
$count++; // Number of successfully uploaded file
$message[] = "$name is uploaded";
echo "$name is uploaded";
}
}
}
}
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.
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();
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,)