PHP file upload with multiple post values - php

I'm having a form that the user can fill in like this:
<form id="regForm" action="" method="POST">
<input type="text" name="name" class="form-control">
<input type="text" name="address" class="form-control">
<input type="text" name="city" class="form-control">
<input type="text" name="country" class="form-control">
<input type="file" name="callflowfile" class="form-control"> // the file
<input type="submit" name="formpost" class="form-control">
</form>
But when I post this form including the file, the file doesn't get uploaded and added to the DB.
This is my PHP code:
if(isset($_POST['formpost'])){
// insert name- address - city - county to DB
// insert callflowfile to directory
// If The array exists, add callflowfile
if ($_FILES["callflowfile"]["name"])
{
//Count number of files in array, loop through each file
for($i=0; $i<count($_FILES['callflowfile']['name']); $i++)
{
// If the file in array exists
if ($_FILES["callflowfile"]["name"][$i])
{
// If the file isnt 0 bytes
if ($_FILES["callflowfile"]["error"][$i] > 0)
{}
else
{
//move the file
// first get the original name of the uploaded file
$filename = $_FILES["callflowfile"]["name"][$i];
// now rename the original file into a random name
// get the file extension first
$ext = substr(strrchr($filename, "."), 1);
// then generate the random file name
$randomName = md5(rand() * time());
$filePath = "documents/" . $randomName . '.' . $ext;
// move the file and rename it
if(move_uploaded_file($_FILES["callflowfile"]["tmp_name"][$i], $filePath)){
// Add uploaded file row to database
}
}
}
}
}
}
The file isn't uploaded while the other form values are saved correctly.
I get the following error:
Undefined index: callflowfile in //directory
Does anyone know how to upload a file next to other form post values?

