$_FILES array is empty - php

This is the first time I am trying to upload a file and for some reason my $_FILES array is empty. I have checked again and again my HTML and it looks okay to me. When i try to debug the below code in eclipse the $_Files array is empty when i check it. I have checked the php_ini file it has:
file_uploads = On
upload_max_filesize = 2M
The form is in a fancybox modal window.
My HTML looks like this:
<form action="/CiREM/attachments/addAttachmentsModal.php?requestId=120" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="120"/>
<input type='hidden' id='listScreen' name='listScreen' value=""?>
<input type='hidden' name='MAX_FILE_SIZE' value='4000000' /><br/> <strong>Max File size Allowed: </strong>4 Mb <br/><strong>File Formats Allowed: </strong>gif,jpeg,jpg,png<br/><hr/> <div class="control-group">
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
</div>
</div>
<div class ="clear"></div>
<input id="addAttachmentsBtn" type="submit" class="btn btn-primary btn-large" value="Add Attachments"/>
</form>
My php is
<form action="<?php echo $_SERVER['PHP_SELF']."?requestId=".$requestId?>" enctype="multipart/form-data" method="post" id="addattachment" name="addattachment" class="form-vertical" autocomplete="off">
<input type='hidden' id='requestId' name='requestId' value="<?php echo $requestId;?>"/>
<input type='hidden' id='listScreen' name='listScreen' value="<?php echo $listScreen;?>"?>
<?php
if ($CIREM['MAX_IMG_NUM']>0){
echo "<input type='hidden' name='MAX_FILE_SIZE' value='".$CIREM['MAX_IMG_SIZE']."' />";
echo "<br/> <strong>Max File size Allowed: </strong>".($CIREM['MAX_IMG_SIZE']/1000000)." Mb <br/><strong>File Formats Allowed: </strong>".$CIREM['IMG_TYPES']."<br/><hr/>";?>
<?php for ($i=1;$i<=$CIREM['MAX_IMG_NUM'];$i++){?>
<div class="controls input">
<input class="input-file" type="file" name="upload_file[]" id="upload_file[]"/><br/>
</div>
<?php }?>
<?php }
else{
echo "<p class='alert alert-info'>Attachment uploading is not allowed</p>";
}
?>
Any help will be greatly appreciated.
Thanks,
Shakira

Without looking through that spaghetti code, first check whether your $_POST is also empty.
If it is, make sure that post_max_size is larger than upload_max_filesize. The two settings have to be congruent.

First of all sorry for the late reply but since sometimes people stumble upon old topics on stackoverflow, I decided to write the way it works for me.
So, to send files via ajax you have to use FormData.
I'll paste a link to a github project I have to submit forms via ajax so you can check the working example and paste here the snippet.
Link: https://github.com/pihh/auto-ajax-form
Code:
$( "form" ).on('submit',function( event ) {
if($(this).attr('ajax')){
event.preventDefault();
var marianaFormUrl = $(this).attr('action');
var marianaFormId = $(this).attr('id');
var marianaFormMethod = $(this).attr('type');
var marianaFormSucess = $(this).attr('success');
var marianaFormComplete = $(this).attr('complete');
var marianaFormBefore = $(this).attr('before');
var marianaFormInputs = $('#' + marianaFormId +' :input');
var marianaEncType = $(this).attr('enctype');
var marianaFormData = {};
// Set enctype
if(marianaEncType === undefined || marianaEncType == ''){
$(this).attr('enctype','multipart/form-data');
}
// Run Ajax Call
$.ajax({
url: marianaFormUrl,
type: marianaFormMethod,
dataType: 'JSON',
data: new FormData( this ),
processData: false,
contentType: false,
cache: false,
success:function(data){
// Run success
if(marianaFormSucess !== undefined && marianaFormSucess !== ''){
var fn = marianaFormSucess;
var func = fn +'( data )';
eval(func);
}
},
complete:function(data){
// Run complete
if(marianaFormComplete !== undefined && marianaFormComplete !== ''){
var fn = marianaFormComplete;
var func = fn +'( data )';
eval(func);
}
}
});
}
});
This is it, using formData it sends the files just fine.

