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";
}
}
}
}
Related
Currently using this code for the upload (but happy to use any if suggested)..
<form style="margin-bottom:2px;" method="post" enctype="multipart/form-data" name="formUploadFile">
<label>Select CSV file to upload:</label>
<input type="file" name="files[]" multiple="multiple" /> <input type="submit" value="Upload CSV" name="btnSubmit"/>
</form>
<?php
if(isset($_POST["btnSubmit"]))
{
$errors = array();
$uploadedFiles = array();
$extension = array("csv");
$bytes = 1024;
$KB = 1024;
$totalBytes = $bytes * $KB;
$UploadFolder = "tmp_csv_store";
$counter = 0;
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name){
$temp = $_FILES["files"]["tmp_name"][$key];
$name = $_FILES["files"]["name"][$key];
if(empty($temp))
{
break;
}
$counter++;
$UploadOk = true;
if($_FILES["files"]["size"][$key] > $totalBytes)
{
$UploadOk = false;
array_push($errors, $name." file size is larger than the 1 MB.");
}
$ext = pathinfo($name, PATHINFO_EXTENSION);
if(in_array($ext, $extension) == false){
$UploadOk = false;
array_push($errors, $name." invalid file type.");
}
if(file_exists($UploadFolder."/".$name) == true){
$UploadOk = false;
array_push($errors, $name." file already exists.");
}
if($UploadOk == true){
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
}
if($counter>0){
if(count($errors)>0)
{
echo "<b>Errors:</b>";
foreach($errors as $error)
{
echo " ".$error.",";
}
echo "<br/>";
}
if(count($uploadedFiles)>0){
echo "<b>Uploaded:</b>";
echo "=";
foreach($uploadedFiles as $fileName)
{
echo " ".$fileName.",";
}
echo "<br/>";
echo "<big><big>".count($uploadedFiles)." file has been successfully uploaded.</big></big>";
}
}
else{
echo "ERROR: Please press the browse button and select a CSV file to upload.";
}
}
?>
And would like to modify it so that it renames the uploaded file from "any-file-name.csv" to "foobar.csv" before it uploads the file and it should also overwrite the file if it already exists.
As a bonus the code currently allows for multi-file upload but I really only need it for a single file each time so it could also possibly be shortened a bit if changed to only allow a single file.
Thanks in advance :-)
To add your custom name:
if($UploadOk == true){
$name = "foobar.csv";
move_uploaded_file($temp,$UploadFolder."/".$name);
array_push($uploadedFiles, $name);
}
For single file, remove multiple="multiple":
<input type="file" name="files[]" />
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
What I am trying to put images where my folder is generate from "$tablename", but fail to bring the image there. How do I store the uploaded files ?
I like to upload images from my form.
<input type="file" id="file" name="files" multiple />
No matter which of those upload techniques I use is not good to use, to save the file to a specific location on the server.
If you have an idea how to do this problem please.
here is the mkdir code. The code is works fine.
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die("" . mysql_error() . "" . $qShowStatus);
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string) ("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If (!file_exists($year)) {
$createsyear = mkdir("$year", 0777);
} else {
If (!file_exists("$year/$month")) {
$createsmonth = mkdir("$year/$month", 0777);
} else {
If (!file_exists("$year/$month/$day")) {
$createsday = mkdir("$year/$month/$day", 0777);
} else {
If (!file_exists($year / $month / $day / $tablename)) {
$createsday = mkdir("$year/$month/$day/$tablename", 0777);
} else {
//dada
}
}
}
}
?>
Thank You.
Here I give basic example for file upload.
in HTML
<form action="phpfilename.php" method="post" enctype="multipart/form-data" >
<input type="file" name="files" />
<input type="submit" name="submit" />
</form>
In PHP
<?php
if(isset($_POST['submit']))
{
$path = $_FILES["files"]["name"];
$target = "$year/$month/$day/$tablename/$path"; //this is your path where image need to be saved
move_uploaded_file($_FILES["files"]["tmp_name"], $target);
}
?>
I fix the problem
<?php
$tablename = "fisa";
$next_increment = 0;
$qShowStatus = "SHOW TABLE STATUS LIKE '$tablename'";
$qShowStatusResult = mysql_query($qShowStatus) or die ( "" . mysql_error() . "" . $qShowStatus );
$row = mysql_fetch_assoc($qShowStatusResult);
$next_increment = $row['Auto_increment'];
echo "$next_increment";
$tablename = (string)("$next_increment");
$year = date("Y");
$month = date("m");
$day = date("d");
If(!file_exists($year)){
$createsyear = mkdir("$year", 0777);
}
else
{
If(!file_exists("$year/$month")){
$createsmonth = mkdir("$year/$month", 0777);
}
else
{
If(!file_exists("$year/$month/$day")){
$createsday = mkdir("$year/$month/$day", 0777);
}
else
{
If(!file_exists($year/$month/$day/$tablename)){
$createsday = mkdir("$year/$month/$day/$tablename/", 0777);
$valid_formats = array("jpg", "png", "gif", "zip", "bmp");
$max_file_size = 1024*100; //100 kb
$target = "$year/$month/$day/$tablename/";
$count = 0;
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[] = "$name is too large!.";
continue; // Skip large files
}
elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
$message[] = "$name is not a valid format";
continue; // Skip invalid file formats
}
else{ // No error found! Move uploaded files
if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $target.$name)) {
$count++; // Number of successfully uploaded files
}
}
}
}
}
}
else
{
}
}
}
}
?>
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.
in my form I'm trying to upload multiple or single file using php. So my html table is look like this :
<tr>
<td width="142"><b>Docs</b>
<td width="142"><input type="file" name="files[]" id="project_docs1" class="docfile" /></td>
<td width="142"><input type="file" name="files[]" id="project_docs2" class="docfile" /></td>
<td width="142"><input type="file" name="files[]" id="project_docs3" class="docfile" /></td>
</td>
Now when I upload only one file it's showing me error message like : Invalid Format but it's should be accept one file. it's not require to must be upload all 3 files. Can you tell me why it's showing this error message called Invalid Format ? If upload all 3 files then it's working fine.
and when I press the upload button without upload any file it's showing me value 1 for $noOfUpload variable. why ?
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "project_docs"; // Upload directory
$error = array(); // load error message
$files_name = array(); // get uploaded file name
foreach ($_FILES['files']['name'] as $key => $name) {
$size = $_FILES['files']['size'][$key]. "<br>";
$noOfUpload = count($name);
if($noOfUpload <= 0){
$error[] = "Upload your document/s<br>";
}elseif(!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){
$error[] = "invalid file formate : $name<br>";
}
//$name = md5(uniqid()) . '-' . htmlspecialchars_decode($name);
$files_name[] = "$name";
}
if(!empty($error)){
foreach ($error as $e) {
echo "<div class='error'>$e</div>";
}
}else{
foreach ($files_name as $fn) {
echo "$fn<br>";
}
}
You help is more appreciate. :)
Try this
if (isset($_FILES))
{
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
for ($i = 0; $i < count($_FILES['files']['name']); $i++)
{
if (in_array(pathinfo($FILES['files']['name'][$i], PATHINFO_EXTENSION), $valid_formats))
{
$tmp_path = $_FILES['files']['tmp_name'][$i];
if ($tmp_path != "")
{
if (move_uploaded_file($tmp_path, $new_path))
{
//Handle other code here
}
else
{
$error[] = ""; //your error handling
}
}
else
{
$error[] = ""; //your error handling
}
}
else
{
$error[] = "invalid file formate : $name<br>";
}
}
}
Your code is run for whole array either it's blank or not. First, count your array then run your code upto that count.
<tr>
<td width="142"><b>Docs</b>
<td width="142"><input type="file" name="files[]" id="project_docs1" class="docfile" /></td>
</tr>
PHP Code:
$valid_formats = array("jpg", "png", "gif", "txt", "bmp");
$max_file_size = 1024*100; //100 kb
$path = "project_docs"; // Upload directory
$error = array(); // load error message
$files_name = array(); // get uploaded file name
foreach ($_FILES['files']['name'] as $key => $name) {
$size = $_FILES['files']['size'][$key]. "<br>";
$noOfUpload = count($name);
if($noOfUpload <= 0){
$error[] = "Upload your document/s<br>";
}elseif(!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)){
$error[] = "invalid file format : $name<br>";
}
//$name = md5(uniqid()) . '-' . htmlspecialchars_decode($name);
$files_name[] = "$name";
}
if(!empty($error)){
foreach ($error as $e) {
echo "<div class='error'>$e</div>";
}
}else{
foreach ($files_name as $fn) {
echo "$fn<br>";
}
}