Add an enctype="multipart/form-data" attribute to your form so that it allows file(s) to be posted/uploaded :
<form id="regForm" action="" method="POST" enctype="multipart/form-data">
And you need to adjust file processing loop conditionals, change it like this :
if (isset($_POST['formpost'])) {
// insert name- address - city - county to DB
// insert callflowfile to directory
// If The array exists, add callflowfile
if ($_FILES["callflowfile"]["tmp_name"]) {
//Count number of files in array, loop through each file
for ($i = 0; $i < count($_FILES['callflowfile']['tmp_name']); $i++) {
...

replace your form tag by this
<form id="regForm" action="" method="POST" enctype="multipart/form-data">
And after update kindly do var_dump($_POST,$_FILES) at the first line of your php file you will get the all post fields within $_POST variable and Information of file will get in $_FILES

Related

how to upload at new name and section

I have a problem that made me lose my temper really I have the following code
OK ?
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
$finalpath =realpath(dirname(__FILE__)."/Uploads/".$path);
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
$type = $_FILES["vedio"]['type'];
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
The first problem is supposed to be the process of uploading the file to file uploads
The file is not even uploaded to the same file as the page
Second, the goal is to write the name of the file uploaded within the text, but what is happening in reverse exactly that
So how to make the upload process successful
Inside the uploads / value received from the form section
And the new name of the received value of the form
<form action="<?php echo $PHP_SELF; ?>" method="post" enctype="multipart/form-data">
<div id="inputs">
<label class="labels" for="name">Vedio Name: </label>
<input id="name" type="text" name="vedionamet" value="vedio"> </br>
<label class="labels" for="selectsection">Select Section :</label>
<select name="selectsection" id="section" >
<?php
foreach($sections as $pathat){
echo "<option value='$pathat'>" . "$pathat" . "</option>";
};
?>
</select></br>
<label class="labels" for="upup">Select Vedio : </label>
<input id="upload" type="file" name="vedio"></br>
<input id="subb" type="submit" name="uploadsub" value="Upload">
</
For the HTML part, you may change the action to "#" if you want to use a same page to handle the upload request.
For the PHP part, you may try the following codes, it works on my computer. Please also make sure that you have already established these sub video folders in Uploads folder
<?php
$sections = array("Other","Romance","Horror","Sucid","Dance","Comedy");
//add one condition to avoid warning when the page first loads
if(isset($_POST["selectsection"])){
$vedioname = $_POST['vedionamet'];
$path = $_POST['selectsection'];
//Use this to get the path
$finalpath = realpath(dirname(getcwd())) . '\\Uploads\\' . $path. '\\';
$vedname= $_FILES['vedio']['name'];
$temp=$_FILES['vedio']['tmp_name'];
//Use this to get the extension of file name
$type = pathinfo($vedname, PATHINFO_EXTENSION);
$size = $_FILES['vedio']['size'];
$errors = $_FILES['vedio']['error'];
if($_POST['uploadsub']){
move_uploaded_file($temp,$finalpath.$vedioname.".".$type);
echo "Done Uploaded".$type;
}else
{
echo "$error";
}
}
?>

php - Upload .dat file to be stored in json

I am trying to upload .dat file, I want to get the content inside the file and have it in json.
I have this code:
HTML:
<from action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>
PHP:
If(isset($_POST["btnSubmit"])) {
$file = file_get_contents($_FILES["fileUpload"]["name"], true);
$r = json_encode($file);
}
The error I get is file_get_contents("fileName.dat"): failed to open stream
I am not trying to upload the file to my server or a folder, I am trying to get the data inside it and store it into json.
A file upload will save the file in the php's defined temporary directory. From there you can either move the file to a desired location, or get the content from it. In your case you can simply get the content by using "tmp_name" instead of "name".
Future more, you have to make sure you have the enctype set in your form.
<?php
// check if file is given
if(!empty($_FILES)) {
// get file from temporary upload dir
$file = file_get_contents($_FILES["fileUpload"]["tmp_name"], true);
$r = json_encode($file);
// show restult
var_dump($r);
}
?>
<!-- add multipart -->
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload">
<button type="submit" name"btnSubmit">Upload</button>
</form>

I have a form where I can submit text files, and i want it to add those text files to another existing form

I have an html form that is used to upload text files:
<div class="form">
<h3>Upload File:</h3>
<form action="networkSelector.php" method="post" enctype="multipart/form-data" name="FileUploadForm" id="FileUploadForm">
<label for="UploadFileField"></label>
<input type="file" name="UploadFileField" id="UploadFileField" />
<input type="submit" name="UploadButton" id="UploadButton" value="Upload" />
</form>
</div>
The php portion of the code for the form:
<?php
require('db.php');
include("auth.php");
if(isset($_FILES['UploadFileField'])){
// Creates the Variables needed to upload the file
$UploadName = $_FILES['UploadFileField']['name'];
$UploadName = mt_rand(100000, 999999).$UploadName;
$UploadTmp = $_FILES['UploadFileField']['tmp_name'];
$UploadType = $_FILES['UploadFileField']['type'];
$FileSize = $_FILES['UploadFileField']['size'];
// Removes Unwanted Spaces and characters from the files names of the files being uploaded
$UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName);
// Upload File Size Limit
if(($FileSize > 125000)){
die("Error - File too Big");
}
// Checks a File has been Selected and Uploads them into a Directory on your Server
if(!$UploadTmp){
die("No File Selected, Please Upload Again");
}else{
move_uploaded_file($UploadTmp, "C:/xampp/htdocs/meg/$UploadName");
}
}
?>
It works great and as seen in the 'move_upload_file command it puts them directly into that directory.
However what I am trying to achieve is to upload these files with this form and then to add it to another form that is on the same page.
Here is an example of my other form:
<form action="networkCompiler.php" method="POST">
<h3>Choose Network/Function:</h3>
<select id ="network" name="network" />
<option value="networkA">A</option>
<option value="networkB">B</option>
</select>
So ideally if I upload networkC on the first form, I want it to then display on the second form. I am using PHP primarily on this project and was attempting to find a solution in that language. So far I have tried saving the file upload as a variable and then adding that to the bottom of the form.
<?php
if (isset($_POST['UploadButton'])) {
if (is_uploaded_file($_FILES['UploadFileField']['tmp_name'])) {
$trying = $_POST['FileUploadForm'];
}
}
?>
Any input would be appreciated. Thank you.
Use file_get_contents():
<?php
if(your_condition)
echo '<option value="the_value_you_want">' . file_get_contents('path_of_uploaded_file') . '</option>';
?>

How to upload multiple images url into database and move files to folder [duplicate]

This question already has answers here:
Multiple file upload in php
(14 answers)
Closed 6 years ago.
i want to upload multiple images url into database , after which i will move the file to an upload folder, then want to display the images and possibly edit by changing or removing them. i've been able to do that with one, but want to do that for multiple pics.
this is my html
<section class="form-group">
<section class="col-md-12">
<label for="price">Add Image</label>
<input type="file" name="uploadedfile" id="uploadedfile" class="form-control" />
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
</section>
</section>
Now my php script
$target_path="uploads/";
$target_path=$target_path.basename($_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
}
if($target_path==="uploads/"){
$target_path="images/no-thumb.png";
}
$query="insert into properties
(owner,email,contact,title,location,price,description,property_id,property_type,bedrooms,images,gsize,size,status,post_date)
values('$name','$email','$contact',
'$title','$location','$price','$description','$listid',$type','$bedroom','$target_path','$gsize','$size','$status',now())";
$result=mysqli_query($dbc,$query);
if($result){
echo '<p class="bg-success alert alert-success text-center">Property Listing Successful</p>';
}else{
echo '<p class="bg-danger alert alert-danger">My bad!!! Something went totally wrong. Try again later while i try to fix it <span class="close pull-right"> <span class="close pull-right"> <a href="#" >× </a></span></p>';
}
```
Change input field to
<input type="file" multiple="true" name="uploadedfile[]" id="uploadedfile" class="form-control" />
Or
<input type="file" multiple="multiple" name="uploadedfile[]" id="uploadedfile" class="form-control" />
You will get array of selected images in $_FILES. You can loop through it and save it one by one.
Here is what you need to do:
1.Input name must be be defined as an array i.e. name="inputName[]"
2.Input element must have multiple="multiple" or just multiple
3.In your PHP file use the syntax "$_FILES['inputName']['param'][index]"
4.Make sure to look for empty file names and paths, the array might contain empty strings
HTML:
input name="upload[]" type="file" multiple="multiple" />
PHP :
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['upload']['name'][$i];
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
//Handle other code here
}
}
}
source

how to count number of uploaded files in php

How can i count the number of uploaded files?
This is my form:
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form id="sfmFiler" class="sfmform" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" multiple />
<input type="submit" name="submitHandler" id="submitHandler" class="buttonUpload" value="Upload">
</form>
and this is the piece of php which uploads the files:
if($_SERVER['REQUEST_METHOD'] == "POST") {
$tmpFilePath = $_FILES['file']['tmp_name'];
$newFilePath = $dir.'/' . $_FILES['file']['name'];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "xxx files are successfully uploaded";
}
}
In this code you are getting only one file thats why you are getting count result 1. if change your input file name like "file[]"
<input type="file" name="file[]" id="file" multiple />
and then use the below line code you will get your desire result. Cause its needs an array filed to hold the input data.
<?php echo count($_FILES['file']['name']); ?>
Thanks, i tried in my system get the result.
AFriend is correct. The above answers always return 1.
Try:
echo count(array_filter($_FILES['file']['name']))
Worked for me anyway.
_t
Using the array_filter function it works
try
$countfiles = count(array_filter($_FILES['file']['name']));
It returns 0 in case of NULL, 1 in case of 1 file uploaded, etc.
Check this answer
<?php echo count($_FILES['file']['name']); ?>
php multiple file uploads get the exact count of files a user uploaded and not the count of all input fields in the array
You could use the count function:
$no_files = count($_FILES);
If no files are selected and your file count is 1, you can use this line before moving the file:
if (!empty($_FILES['file']['tmp_name'][0])) {
for($i=0;$i<$countfiles;$i++){

Categories