I have this add button to select the file inside a upload form field:
$("#add_attachment").on('click', function() {
var no_attachment = parseInt($('#noa').val()) + 1;
$('#noa').val(no_attachment);
$("#tbody_attachment").append("<tr><td bgcolor='#d9d9d9' class='td-data_1'><div class='col-xs-12'><input type='number' class='form-control' name='noa_save[]' id='noa_save' placeholder='No' value='" + no_attachment + "' /></div></td><td bgcolor='#d9d9d9' class='td-data_1'><div class='col-xs-12'><input type='file' class='form-control' name='attachment_save[]' id='attachment_save' placeholder='Attachment'/></div></td><td bgcolor='#d9d9d9' class='td-data_1'><div align='center'><input type='button' name='attachment' id='remove_attachment' value='Remove' style='font-size:16px; width: 98%;'/></div></td></tr>");
});
$("#tbody_attachment").on('click', '#remove_attachment', function() {
$(this).closest('tr').remove();
var no_attachment = $('#noa').val();
$('#noa').val(parseInt(no_attachment) - 1);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="save_sop.php" enctype="multipart/form-data">
<div align="center">
<table class="table" id="t_attachment">
<thead>
<tr>
<th width="10%" bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>No</strong></font>
</div>
</th>
<th bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>Attachment</strong></font>
</div>
</th>
<th width="10%" bgcolor="#8eb4e3" class="td-data_1">
<div align="center">
<font size="3dp"><strong>Button</strong></font>
</div>
</th>
</tr>
</thead>
<tbody id="tbody_attachment">
<tr>
<td bgcolor="#d9d9d9" class="td-data_1">
<div class="col-xs-12">
<input type="number" class="form-control" name="noa" id="noa" placeholder="No" value="0" />
</div>
</td>
<td bgcolor="#d9d9d9" class="td-data_1">
<div class="col-xs-12">
<div align="justify">
<font size="3dp"><strong>Choose file after clicking Add button</strong></font>
</div>
</div>
</td>
<td bgcolor="#d9d9d9" class="td-data_1">
<div align="center"><input type="button" name="add_attachment" id="add_attachment" value="Add" style="font-size:16px; width: 98%;" /></div>
</td>
</tr>
</tbody>
</table>
</div>
</form>
You can run the code above to give an idea how's the form works.
And in the save_sop.php file, I have to upload the files that submitted from the previous form and also get the file name to be stored to MySQL database as a JSON array value.
Here's the code so far in the save_sop.php file:
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
include 'con.php';
$total_attachment = mysqli_real_escape_string($con, $_POST['noa']);
$attachment["no"] = $_POST['noa_save'];
foreach($_FILES['attachment_save']['name'] as $filename) {
$imgFile = $filename;
$tmp_dir = $_FILES['attachment_save']['tmp_name'];
$imgSize = $_FILES['attachment_save']['size'];
$folder = 'sop/attachment/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
// valid image extensions
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
// rename uploading image
$img = rand(1000, 1000000) . "." . $imgExt; //generate the random file name
// allow valid image file formats
if (in_array($imgExt, $valid_extensions)) {
// Check file size '50MB'
if ($imgSize < 5000000) {
//move_uploaded_file($tmp_dir, $folder . $img);
} else {
$errMSG = "Sorry, your file is too large.";
}
} else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
echo "Generated File Name: " . $img . "<hr />";
$attachment['attachment'] = $img;
}
$attachment_save = json_encode($attachment, true);
echo $attachment_save;
}
?>
When the echo $attachment_save called, the result I get is below.
Generated File Name: 430609.jpg
<hr />
Generated File Name: 575033.jpg
<hr />
{"no":["1","2"],"attachment":"575033.jpg"}
Inside foreach loop, I called echo "Generated File Name:" . $img; I do get the result as expected, but in the attachment array, I only get one filename instead of two.
I need to get two file name value inside the attachment['attachment'] array. The result expected should be:
{"no":["1","2"],"attachment":["430609.jpg", "575033.jpg"]}
Can anybody help me with this? thanks in advance.
Regards.
the answer lies on
$attachment. Instead of $attachment['attachment'] = $img;
it should be
$attachment['attachment'][] = $img;
and it's working perfectly.
Related
file uploading then am choose
only notice but my file path is automatic load am not want to load my path how it possible
and then am fetching my database show my file path only am not want show my code path so am not choose any file am choose only NOTICE text how it possible enter link description here
my code
-------
t>
<?php
$alert = ( isset($_REQUEST['alert']) ) ? trim($_REQUEST['alert']):'';
$im=$_FILES['image'];
$rnd = rand(1,1000);
$path = "../home_image/";
$im_name = $rnd."_".$im['name'];
$fullpath =$path. $im_name;
$value_fullpath = empty($fullpath) ? null : ($fullpath);
if($im['error']==0)
{
if($im['type'] == "image/jpeg" or $im['type'] == "image/gif" or $im['type'] == "image/png")
{
copy($im['tmp_name'],$fullpath);
}
}
$imp=$_FILES['imagep'];
$rnd = rand(1,1000);
$path = "../home_image/";
$im_name = $rnd."_".$imp['name'];
$fullpathp=$path.$im_name;
$value_fullpath = empty($fullpath) ? null : ($fullpath);
if($im['error']==0)
{
if($im['type'] == "image/jpeg" or $im['type'] == "image/gif" or $im['type'] == "image/png")
{
copy($imp['tmp_name'],$fullpathp);
}
}
if(isset($_REQUEST['submit']))
{
echo $sql="INSERT INTO `home_page`(`slider_image`,`notice`,`prtofolio`)
VALUES ('$value_fullpath','$alert','$fullpathp')";
echo $query=mysqli_query($conDB,$sql) or die (mysqli_error());
header('location:homepage_show.php');
}
?>
<table width="687" id="rounded-corner" summary="2007 Major IT Companies' Profit" >
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="myForm" method="post" enctype="multipart/form-data" onsubmit="return(validate());">
<tr>
<td> slect slider image</td>
<td><input type="file" name="image"cols="60" rows="2"></textarea></td>
<tr>
<tr>
<td> notice for home page </td>
<td><input type="text" name="alert"cols="60" rows="2"></textarea></td>
<tr>
<tr>
<td> protofolio </td>
<td><input type="file" name="imagep"cols="60" rows="2"></textarea></td>
<tr>
<tr>
<td> </td>
<td></td>
<tr>
<td><input type="submit" name="submit" value="submit"/></td><td></td>
</tr>
</table>
<div class=""> <span class="disabled"> </span> </div>
</div>
<!-- end of right content-->
</div>
<!--end of center content -->
enter code here
I'm new here.
I need to upload Multiple mp3 files to a directory and store them in the 'audio' table in mysql.
I'm using this script but it works only with one file, it's annoying to do one track each time. That's why I need a multiple upload script.
I wish to only write the title of each track like this:
php: file1.mp3 [0] file2.mp3 [1] file3.mp3 [2]
html form: File 1 title: .... File 2 title: .... File 3 title: ....
insert to 'audio'
Sorry for my bad English. i hope you know what I mean
<?php if(isset($_POST['kkupload'])){
$filename = $_FILES['foto']['name'];
$extensie = substr($filename, -3);
$map = "/mounted-storage/home150/sub007/sc80538-VHHY//audio/files/";
$file = $_FILES['foto'];
$breedte = $_FILES['foto'];
$max_bytes = 100000000000;
if(strtolower($extensie) != "mp3" && strtolower($extensie) != "jpg" && strtolower($extensie) != "jpeg" && strtolower($extensie) != "png" && strtolower($extensie) != "bmp")
{
echo "Je kan alleen .gif, .jpg .jpeg en .png bestanden uploaden!";
}
elseif($_FILES['foto']['size'] > $max_bytes) { echo("Het bestand is groter dan ".$max_bytes." bytes!"); }
else {
$length = strlen($filename);
$name = "pict";
$name = substr($filename, 0, $length - 4);
$i = "1";
$tempname = $name;
$picName = $_FILES['foto']['name'];
$titel = htmlspecialchars($_POST['titel']);
$bericht = $_POST['bericht'];
$url = htmlspecialchars($_POST['pica']);
$youtube = $_POST['youtube'];
$nr = rand(0,99999999999);
if(file_exists($_FILES['foto']['name']))
{
$picName = $nr. $_FILES['foto']['name'];
if(file_exists($picName))
{
$picName = $nr. $_FILES['foto']['name'];
}
}
move_uploaded_file($_FILES['foto']['tmp_name'], $map.$_FILES['foto']['name']."") or die("Fout met uploaden plaatje");
mysql_query("INSERT INTO `audio` (titel, url, categorie) values ('".$titel."', '/audio/files/".$picName."','".$bericht."')");
echo "je hebt succesvol nieuws geupload!"; }}?>
<form action="?pagina=addnieuws" method="post" enctype="multipart/form-data" name="form1" id="form1">
<table width="100%" border="0" cellpadding="2" cellspacing="2" id="form1">
<tr>
<td width="77"><b> <font size="2" face="Verdana">Tite track:</font></b>
</div></td>
<td><font size="2">
<input name="titel" type="text" id="Titel" size="63" />
</font></td>
</tr>
<tr>
<td width="77"><b> <font size="2" face="Verdana">Plaatje:</font></b>
</div></td>
<td><font size="2">
<input type="file" name="foto" size="52" />
</font><b><font size="1" face="Verdana"> <br />
MP3</font></b></td>
</tr>
<tr>
<td valign="top" width="77"><b> <font size="2" face="Verdana">Artiest:</font></b>
</div></td>
<td>
<script type="text/javascript">
bkLib.onDomLoaded(function() {
new nicEditor({fullPanel : true}).panelInstance('area2');
});
</script>
<select name="bericht">
<?php
$query = mysql_query("SELECT * FROM artiesten ORDER BY naam ASC");
while ($array = mysql_fetch_assoc($query)){
echo "<option value=\"". $array['naam'] ."\">". $array['naam']. "</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td width="77" colspan="2"><font size="2">
<input type="submit" name="kkupload" value="Upload" />
</font></td>
</tr>
</table>
</form>
The code below is a example to give you a idea of how to upload more then one file at a time but to a folder
for($i=0; $i < count($_FILES['filesToUpload']['name']); $i++){
$target_dir = "../uploads/";
$target_file = $target_dir . basename($_FILES['filesToUpload']['name'][$i]);
$uploadOk = 1;
Insert your security check code here between the above and below code to see if the file really is a mp3 and etc.
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded. ";
} else {
if (move_uploaded_file($_FILES["filesToUpload"]["tmp_name"][$i], $target_file)) {
echo "The file ". basename( $_FILES["filesToUpload"]["name"][$i]). " has been uploaded. ";
} else {
echo "Sorry, there was an error uploading your file. ";
}
}
}
Also, depending on the type of database you're using, probably best to save the files in a folder and not directly inside the database so that you're not over-bloating the database.. You instead would need to save its file path to the database and then open from the file path. Though that's just giving you a suggestion.
Lastly, that's just the PHP side of it, not sure what you'll need for the SQL part. Though I guess that's fine since you mainly asked for how to do multiple file uploads.
I'm relatively new to PHP and need some help checking to see 1. If an image has been uploaded for submission and complete one set of submission ELSE IF an image has not been uploaded, submit a different set of sql information.
I've previously tried isset(), is_uploaded_file(), and file_exists(), and cannot seem to get anything to send.
HTML FORM
<form method="POST" action="php/editInv.php" enctype="multipart/form-data" id="editInv">
<table>
<tbody>
<?php
$productId = $_GET['productId'];
require ('php/dbcon.php');
$con=mysqli_connect(HOST,USER,PASS,DB);
$sqlId = "SELECT * FROM products WHERE productId='".$productId."'";
$sqlIdResult = mysqli_query($con,$sqlId);
while($rowId=mysqli_fetch_array($sqlIdResult)) {
?>
<tr>
<td>
<label for="productName">Product Name: </label>
</td>
<td>
<input name="productName" id="productName" type="text" value="<?php echo $rowId['productName']; ?>"/>
<input name="prodId" id="prodId" type="hidden" value="<?php echo $rowId['productId']; ?>" />
</td>
<td>
<label for="productDesc">Product Description: </label>
</td>
<td rowspan="4">
<textarea name="productDesc" id="productDesc" cols="55" rows="10"><?php echo $rowId['productDesc']; ?></textarea>
</td>
</tr>
<tr>
<td>
<label for="gender">Gender: </label>
</td>
<td>
<select name="gender" id="gender">
<option id="1" value="1">Male</option>
<option id="2" value="2">Female</option>
<option id="3" value="3">Unisex</option>
</select>
<input type="hidden" value="<?php echo $rowId['genderId']; ?>" id="genderHid"/>
<script>
var gender=$('#genderHid').val();
var selected=$('#gender').find('#'+gender);
$(selected).attr('selected','selected');
</script>
</td>
</tr>
<tr>
<td>
<label for="inventory">Inventory: </label>
</td>
<td>
<input type="number" name="inventory" id="inventory" value="<?php echo $rowId['inventory']; ?>"/>
</td>
</tr>
<tr>
<td>
<label for="price">Price: </label>
</td>
<td>
$<input type="text" name="price" id="price" value="<?php echo $rowId['price']; ?>" />
</td>
</tr>
<tr>
<td>
<label for="productImage">Upload Image: </label>
</td>
<td>
<input type="file" name="productImage" id="productImage" />
</td>
<td colspan="2">
<div id="progress" style="width:100%;">
<div id="bar" style="height:50px;background-color:blue;width:0%;">
</div>
<p id="percent"></p>
</div>
</td>
</tr>
<tr>
<td colspan="2" rowspan="2">
<img id="prevImage" style="" src="<?php echo $rowId['productImage']; ?>" />
</td>
<td id="response">
</td>
<td>
<button type="submit" id="editInv">Edit Item</button>
</td>
</tr>
<tr>
</tr>
<?php
};
?>
</tbody>
</table>
</form>
AJAX
var options = {
beforeSubmit: function() {
// pre submit callback
$("#progress").show();
$("#percent").html("0%");
},
data: {
productName : $('#productName').val(),
productDesc : $('#productDesc').val(),
inventory : $('#inventory').val(),
price : $('#price').val(),
gender : $('#gender').val(),
image : $('#prevImage').attr('src'),
prodId : $('#prodId').val()
},
uploadProgress: function(event, position, total, percentComplete) {
//during submission
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function(msg) {
//post submit call back
$(".bar").css("width","100%");
$(".percent").html('100%');
$("#response").html(response.responseText);
},
complete: function(response) {
if(response.responseText=="Invalid File"){
} else {
$("#response").html(response.responseText);
//$("#addNew")[0].reset();
//$("#prevImage").attr('src','').hide();
$(".bar").css("width","0%");
$(".percent").html('0%');
}
},
error: function(response) {
alert(response.responseText);
}
};
$("#editInv").ajaxForm(options);
PHP
//If a file has been uploaded
if (!empty($_FILES["productImage"]["name"])) {
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/images/inventory/";
$target_file = $target_dir . basename($_FILES["productImage"]["name"]);
$fileName = str_replace(' ', '', $productName);
$target_file_insert = "/images/inventory/" . $fileName . ".jpg";
$targetFileUpload = $target_dir . $fileName . ".jpg";
$sql1 = "UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$targetFileUpload."' WHERE productId='".$prodId."'";
mysqli_query($con,$sql1);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["productImage"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "jpeg" && $imageFileType != "JPG" && $imageFileType != "JPEG") {
echo "Sorry, only JPG, and JPEG files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["productImage"]["tmp_name"], $targetFileUpload)) {
mysqli_close($con);
} else {
echo "Sorry, there was an error uploading your file.";
}
}
} else
//If a file has not been uploaded
/*if (empty($_FILES["productImage"]["name"])) */{
$sql2="UPDATE products SET productName='".$productName."', productDesc='".$productDesc."', inventory='".$inventory."', price='".$price."', genderId='".$gender."', productImage='".$image."' WHERE productId='".$prodId."'";
mysqli_query($con,$sql2);
}
The path you need to check is $targetFileUpload not $upload.
Once uploaded check:
if (!file_exists($targetFileUpload)){...}
Ok, it was actually being caused by two different issues, one in the PHP and one in the order in which the variables were called in the JavaScript. I had to call everything except for the generated image using jQuery at the top of the page as global variables, then put the jQuery AJAX at the bottom of the page with the form action call.
Apparently, using the jQuery to call the values of the fields at the bottom of the page caused them to send the information that the page populated with from the back end, while placing them at the top of the page causes them to relay the changed input data to the AJAX call.
Any explinations why this worked this way?
<script>
var productName = $('#productName').val();
var productDesc = $('#productDesc').val();
var inventory = $('#inventory').val();
var price = $('#price').val();
var gender = $('#gender').val();
var prodId = $('#prodId').val();
</script>
//All your HTML Content
<script>
var options = {
beforeSubmit: function() {
// pre submit callback
$("#progress").show();
$("#percent").html("0%");
},
data: {
productName : productName,
productDesc : productDesc,
inventory : inventory,
price : price,
gender : gender,
image : $('#prevImage').attr('src'),
prodId : prodId
},
uploadProgress: function(event, position, total, percentComplete) {
//during submission
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function(msg) {
//post submit call back
$(".bar").css("width","100%");
$(".percent").html('100%');
$("#response").html(response.responseText);
},
complete: function(response) {
if(response.responseText=="Invalid File"){
} else {
$("#response").html(response.responseText);
//$("#addNew")[0].reset();
//$("#prevImage").attr('src','').hide();
$(".bar").css("width","0%");
$(".percent").html('0%');
}
},
error: function(response) {
alert(response.responseText);
}
};
$("#editInv").ajaxForm(options);
</script>
PHP if statement statement essentially looks like this:
if (!empty($_FILES["productImage"]["name"])) {
} else
//If a file has not been uploaded
if (empty($_FILES["productImage"]["name"])) {
}
Thank you #fred-ii- for the error catcher.
I want to add the ID number of the row to the uploaded file file name.
e.g. if the file name is stack.pdf before uploading, after uploading it should change to stack-ID#.pdf.
This is the PHP Codes that is use to upload
$sp=mysqli_connect("localhost","root","","ara");
if($sp->connect_errno){
echo "Error <br/>".$sp->error;
}
$path="pdf/";
if(isset($_POST['upload']))
{
$path=$path.$_FILES['file_upload']['name'];
if(move_uploaded_file($_FILES['file_upload']['tmp_name'],$path))
{
echo " ".basename($_FILES['file_upload']['name'])." has been uploaded<br/>";
echo '<img src="gallery/'.$_FILES['file_upload']['name'].'" width="48" height="48"/>';
$img=$_FILES['file_upload']['name'];
$query="insert into library (path,CreatedTime) values('$img',now())";
if($sp->query($query)){
echo "<br/>Inserted to DB also";
}else{
echo "Error <br/>".$sp->error;
}
}
else
{
echo "There is an error,please retry or ckeck path";
}
}
And this is the form
<form action="accept-file.php" method="post" enctype="multipart/form-data">
<table width="384" border="1" align="center">
<tr>
<td width="108">Select File</td>
<td width="260"><label>
<input type="file" name="file_upload">
</label></td>
</tr>
<tr>
<td><label>
<input type="submit" name="upload" value="Upload File">
</label></td>
<td> </td>
</tr>
</table>
</form>
I will really appreciate your help. Thanks.
Try this:
$uploadFileName = $_FILES['file_upload']['name'];
//get extention of upload file
$attachment_ext = explode('.', $uploadFileName);
$ext_pt = $attachment_ext[1];
//Give a new name for the file
$newName = '123'.$uploadFileName.".".$ext_pt;
$path = "YOURPATHHERE/";
$save_attchment = $path.$newName ; //setting the path
move_uploaded_file($_FILES['file_upload']['tmp_name'], $save_attchment);
Okay, this is what I got so far, I'm able to upload one image and display it in a div, but I just cant seem to figure out how to do the same for loading multiple images. As in upload multiple images and display all uploaded images on screen. Any help is appreciated, thanks in advance.
Also: I kinda think I have to set a variable for
$_FILES['image']['name'][0]
$_FILES['image']['name'][1]
etc
and do a forloop to print it out? Correct me if I am wrong?
<?php
// prevent timezone warnings
date_default_timezone_set('America/New_York');
// set the upload location
$UPLOADDIR = "tmp";
// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
// loop through the uploaded files
foreach ($_FILES as $key => $value){
$image_tmp = $value['tmp_name'];
$image = $value['name'];
$image_file = "{$UPLOADDIR}{$image}";
// move the file to the permanent location
if(move_uploaded_file($image_tmp,$image_file)){
echo <<<HEREDOC
<div style="float:left;margin-right:10px">
<img src="{$image_file}" alt="file not found" /></br>
</div>
HEREDOC;
}
else{
echo "<h1>image file upload failed, image too big after compression</h1>";
}
}
}
else{
?>
<form name='newad' method='post' enctype='multipart/form-data' action=''>
<table>
<tr>
<td><input type='file' name='image'></td>
</tr>
<tr>
<td><input name='Submit' type='submit' value='Upload image'></td>
</tr>
</table>
</form>
<?php
}
?>
I' am not sure which CMS/Framework this is but If you change this line
From
<input type='file' name='image'>
To
<input type='file' name='image[]' multiple>
Hope this helps you out.
How are multiple files, you must have two loops. Put a foreach inside a for.
I believe that is what you want. Make sure the tmp folder has write permission.
<?php
// prevent timezone warnings
date_default_timezone_set('America/New_York');
// set the upload location
$UPLOADDIR = "tmp";
// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
$num_files = count($_FILES['image']['tmp_name']);
for($x = 0; $x < $num_files; $x++){
$image = $_FILES['image']['name'][$x];
$image_file = $UPLOADDIR."/". $image;
if(!is_uploaded_file($_FILES['image']['tmp_name'][$x])){
$messages[] = '<h1>'.$image.' image file upload failed, image too big after compression</h1>."<br>"';
}
if (move_uploaded_file($_FILES["image"]["tmp_name"][$x],$image_file)){
echo '
<div style="float:left;margin-right:10px">
<img src="'.$image_file.'" alt="file" /></br>
</div>';
} else{
echo "<h1>image file upload failed, image too big after compression</h1>";
}
}
}else {
?>
<form name='newad' method='post' enctype='multipart/form-data' action=''>
<table>
<tr>
<td><input type='file' name='image[]'></td>
</tr>
<tr>
<td><input type='file' name='image[]'></td>
</tr>
<tr>
<td><input name='Submit' type='submit' value='Upload image'></td>
</tr>
</table>
</form>
<?php
}
?>