Wordpress custom form with fileupload - php

I have a custom wordpress php page where I have a form which update a database with the posted data fra input fields.
Now I wan't to be able to upload at file/picture in a specifik folder, and store the link to the file/picture in my database. I need help to implement that, because I do not understand how to achieve that at all even though I have tried to read a lot about it.
This is my code:
If($_POST['Submit'])
{
global $wpdb;
$medlemsnr=$_POST['medlemsnr'];
$navn=$_POST['navn'];
$baadnavn=$_POST['baadnavn'];
$art=$_POST['art'];
$vaegt=$_POST['vaegt'];
$billede=$_POST['billede'];
if($wpdb->insert(
'ct_storfanger_indberetninger',
array(
'Medlemsnr' => $medlemsnr,
'navn' => $navn,
'bådnavn' =>$baadnavn,
'art' =>$art,
'vægt' =>$vaegt,
'billede' =>$billede
)
) == false) wp_die('Der var en fejl i indsendelsen. Kontakt venligst webmaster'); else echo 'Tak for din indsendelse. Den vil fremgå af listen så snart den er godkendt af juryen!<p />';
?>
<?php
}
else // else we didn't submit the form, so display the form
{
?>
<form action="" method="post" id="form">
<table style="border:none;">
<tr>
<td style="border:none;width:25%">Medlemsnr</td>
<td style="border:none;"><input name="medlemsnr" type="text" value="" /></td>
</tr>
<tr>
<td style="border:none;">Navn</td>
<td style="border:none;"><input name="navn" type="text" value="" /></td>
</tr>
<tr>
<td style="border:none;">Bådnavn</td>
<td style="border:none;"><input name="baadnavn" type="text" value="" /></td>
</tr>
<tr>
<td style="border:none;">Art</td>
<td style="border:none;">
<?php
global $wpdb;
$retrieve_data = $wpdb->get_results( "SELECT Art FROM ct_storfanger_arter");
?>
<SELECT NAME="art"><option value=""></option>
<?php
foreach ($retrieve_data as $retrieved_data){
echo "<option value='" . $retrieved_data->Art . "'>" . $retrieved_data->Art . "</option>";
}
?>
</SELECT></td>
</tr>
<tr>
<td style="border:none;">Vægt i gram</td>
<td style="border:none;"><input name="vaegt" type="text" value="" /> gram</td>
</tr>
<tr>
<td style="border:none;">Billede</td>
<td style="border:none;"><input name="billede" type="file" value="" /></td>
</tr>
</table>
<table style="border:none;">
<tr>
<td style="border:none;"><input type="submit" name="Submit" id="formsubmit" value="Indsend" /></form></td>
</tr>
</table>
</form>
<?php
} // end else no post['submit']
?>

You can use this code as a reference, heres the HTML :
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
and this would go on the PHP side:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$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["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
Simply try this on a separated folder until you understand the code and then you will be able to implement it into your wordpress modification
And if you are loading wp_init on that module you can also use the wordpress function wp_handle_upload :
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
$uploadedfile = $_FILES['file'];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile && ! isset( $movefile['error'] ) ) {
echo "File is valid, and was successfully uploaded.\n";
var_dump( $movefile );
} else {
/**
* Error generated by _wp_handle_upload()
* #see _wp_handle_upload() in wp-admin/includes/file.php
*/
echo $movefile['error'];
}
here's the function reference : wp_handle_upload

Related

file upload (php) two warnings

