How to upload files in a form via AJAX and PHP? - php

Here is what I have tried so far and it isn't working. The HTML file contains:-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Form Generator | Upload Driver Specification Sheet</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type='text/javascript'>
function submit_form() {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'last_file_action.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
$('#results').html(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
}
</script>
</head>
<body class="gray-bg3_full">
<form class="m-t" role="form" id='data' method="post" enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<div class="form-group">
<p id='new_project_text'>Please include your Product spec sheet: </p>
<input class="btn btn-primary-save btn-block" type="file" name="userfile" /> <i class="fa fa-upload"></i> <br/>
</div>
<button type= 'button' id="submit_driver" class="btn btn-warning block full-width m-b m-t" onclick='submit_form()'>Submit</button>
</form>
<div id='results'></div>
</body>
</html>
And the PHP file i.e. 'last_file_action.php' contains this:-
<?php
if ($_FILES['userfile']['error'] > 0)
{
switch ($_FILES['userfile']['error'])
{
case 1:
echo "File exceeded upload_max_filesize";
break;
case 2:
echo "File exceeded max_file_size";
break;
case 3:
echo "File only partially uploaded";
break;
case 4:
echo "Please choose a file to upload";
break;
case 6:
echo "Cannot upload file: No temp directory specified";
break;
case 7:
echo "Upload failed: Cannot write to disk";
break;
}
exit;
}
$upfile = 'productinformation/';
if (is_uploaded_file($_FILES['userfile']['tmp_name']))
{
if (!move_uploaded_file($_FILES['userfile']['tmp_name'], $upfile))
{
echo "Problem: Could not move file to destination directory";
exit;
}
}
else
{
echo "Problem: Possible file upload attack. Filename: ";
echo $_FILES['userfile']['name'];
exit;
}
// remove possible HTML and PHP tags from the file's contents
$contents = file_get_contents($upfile);
$contents = strip_tags($contents);
file_put_contents($_FILES['userfile']['name'], $contents);
// show what was uploaded
When I click the submit button I get this error "Problem: Possible file upload attack. Filename:". This is the error I've myself set in PHP file. It shows this error even when I don't select the file to upload. I want it to show Error "Please choose a file to upload" if I don't select a file to upload.

var formData = new FormData();
formData.append("userfile", $(":file")[0].files[0]);

Here is how I did it.
var formData = new FormData();
formData.append("userfile", $(":file")[0].files[0]);
The above code is right as long as you have one file and no other input fields. In case you have more input field and multiple file upload in a single form. One should consider target elements by their IDs instead of type $(":file").
Here is how we can get other files:-
var formData = new FormData();
formData.append("first_file", $("#1st_file_id")[0].files[0]);
formData.append("2nd_file", $("#2nd_file_id")[0].files[0]);
formData.append("3rd_file", $("#3rd_file_id")[0].files[0]);
Here is how we can get data from input fields of form by targeting their IDs.
formData.append("input_field", $("#input_field_id").val());
In PHP nothing needs to be changed. If we want to get the value of input field we can do it by:-
$var = $_POST['input_field'];
And if its a file, we can capture it by this and do the rest of the work as done in the question.
$_FILES['userfile'] or $_FILE['2nd_file']

Related

HTML prevent from redirect upload php

I need to prevent the page redirected to the upload php when click upload button.
How can I do this in below code.
<form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
</form>
<button onclick="myFunction()"> Upload
</button>
<script>
function myFunction(){
document.getElementById("myForm").submit();
}
</script>
A very basic, quickly written example of how to send a file - using ajax to the same page so that the user doesn't get redirected. This is plain vanilla javascript rather than jQuery.
The callback function can do more than print the response - it could, for instance, be used to update the DOM with new content based upon the success/failure of the upload.
<?php
$field='fileToUpload';
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_FILES ) ){
$obj=(object)$_FILES[ $field ];
$name=$obj->name;
$tmp=$obj->tmp_name;
$size=$obj->size;
$error=$obj->error;
$type=$obj->type;
if( $error==UPLOAD_ERR_OK ){
/*
This is where you would process the uploaded file
with various tests to ensure the file is OK before
saving to disk.
What you send back to the user is up to you - it could
be json,text,html etc etc but here the ajax callback
function simply receives the name of the file chosen.
*/
echo $name;
} else {
echo "bad foo!";
}
exit();
}
?>
<!doctype html>
<html>
<head>
<title>File Upload - using ajax</title>
<script>
document.addEventListener('DOMContentLoaded',function(e){
var bttn=document.getElementById('bttn');
bttn.onclick=function(e){
/* Assign a new FormData object using the buttons parent ( the form ) as the argument */
var data=new FormData( e.target.parentNode );
var xhr=new XMLHttpRequest();
xhr.onload=function(e){
document.getElementById('status').innerHTML=this.response;
}
xhr.onerror=function(e){
alert(e);
}
xhr.open('POST',location.href,true);
xhr.send(data);
};
},false);
</script>
</head>
<body>
<form method='post' enctype='multipart/form-data'>
Select image to upload:
<input type='file' name='fileToUpload'>
<input type='button' id='bttn' value='Upload' />
</form><div id='status'></div>
</body>
</html>
Using JQuery AJAX methods will allow you to send and receive information to a specified url without the need to refresh your page.
You will need to include the JQuery library in your HTML page aswell. You can either download it and put it in your project folder or include an online library here, like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
So your form will now look like this:
<form id="myForm" method="post" >
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload1">
<input type="submit">
</form>
Then you can use this code to simply upload your image to your file upload page (tested and working for myself):
<script>
$(document).ready(function ()
{
$("#myForm").submit(function (e)
{
//Stops submit button from refreshing page.
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
url: 'http://example/DB_1/AccessWeb/file_upload.php', //location of where you want to send image
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response)
{
alert('success');
},
error: function ()
{
alert('failure');
}
});
});
});
</script>
use AJAX With jQuery
$("#myForm").submit(function()
{
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(response) {
//Handle the response here
});
return false;
});