Related

Sending file together with form data via ajax post in php

Here is what I'm trying to do.
I'm uploading a file on the form and send the data via ajax.
Here is my code:
<form enctype="multipart/form-data" name="addcert_form" id="addcert_form" method="post" >
<input type='hidden' id="staffid" name="staffid" value="<?php echo $staffid; ?>" />
<label for="certNumber"><?php echo("Certification Number"); ?></label>
<input type="text" class="form-control certNumber" id="certNumber" name="certNumber" >
<div class="form-group" style="margin-bottom: 0px;margin-left: 15px;">
<label for="file-upload"><?php echo('File Upload'); ?></label>
<input type='hidden' id="file-upload-hidden" name="file-upload-hidden" />
<input type="file" name="file-upload" id="file-upload" accept="application/pdf">
</div>
</form>
$(document).on('change', "#cert-upload", function() {
var ajaxurl = generalObj.ajax_url;
var form = $("#addcert_form");
var params = form.serializeArray();
var formData = new FormData();
var file_data = $('#file-upload').prop('files')[0];
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
formData.append('file-upload', file_data);
$.ajax({
url: ajaxurl + "rzvy_staff_ajax.php",
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function (res) {
if(res=="file-uploaded"){
swal.fire(generalObj.updated, generalObj.cert-upload_changed, "success");
//location.reload();
}
}
});
});
However, when I see the information, I'm only getting the file info.
I have tried doing $_POST, and $_FILES, however, I'm not getting the information from the form. How can I get all of the information from the form when I upload the file?
Thank you,
Kevin
Here is what I found out. The data was coming over, I should have used both $_FILES and $_POST

data not retrieve through formdata