I am working on small page where I update MySQL records via PHP page, all the functionality is well working but I constantly get warnings for an Undefined array.
Here are the warnings:
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 11
Warning: Undefined array key "file" in C:\xampp\htdocs\crud\edit.php on line 22
Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\crud\edit.php on line 22
I was looking at many topics like this but did not manage to fix my own one...
Here is the code of edit.php
include 'db.php';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
I have also a pcs of HTML for that in <form:
<form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
I have a feeling that I missed something very simple.
----- update -------
here is my full code: in one file I put php with the html
// include database connection file
include_once("config.php");
//тук стартирам за фаил ъплоад
// Include the database configuration file
include 'db.php';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
}
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// край на фаил ъплоад
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// update user data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
// Redirect to homepage to display updated user in list
header("Location: index.php");
}
?>
<?php
// Display selected user data based on id
// Getting id from url
$id = $_GET['id'];
// Fetech user data based on id
$result = mysqli_query($mysqli, "SELECT * FROM tools WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$toolnr = $user_data['toolnr'];
$status = $user_data['status'];
$toolname = $user_data['toolname'];
$serial = $user_data['serial'];
$usedat = $user_data['usedat'];
$owner = $user_data['owner'];
$calibrated = $user_data['calibrated'];
$nextcalibration = $user_data['nextcalibration'];
$vendors = $user_data['vendors'];
$momenten = $user_data['file_name'];
}
?>
<html>
<head>
<title>Актуализация</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
<center> <img src="logo-ottobock.png" alt="OttobockLogo"> </center>
<hr> <br>
<center> <img src="notification.png" alt="Warning"> </center>
<center> <i> <p style="color:red;"> В момента работите с най-високо ниво на достъп, моля бъдете внимателни. <br> Всички направени от Вас промени са необратими. <p> </i> </center>
</head>
<body>
<br/><br/>
<center> <form name="update_user" method="post" action="edit.php" enctype="multipart/form-data" >
<table border="0" class="table table-striped" >
<tr>
<td>Номер</td>
<td><input type="text" name="toolnr" class="form-control" value=<?php echo $toolnr;?>></td>
</tr>
<tr>
<td>Статус</td>
<td>
<select name="status" id="status" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT status FROM tools WHERE id=$id UNION SELECT currentstatus FROM statuses");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['status'] ."'>" .$data['status'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Найменование</td>
<td><input type="text" name="toolname" class="form-control" value="<?php echo $toolname;?>"></td>
</tr> <br>
<tr>
<td>Сериен номер</td>
<td><input type="text" name="serial" class="form-control" value="<?php echo $serial;?>"></td>
</tr>
<tr>
<td>Локация</td>
<td>
<select name="usedat" id="usedat" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT usedat FROM tools WHERE id=$id UNION SELECT locations From whereused");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['usedat'] ."'>" .$data['usedat'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Отговорник</td>
<td>
<select name="owner" id="owner" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT owner FROM tools WHERE id=$id UNION SELECT responsiblepersons From responsibles");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['owner'] ."'>" .$data['owner'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td>Калибриран на:</td>
<td><input type="date" name="calibrated" class="form-control" value=<?php echo $calibrated;?>></td>
</tr>
<tr>
<td>Следваща</td>
<td><input type="date" name="nextcalibration" class="form-control" value=<?php echo $nextcalibration;?>></td>
</tr>
<tr>
<td>Сертификат</td>
<td><?php echo "<a target = '_blank' href='http://10.171.2.15/crud/uploads/$momenten'> Свали </a>";?></td>
</tr>
<tr>
<td>Нов сертификат:</td>
<td><input type="file" name="file" ></td>
</tr>
<tr>
<td>Калибрира се при</td>
<td>
<select name="vendors" id="vendors" class="form-control" required>
<?php
include "dbConn.php";
$records = mysqli_query($db, "SELECT vendors FROM tools WHERE id=$id UNION SELECT vendoren FROM vendors");
while($data = mysqli_fetch_array($records))
{
echo "<option value='". $data['vendors'] ."'>" .$data['vendors'] ."</option>";
}
?> </select>
</td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" class="btn btn-success" value="Запис">
<a href="index.php" class="btn btn-danger" >Отказ</a> </td>
</tr>
</table>
</form> </center>
</body>
Posting working code:
final-fixed code (only php part). The problem was that the part of the code responsible for file upload was out of the if statement
<?php
// include database connection file
include_once("config.php");
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$toolnr=$_POST['toolnr'];
$status=$_POST['status'];
$toolname=$_POST['toolname'];
$serial=$_POST['serial'];
$usedat=$_POST['usedat'];
$owner=$_POST['owner'];
$calibrated=$_POST['calibrated'];
$nextcalibration=$_POST['nextcalibration'];
$vendors=$_POST['vendors'];
// Include the database configuration file
include 'db.php';
$statusMsg = '';
// File upload path
$targetDir = "uploads/";
$fileName = basename($_FILES["file"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(isset($_POST["submit"]) && !empty($_FILES["file"]["name"])){
// Allow certain file formats
$allowTypes = array('jpg','png','jpeg','gif','pdf','doc','xlsx');
if(in_array($fileType, $allowTypes)){
}
}
// Upload file to server
if(move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)){
}
// update user data
$result = mysqli_query($mysqli, "UPDATE tools SET toolnr='$toolnr',status='$status',toolname='$toolname',serial='$serial',usedat='$usedat',owner='$owner',calibrated='$calibrated',nextcalibration='$nextcalibration', vendors='$vendors', file_name = '$fileName' WHERE id='$id'");
// Redirect to homepage to display updated user in list
header("Location: index.php");
}
?>