posting text file thru jQuery ajax in php and download the response file

Requirement:
I have to submit a form in a PHP file which has a file type input. I need jQuery ajax to post this text file to lets say processFile.php
processFile.php will take this text file as input and after processing will return a csv file which I want to download at the client.
I have seen many posts but nothing is helping me out.
HTML:
<form id="utilityForm" class="utilityForm4" method="POST" enctype="multipart/form-data" style="margin-top:25px">
<input type="file" name="image" id="image"/>
<br/><input type="submit" name="download" class="submit" value="Submit"/>
</form>
jQuery:
$(document).ready(function(){
$(".submit").click(function(e){
var urlstring = "processFile.php"
var form_data = new FormData($(this)[0]);
$.ajax({
url : urlstring,
type: "POST",
data : postData,
success:function(result){
var uri = 'data:application/csv;charset=UTF-8,' + encodeURIComponent(result);
window.open(uri, 'result.csv');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('failed');
echo (errorThrown);
}
});
});
});
I have tried hundreds of solutions given on the net but none is working.
Here I am providing complete working example:
HTML File:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(result) // A function to be called if request succeeds
{
e.preventDefault(); //stop the browser from following
window.location.href = 'upload/'+result;
}
});
}));
// Function to preview image after validation
});
</script>
</head>
<body>
<form id="uploadimage" action="" method="post" enctype="multipart/form-data">
Download
<input type="file" name="file" id="file" required />
<input type="submit" value="Upload" class="submit" />
</form>
</body>
PHP File:
<?php
if(isset($_FILES["file"]["type"]))
{
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo $_FILES["file"]["name"];
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
?>
Try to upload any file.
Is this useful for you?

Empty $_FILES while AJAX Uploading

I Have got the Following Problem:
I'm trying to Upload a File via a Form over Ajax
Here is the HTML File:
<html>
<header>
<link rel="stylesheet" href="useme.css"/>
<script src="jq.js"></script>
<script src="actions.js"></script>
</header>
<body>
<form enctype="multipart/form-data">
<input type="hidden" name="MAX_FILE_SIZE" value="30000000" />
<input type="file" id="file" name="file"/>
<input type="button" value="Click" id="submitBtn"/>
</form>
<span class="status">no status</span>
</body>
The JavaScript File:
/**
* Created by Kenny on 12.04.2015.
*/
$(document).ready(function(){
$("#submitBtn").click(function(){
var filename = $("#file").serialize();
$.ajax({
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
url: "upload.php",
enctype: 'multipart/form-data',
data : {
file: filename
},
type : "POST",
success: function(data){
if(data != "fail")
$(".status").html("Upload is availible at: " + data);
else
$(".status").html("Upload failed.");
}
});
});
});
And last but not lately the PHP File that does the Magic (Not really atm)
<?php
/**
* Created by PhpStorm.
* User: Kenny
* Date: 12.04.2015
* Time: 23:55
*/
$uploaddir = '/many/upload/' . uniqid() . '/';
if(!file_exists($uploaddir)){
mkdir($uploaddir, 0777, true);
}
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "http://use.hints.me/" . $uploaddir;
file_put_contents($uploaddir . "/index.php", "<?php Header('Location: " . basename($_FILES['userfile']['name']) . "'); ?>");
} else {
echo "fail";
}
?>
My Problem here is that I only get empty $_FILES in the PHP-File, the PHP File somehow works fine when i use a Standard POST form, but with Ajax it doesnt work at all.
Excuse my messy Code, it's just a Proof of Concept to a friend of mine and not at all used for Providing a serious File Upload site. I just want to get this working.
Things i checked here before:
check the php.ini File if the File Upload is enabled
added enctype="multipart/form-data" to the Form
added the MAX_FILE_SIZE tag to the Form
checked StackOverFlow all over