I am trying to save image using ajax .and passing data through Formdata()
but at php file i can not retrieve data or image name please help me
here is my code
<form name='signup' id='signup'>
<div class="row">
<!--<form id="uploadimage" action="" method="post" enctype="multipart/form-data">-->
<div id="selectImage">
<label>Select Image</label>
<div id="image_preview">
<img id="previewing" src="uploaded_files/259700.png" height="150" width="150" />
</div>
<input type="file" name="file" id="file" required />
<!--<input type="submit" value="Upload" class="submit" />-->
</div>
<!--</form>-->
</div>
<div class='row'>
<p>
<label for='username'>First name</label>
<input type='text' name='firstname' id='firstname' value='' placeholder='Enter First name' />
</p>
</div>
<div class='row'>
<p>
<label for='lastname'>Last name</label>
<input type='text' name='lastname' id='lastname' value='' placeholder='Enter Last name' />
</p>
</div>
<div class='row'>
<p>
<label for='email'>Email</label>
<input type='text' name='email' id='email' value='' placeholder='Enter Email' />
</p>
</div>
<div class='row'>
<p>
<label for='phno'>Phno.</label>
<input type='text' name='phno' id='phno' maxlength="10" value='' placeholder='Enter ph no' />
</p>
</div>
<!--<input type="hidden" name="actionfunction" value="saveData" />-->
<input type="hidden" name="actionfunction" value="saveData" />
<div class='row'>
<input type='button' id='formsubmit' class='submit' value='Submit' />
<!--<input type='submit' id='formsubmit' class='submit' value='Submit' />-->
</div>
</form>
here is my ajax script code:
$("#signup").on('submit', (function() {
var fname = $("#firstname");
var lname = $("#lastname");
var email = $("#email");
var phno = $("#phno");
if (validateform(fname, lname, email, phno)) {
var formdata = new FormData(this);
$.ajax({
url: "DbManipute.php",
type: "POST",
data: formdata,
processdata: false,
cache: false,
contentType: false,
success: function(response) {
//alert(response);
if (response == 'added') {
$("#show_user").trigger("click");
getusers();
$("#msg").html("user added");
}
},
});
}
});
And here is my "DbManipute.php" code:
function saveData($data,$con){
$imgfile=$_FILES['file']['name'];
$fname = $data['firstname'];
$lname = $data['lastname'];
$email = $data['email'];
$phno = $data['phno'];
//$fname = $_POST['firstname'];
//$lname = $_POST['lastname'];
//$email = $_POST['email'];
//$phno = $_POST['phno'];
$sql = "insert into tbl_employees(emp_name,emp_lname,emp_email,emp_phno,emp_pic) values('$fname','$lname','$email','$phno','$imgfile')";
if($con->query($sql)){
echo "added";
} else {
echo "error";
}
}
i didn't get any error and data also not inserted.
when i remove image upload and use serialize method then data is saved successfully but in serialize method image file name can not retrieve
please help me regarding this.
You need to append the type="file" separately.
$("#signup").on('submit', (function() {
var fname = $("#firstname");
var lname = $("#lastname");
var email = $("#email");
var phno = $("#phno");
if (validateform(fname, lname, email, phno)) {
var formdata = new FormData(this);
formdata.append( 'file', $("input[name='file']")[0].files[0] );
$.ajax({
url: "DbManipute.php",
type: "POST",
data: formdata,
processdata: false,
cache: false,
contentType: false,
success: function(response) {
//alert(response);
if (response == 'added') {
$("#show_user").trigger("click");
getusers();
$("#msg").html("user added");
}
},
});
}
});
Your client side error will not be shown in the page just like php.
You have some errors in your javascript code. You have missed an closing parenthesis at the end of js code: });
If you are using chrome or firefox browser, press F12 button and console will be shown and will show you your js errors.
Tip: you can debug your project by printing any variables in your code. For example try to use console.log('test'); in your js code to check if your ajax command is working. console.log() will print in console box of browser.
When i did this in your code i understood that your code is not running at all. Because you have set your code to be run on submit and you do not have any submit button. Then you need to change your button's type="submit".
After that you need to prevent form by submitting the form using browser and tell browser that you want to run your js code. For that you need need to prevent default action for form submit event like this:
$("#signup").on('submit', (function(evt) {
evt.preventDefault();
Another tip is that your php code is in a function that is never called. you need to call your php function in your php file or you should put your codes out of function.
Try changing your code like this. This should make your code work. And to check if your ajax request is working try to echo something in your code and in your js code alert the response.
Edit#1 One more thing to consider is that for cases that you want to upload files using ajax, you can not set data like FormData(this). For ajax uploading purpose you should create object of FormData (new FormData()) and append the data separately. (as Rejith R Krishnan said).

Order of execution ISSET vs JQUERY

I have two functions one is PHP second is JQuery. I want them to activate on same button click. But I want fisrt to activate PHP function and then JQuery. How can I do this. Here is my code. The problem is this line in JQuery function
var imagename = "<?php echo $nameoffile ?>";
When I replace that with hardcoded variable everything work fine. How can I control order of execution ?
HTML :
<form id ="submit_leave_email" enctype="multipart/form-data" method="POST" >
<div class="form1">
<div class="radio-line" id="radio-manager" style="font-size:12px">
<input type="radio" id="rad-400" name="radio-manager" value="No"/> Registered
<input type="radio" id="rad-400" name="radio-manager" value="No"/> Unregistered
</div> <br>
<h4 class="manager" style="font-size:12px">ID of car is :</h4><br><br>
<input type="hidden" name="MAX_FILE_SIZE" value="100000" class="input_1" />
<input id="fileupload" name="uploadedfile" type="file" class="input_1" /><br/>
<input id="brand" type="text" value="Name of car :" class="input_1" name="brand" /><br></div> <br>
<div id = "image" style="width:100px; height:100px"></div></div>
<input id="submit" type="submit" name="submit" value="submit">
</form>
PHP :
<?php
if(isset($_POST['submit'])){
$target_path = "images/";
$nameoffile = basename( $_FILES['uploadedfile']['name']);
$target_path = $target_path . $nameoffile;
echo $nameoffile;
if(!move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "There was an error uploading the file, please try again!";
}
}
?>
JQuery :
<script type="text/javascript">
$( "#submit_leave_email" ).submit(function( event ) {
var brand = $('#brand').val();
var id = localStorage.getItem("id");
if($('#rad-400').is(':checked')){
var ide = 'reg';
} else {
var ide = 'unreg';
}
var imagename = "<?php echo $nameoffile ?>";
$.ajax({
type: "POST",
url: "updateCarSql.php",
data: "ide=" + ide + "&id="+ id + "&brand="+
brand+"&imagename="+imagename,
success: function(){
$("#submit_leave_email").fadeOut();
$("#update_success1").fadeIn();
}
});
});
</script>
PHP code runs at the server, jQuery runs at the client so the strict answer to your question is ISSET is executed before the jQuery; however that doesn't really help you.
It looks like you are trying to use PHP to get the file name for your jQuery code before submitting the form. This is a bit of a catch 22 as PHP code won't be run until after you submit the form.
If you want to get the chosen file name you'll need to use javascript. Look at this question - Use jQuery to get the file input's selected filename without the path
Also look at preventDefault as I suspect you don't want to do an ajax call and submit your form.

how to upload image using ajax in php

<div class="control-group">
<label class="control-label" for="inputEmail">Image</label>
<div class="controls">
<input type="file" value="Browse" name="image" id="image" />
<span style="color: #61625F; font-weight: bolder;" class="sixth"></span>
</div>
</div>
ajax code below
$("#reg").click(function() {
$.ajax({
url: "process_service_person_register.php",
type: "post",
data: "image": $("#image").val()},
});
how will i send the image to the "process file"
You have to use the FormData object.
<script>
if ("FormData" in window)
{
var fd = new FormData();
fd.append('file', $('#image')[0].files[0]);
$.ajax({
url: "process_service_person_register.php",
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(result) {
console.log(result);
}
});
}
else
{
console.log('sorry, FormData object is not available.');
}
</script>
Without FormData, you will have to go old school like using the hidden iframe method
Here is my php page when i post through ajaxform
<?php
include('phpfunc.php');
$path = "images/news/";
$utime = time();
$valid_formats = array("jpg", "png", "bmp","jpeg","gif");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
$name = strtolower($_FILES['uploadnews']['name']);
if(strlen($name)){
$extpos = strrpos($name, '.', -1);
$ext = substr($name,$extpos+1);
if(in_array($ext,$valid_formats)){
$actual_image_name = $utime.".".$ext;
$fpath = $path.$actual_image_name;
$tmp = $_FILES['uploadnews']['tmp_name'];
if(move_uploaded_file($tmp, '../'.$fpath)){
echo $fpath;
}else{
echo "failed";
}
}else{
echo "Invalid file format..";
}
}else{
echo "Please select image..!";
}
exit;
}
?>
There is no way to upload files using AJAX
BUT, you can imitate the behavior of AJAX by using hidden Iframe (other ways exists - but this is the most compatible way for old and new browsers)
for example:
This is your form:
<form target="upload_frame" action="upload_handler.php" method="POST" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="inputEmail">Image</label>
<div class="controls">
<input type="file" value="Browse" name="image" id="image" />
<span style="color: #61625F; font-weight: bolder;" class="sixth"></span>
</div>
</div>
</form>
Now you should have a hidden IFrame inside your page, and name it upload_frame
<iframe name="upload_frame" id="upload_frame" width="1" height="1" frameborder="no" ></iframe>
And in upload_handler.php or whatever file that suppose to handle your upload request you should output something like
<script type="text/javascript">
window.parent.onUploadCallback(callback_data);
</script>
This will call onUploadCallback function set on the original's page JavaScript.
The callback_data parameter better be JSON serialized so you can use it inside the function as a native JavaScript object.
For example:
function onUploadCallback(response){
if(response.success)
alert("File uploaded: "+response.file_path);
} else {
alert("Error while uploading the file: "+response.error_message);
}
}
For making the all thing more generic - you should use "JSONP" like style and pass "callback" parameter to upload_handler.php with the name of the function you want to call. and then add it to the form as hidden field <input type="hidden" name="callback" value="window.parent.onSuccessCallback" />
After all that description - my real suggestion to you is - use an already made jQuery library for the task

How to upload open and read large(20 mb) csv file?

i am working on csv file upload and i need to upload large csv files and then need to insert into database with field mapping.I am doing this using Jquery it is not showing any error just show the url into red color into firbug. I am not getting what is the problem?This is my script.
<script src="js/jquery.form.js"></script>
<script src="js/create_input.js"></script>
<script>
$(document).ready(function() {
$('#UploadForm').on('submit', function(e) {
e.preventDefault();
var value= $("#valS").val();
var host=$('#host').val();
//alert(host);
$(this).ajaxSubmit({
type: "POST",
url: host+"views/excel_file_import.php",
data: {value: value},
success: function(html){
$('#Exceloutput').html(html);
}
});
});
});
$(document).ready(function() {
$("#updatefields").click(function(){
var arrayOfValues = $(".bookDetails select").map(function (i, el) { return $(el).val(); }).get();
var fileName= $("#excelfile").val();
var csvState= $("#state_csv").val();
var host=$('#host').val();
$.ajax({
type: "POST",
url: host+"views/update_fields.php",
data:{str:arrayOfValues, fileName:fileName, csvState:csvState},
success: function(msg){
$('#fieldUpdate').html(msg);
}
});
return false;
});
});
</script>
<?php
$host=$_SERVER['HTTP_REFERER'];
$url=substr($host,0,-9);
?>
<input type="hidden" value="<?php echo $url; ?>" id="host">
<h1 class="page-title">Upload Csv File</h1>
<div class="container_12 clearfix leading">
<div class="grid_12" id="edit-form">
<form action="<?php echo $url; ?>views/excel_file_import.php" method="post" enctype="multipart/form-data" id="UploadForm" class="form has-validation">
<div class="clearfix">
<label for="form-upload" class="form-label">Upload File<em>*</em></label>
<div class="form-input">
<input type="file" size="50" class="text" id="excelfile" name="excelfile" required="required"/>
<input type="hidden" size="50" class="text" id="valS" name="valS" value="1" required="required"/>
</div>
</div>
<div class="form-action clearfix">
<button class="button class-button" type="submit" id="SubmitButton">Upload</button>
<button class="button class-button" type="submit" id="updatefields" name="updatefields">UpdateExcel</button>
</div>
</form>
<div id='fieldUpdate'>
</div>
<div id='Exceloutput'>
</div>
</div>
</div>
and this is excel_file_import.php code.
<?php
include("../common/connection.php");
if(isset($_POST))
{
$database= "test2";
$filename = 'test-'.$_FILES['excelfile']['name'];
$value= $_POST['value'];
$copy= move_uploaded_file($_FILES["excelfile"]["tmp_name"],"../files/".$filename);
if($copy)
{ echo "Upload Success";?>
<?php
}
}
?>
Have you tried increasing the file upload limit in php.ini file:
file_uploads = On
upload_max_filesize = 20M //needs to be in {x}M format
see more info here:
http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes
http://davidwalsh.name/increase-php-file-upload-limit-using-php-ini
http://wiki.lunarpages.com/Increase_php.ini_Upload_Limit
http://www.radinks.com/upload/config.php
I am doing this using jQuery. it is not showing any error. It is just showing the url into red color into firbug
Are both the files residing on same domain? html and php both? Firebug is showing that red color url because cross domain ajax request is not allowed normally
For uploading large files on server check these setting in php.ini file and if you don't have access of php.ini than you can change it htaccess file.Increase value of these file uploads according to your requirements.
max_input_time 1000
max_execution_time 1000
post_max_size 1000M
max_file_uploads 50
upload_max_filesize 1000M

Categories