Multiple Upload File with Unusual Condition PHP

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.

Why unlink function will not delete old image when uploading image

I have to manually go into my folder every time I update an image. The image will update to a new image. However, when I update an image, the old image is not being deleted. I am using the PHP function unlink to delete the image but for some reason its not working. I have removed the at "#" sign from php unlink in the code. I have re-edited coded the code. I keep getting the following error:
Warning: unlink(picture/): Permission denied in C:\xampp\htdocs\upload_update\New_project\edit_image.php on line 24
I am trying to teach myself php, Thank you so much for your help.
This is the code:
<?php
include "connection.php";
$vid="";
$vname="";
$vprice="";
$vpicture="";
if(isset($_POST["button_edit"])){
$product_name = $_POST["product_name"];
$product_price = $_POST["product_price"];
$product_id = $_POST["product_id"];
$old_picture = $_POST['old_picture'];
if(!empty($_FILES["product_picture"]["name"])) {
$product_picture = $_FILES["product_picture"]["name"];
$qry = mysqli_query($con,"Update table_product Set product_name='$product_name', product_price='$product_price', product_picture='$product_picture' Where product_id='$product_id'");
$target_dir = "picture/";
$target_file = $target_dir . basename($_FILES["product_picture"]["name"]);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
move_uploaded_file($_FILES["product_picture"]["tmp_name"],$target_file);
if (isset($old_picture) && ($old_picture != $product_picture)) {
unlink("picture/" . $old_picture);
}
}
else{
$qry = "Update table_product Set product_name='$product_name', product_price='$product_price' Where product_id='$product_id'";
}
$qryUpdate = mysqli_query($con,$qry);
}
else if(isset($_GET["edit"])){
$qry = mysqli_query($con,"Select * From table_product Where product_id='".$_GET["edit"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["product_id"];
$vname=$row["product_name"];
$vprice=$row["product_price"];
$vpicture=$row["product_picture"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Product</title>
</head>
<body>
<form action='<?php echo $_SERVER["PHP_SELF"]; ?>' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>Product ID</td>
<td><input type="text" name="product_id" value="<?php echo $vid;?>"></td></tr>
<tr><td>Product Name</td>
<td><input type="text" name="product_name" value="<?php echo $vname;?>"></td></tr>
<tr><td>Product Price</td>
<td><input type="text" name="product_price" value="<?php echo $vprice;?>"></td></tr>
<input type="hidden" name="old_picture" value="<?php if (!empty($old_picture)) echo $old_picture; ?>" />
<tr><td>Product Picture</td>
<td><input type="file" name="product_picture" ></td></tr>
<?php if (!empty($old_picture)) {
echo '<img class="profile" src="picture/' . $old_picture . '" alt="image" style=width:150px;height:xpx;">';
} ?>
<tr><td colspan="2">
<input type="submit" name="button_add" value="Add">
<input type="submit" name="button_edit" value="Edit"></td></tr> </table>
</form>
<table border=1>
<tr><th>product ID</th><th>product Name</th>
<th>product price</th><th>product image</th> <th>Action</th></tr>
<?php
$qry =mysqli_query($con, "Select * From table_product");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
echo '<tr><td>'.$row["product_id"].'</td>';
echo '<td>'.$row["product_name"].'</td>';
echo '<td>'.$row["product_price"].'</td>';
echo '<td><img src="picture/'.$row["product_picture"].'" style=width:100px;height:xpx;"/></td>';
echo '<td>Edit </td></tr>';
}
?>
</table>
<br><br><br>
</body>
</html>
remove # sign from this line:
#unlink("picture/".$_GET["picture"])
this may show you warnings.
Use absolute path to file you want to unlink, not relative so your unlink should look like that
#unlink(__DIR__."/picture/".$_GET["picture"]);

Muliple upload php script and store in mysql database

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.

Adding the row ID to the filename of the uploaded file

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);

Categories