Search Text Files with PHP from User Input

Looking for a solution to search through a list of Zip Codes. I have a text file with a bunch of zip codes that we service. Would like to have a form on the website asking for the user to input their zip code to see if we service that area. If it does, display a message saying that we do, if not, saying that we don't. Thought PHP would be the best solution for my problem, but I'm a total noob when it comes to that.
I have my form set up, I'm just not sure how to search the text file and display the answer in another div?
<form action="zipcode.php" method="post">
<input type="text" name="search" />
<input type="submit" />
</form>
UPDATE: Preferably an AJAX solution!
AJAX method (tested)
PHP handler
(find_in_file_ajax.php)
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found";
}else{
echo "ZIP code does not exist";
}
?>
HTML form
<!DOCTYPE html>
<html>
<head>
<style>
.update {
font-family:Georgia;
color:#0000FF;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
// getting the value that user typed
var searchString = $("#search_box").val();
// forming the queryString
var data = 'search='+ searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "find_in_file_ajax.php",
data: data,
beforeSend: function(html) { // this happens before actual call
$("#results").html('');
$("#searchresults").show();
$(".word").html(searchString);
},
success: function(html){ // this happens after we get results
$("#results").show();
$("#results").append(html);
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="container">
<div>
<form method="post" action="">
<input type="text" name="search" id="search_box" class='search_box'/>
<input type="submit" value="Search" class="search_button" /><br />
</form>
</div>
<div>
<div id="searchresults">Search results: <span id="results" class="update"></span>
</div>
</div>
</div>
</body>
</html>
Original answer
Tested
First the file needs to be accessed via file_get_contents, then explode each entry and extract the zip code search in question.
Assuming the zipcodes.txt file is in the following format:
43505
43517
43518
43526
43543
NOTE: If 43505 is queried, it will be found. Unlike 4350 or 3505 will not be found, so it's a unique query.
Consider the following:
<?php
$search = $_POST['search'];
$text = file_get_contents('zipcodes.txt');
$lines = explode("\n", $text);
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "ZIP code found.";
}else{
echo "ZIP code does not exist";
}
?>
Saw your edit...the below is PHP.
I would do something like
$lines = file("/path/to/file.txt", FILE_IGNORE_NEW_LINES); //reads all values into array
if(in_array($_POST['search'], $lines)){ //checks if ZIP is in array
echo "found zip code";
}else{
echo "zip code does not exist";
}
As long as there isn't a VERY LARGE amount of zip codes...this should be fine. Also, what is the format of your file? This may not work.

ajax form data serialization failed

I have a HTML with a form in it like this:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
</head>
<body>
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
Your Photo: <input id="thefile" type="file" name="photo" size="25" />
<input type="button" name="submit" value="Submit" onclick="submitform();"/>
</form>
</body>
<script>
function submitform()
{
data = $('*').serialize();
$.post(
'http://localhost/banksoal/1.0.0/accept-file.php',
data
);
}
</script>
</html>
and the .php script like this:
<?php
//if they DID upload a file...
if($_FILES['photo']['name'])
{
print_r($_FILES['photo']);
$message = 'default message';
//if no errors...
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB
{
$valid_file = false;
$message = 'Oops! Your file\'s size is to large.';
}
else
{
$valid_file = true;
}
//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name);
$message = 'Congratulations! Your file was accepted.';
}
}
//if there is an error...
else
{
//set that to be the returned message
$message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error'];
}
}
var_dump($message);
?>
The problem:
in the submitform() function, in the script tag at the line:
data = $('*').serialize();
why I get empty result?
What is wrong with the code?
Thank you
change this
data = $('*').serialize();
to
data = $('theform').serialize();
and change this
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform">
to
<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform">
Give thsi a try as mentioned here: http://api.jquery.com/serialize/
$('form').submit(function() {
console.log($(this).serialize());
return false;
});
You can also use
echo json_encode($data);
http://php.net/manual/en/function.json-encode.php
You cannot upload files using Ajax, if you MUST upload files in an AJAX-like way you can use hidden iframes, set the target attribute equal to the iframe and grab the iframe's content to know whether the request has failed or not
This is what i usually do for this purpose, create a hidden iframe that will be the target to the form, something like this:
<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe>
and in processResult you can fetch the iframe's content by:
$(results).html();
This way when the iframe is loaded it will automatically trigger the function to inform the request is complete

Categories