Issues writing HTML form fields to text file - php

I'm trying to write the contents of a HTML form field to a text file on my web server.
I was able to get code I found on an example to work in a plain PHP file, but not in my desired file.
Whenever I submit the form, PHP throws an error. PHP Notice: Undefined index: person in <snip>/upload.php on line 26, referer: <snip>/upload
Here's the code of the file I want to log:
<?php
//Delete Current Files
$dirfiles = glob('<snip>/uploads/*'); // get all file names
foreach($dirfiles as $dirfile){ // iterate files
if(is_file($dirfile))
unlink($dirfile); // delete file
}
//Upload New Files
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
move_uploaded_file( $_FILES["images"]["tmp_name"][$key], "uploads/" . $_FILES['images']['name'][$key]);
}
}
echo "<h2>Successfully Uploaded Images</h2>";
//Log
$when = date("F j, Y, g:i a");
$who = $_POST["person"];
$out = fopen("output.txt", "a");
if (!$out) {
print("Could not append to file");
exit;
}
fputs($out,"$who\t");
fputs($out,"$when\t");
fputs($out,"$_SERVER[REMOTE_ADDR]\n");
print("Name, Time, Date, and IP Address have been recorded.");
?>
In the log file, date and IP address are logged fine, but not the name. (Like This)
February 11, 2013, 3:26 am IPADDR
where the name should be at the beginning like
JohnDoe February 11, 2013, 3:26 am IPADDR
In the original form file, it's just a typical form:
<form method="post" action="upload.php">
<input type="text" name="person" /> Your Name<br />
snip...
</form>
The only difference between the form where the logging worked and where it didn't was that this one also allows for image uploading via <input type="file" name="images" id="images" multiple />
What on earth would be causing the name not to be logged?
Edit: Update - It turns out thus bug is not present in Internet Explorer, but still is present in Chrome and Firefox. That's really strange.

you need to add formdata.append("person", $('input[name=person]').val()); in your js file
if (formdata) {
formdata.append("person", $('input[name=person]').val());
$.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
}
REF
[1] https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects

You must set enctype="multipart/form-data" in your html form attributes. I suspect FormData.append() isn't working properly if you don't.
EDIT:
Try adding this to the javascript code (maybe after if (formdata) {):
var person = $('input[name=person]').val();
formdata.append('person', person);

Related

PHP AJAX No data received through $_POST

As stated I am recieving no data through my $_POST. I am trying to pass multiple canvas dataURLs to the server to be stored as images. The data exists on the client but never makes it to the server. It saves a bunch of empty .PNGs which shows me that the code is being executed, just none of the data there.
Here is relevant info from my JavaScript file:
function saveImages(){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "urlForPHP.php",
data: $('#form1').serialize(),
success: function (result) {
console.log("Success");
}
});
}
And here is my PHP file (for one image only, I have removed the loop to store multiple images for readability)
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
$finalDest = "path/to/save/";
if (!is_dir($finalDest)) {
// dir doesn't exist, make it
mkdir($finalDest, 0777, true);
}
//save data
$file = base64_decode($_POST["image"]);
$success = file_put_contents($finalDest . $x . ".png", $file);
print $success ? $file : 'Unable to save the file.';
Thank you in advance, sorry if this has been solved before but I have done quite a bit of reading up on this and tried the solutions to similar answers and nothing has worked so far.
EDIT
Added HTML code, forgot to include my Form!
<form method="post" accept-charset="utf-8" name="form1">
<input name="boxTypeID" id="boxTypeID" type="hidden"/>
<input name="image" id="image" type="hidden"/>
<input type="button" name="send" onclick="saveImages()"/>
</form>

Obtain AJAX returned object in PHP

I have a program which is running server script on raspberry pi (client which is also a server). I'm scanning a barcode which then executes few commands (including generating XML file). When I submit the form with the 'serial' number, I want to be able to retrieve the filename (string) returned from AJAX ($_POST) method in server.php? if (isset($_POST['filename']) does not return the filename, how do I obtain filename with a single AJAX? and use it in PHP? I have no error messages, the $_POST['filename'] is empty. I tried separating the script into a different file and creating another AJAX calling that PHP script but it did not fully work and I wonder if there is a possibility to do it with a single AJAX and make PHP listen for the returned filename.
Or maybe is there a better way to obtain the filename of the external file than through client-side? (there is always single XML file waiting to be picked up).
server.php
<?php
$show_error = "";
if (isset($_POST['serial'])) {
$serialnumber = $_POST['serial'];
if ($serialnumber > 0) {
if (isset($_POST['filename'])) {
$filenamer = $_POST['filename'];
echo $filenamer;
} else {
echo "no filename returned from ajax call";
}
$remote_file_url = 'http://' . $_SERVER['REMOTE_ADDR'] . '/345.xml'; //FILENAME NEEDED
$local_file = '345.xml'; //FILENAME NEEDED
$copy = copy( $remote_file_url, $local_file );
}
?>
<html>
<body>
<form name="test" method="post">
<input type="number" name="serial" id="serial" value="1">
<input type="submit" name="">
</form>
</body>
<script type="text/javascript">
function scan(serialnumber)
{
return $.ajax({
url : 'http://localhost/test.php',
type : 'POST',
dataType : 'json',
data : { serial_no : serialnumber},
cache : false,
success : function(data) {
var filename = data[Object.keys(data)[1]];
console.log(filename);
}
});
};
scan(<?php echo $serialnumber; ?>);
</script>
</html>
test.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-type: text/json');
# Get the serial
$serial_no = $_POST['serial_no'];
$return['serial_no'] = $serial_no;
# Get the filename of the XML file
$filename = shell_exec('find /var/www/html/*.xml -printf "%f"');
$return['filename'] = $filename;
$return['scanpink'] = 1;
echo json_encode($return);
?>
As I mentioned in my comment, you don't have filename in php because your form does not include filename field. After receiveing filename from ajax you can do another ajax request with serial & filename fields or the second solution is to use a hidden field. After receiving data in ajax you cannot use them in php - You have to send it (filename) to php.

Delete local files and database records with AJAX

I am using ajax to delete files from both database and local. There is no problem on the database side. However I can't delete the correct file from local. I think I can't pass the correct file name... It deletes the local file listed top of the page.
My index.php file:
<p><?php echo $file->name; ?></p>
<input type="hidden" name="file-name" value="<?php echo $file->name; ?>">
<button name="delete" id="delete" value="<?php echo $file->id; ?>">
<span>DELETE</span>
</button>
My delete.php file:
if(isset($_POST['deleteFile'])) {
$delFile = $db->execute("DELETE from files WHERE id='{$_POST['id']}'");
$fname = 'upload/'.$_POST['fname'];
if($delFile){
unlink($fname);
echo "File is deleted!";
}
else{
echo "There was a problem!";
}
}
JS file:
$('body').delegate('#delete','click',function(){
var idDelete = $(this).val();
var nameDelete = $("input[name=file-name]").val();
var parent = $(this).parent().parent();
if(confirm){
$.ajax({
url : "delete.php",
type : "POST",
async : true,
data : {
deleteFile : 1,
id : idDelete,
fname : nameDelete,
},
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
This is more along the lines of "teach a man to fish" rather than an exact answer because it's hard to tell from your code why that file may or may not be deleted.
First, as other have said your code is extremely dangerous and has the ability for anybody to delete any file on your system - never trust user input. You might also have a SQL injection vulnerability too.
But, as far as your problem, you are not able to see what is going on because you are ignoring or masking bugs with your code. To provide some visibility this is what I would do:
if($delFile){
$fname = __DIR__ . '/' . $fname;
if (unlink($fname)) {
echo "File is deleted!";
}
else {
throw new Exception("Unable to delete file with name " . $fname);
}
}
else{
throw new Exception("Unable to delete DB record with id " . $_POST['id']);
}
Then in your javascript, something to the effect which will output the results of the ajax to the console so you can see what the file path is that is being looked for
if(confirm){
$.ajax({...},
success: function(){...},
error: function(jqXHR){console.log(jqXHR.responseText);}
});
}
That probably won't fix your error, but it will allow you to see what is going on, which is likely to be a simple error with the file path.

upload file using ajax like facebook uploading

My problem is, I want to upload a csv file without pressing a submit button and I used ajax for that case. But now, their is something errors appear, and the error said fopen() Filename cannot be empty. But I already get the file value that I want, but the $_FILES[$fie]['tmp_name'] can't read this value. But if I attach the variable in an alert() they display the exact filename. This is my sample codes.
This is the html:
<form id="Form2">
<input type="file" id="fie" />
</form>
this is the javascript:
<script style="text/javascript">
$(function(){
$('#Form2').change(function(e){
e.preventDefault();
var sub = document.getElementById("fie").files[0].name;
if($('#cat1').hasClass('show')){
$('#cat1').hide();
$('#cat2').html("<img src='pb1.gif' />");
$.ajax({
url:'uploading.php',
action:'get',
data: 'fie='+sub,
success: function(data){
$('#cat2').html(data);
}
});
}
});
});
</script>
This is the Php:
uploading.php
<?php
include("conn.php"); //assuming that connected to a database.
if (isset($_GET['fie'])) {
echo "<script>alert('".$_GET['fie']."')</script>";//IN ALERT THEY EXECUTE THE EXACT VALUE OF THE FILE I INPUT
$fie = $_GET['fie'];
$file = $_FILES[$fie]['tmp_name']; //PROBLEM IS THIS. THEY CAN'T READ THE VALUE AND TELL THEIR IS NO FILE.
$handle = fopen($file,'r') or die ('Cannot open file');
fgets($handle);
do {
if (isset($data[0])) {
mysql_query("INSERT INTO tbl_numbers (numbers,cute) VALUES ('".addslashes($data[0])."','".addslashes($data[1])."')");
}
}
while ($data = fgetcsv($handle,1000,",","'"));
echo "Successful Upload~!";
}
?>
Thanks for the reply.

Send/receive data via jQuery to/from PHP

I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.
However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.
This is the code I have till now:
create.php:
<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
<form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
<p id="message" style="display:none;">
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
</p>
<input type="text" id="create_album" name="create_album" value="" />
<input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
</form>
</div>
</body>
</html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
/* $("#btn_album").click(function() { */
function checkForm(form) {
//create post data
var postData = {
"create_album" : $("#create_album").val()
};
//make the call
$.ajax({
type: "POST",
url: "createAlbum.php",
data: postData, //send it along with your call
success: function(response){
$('#message').fadeIn();
}
});
/* }); */
}
</script>
createAlbum.php:
<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/
// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';
if (isset($_POST['btn_album'])) {
// Grab our form Data
$dirName = isset($_POST['create_album'])?$_POST['create_album']:false;
// first validate the value:
if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
// We have a valid directory:
if (!is_dir($path . $dirName)) {
// We are good to create this directory:
if (mkdir($path . $dirName, 0775)) {
$success = "Your directory has been created succesfully!<br /><br />";
}else {
$error = "Unable to create dir {$dirName}.";
}
}else {
$error = "Directory {$dirName} already exists.";
}
}else {
// Invalid data, htmlenttie them incase < > were used.
$dirName = htmlentities($dirName);
$error = "You have invalid values in {$dirName}.";
}
}
?>
There are at least two seperate problems with your code:
In the php-file, you check if $_POST['btn_album'] is set. This field is not sent as it is not part of your ajax-request (You're only sending "create_album" : $("#create_album").val()). So the code that creates the folder is never executed.
Another problem is the part
<?php echo (isset($success)?"<h3>$success</h3>":""); ?>
<?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.
The ajax request has a bad habit of failing silently.
You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code.
Also use the console.log() to check if the parameters are sent corectly. I'll try out the code myself to see the problem.
http://api.jquery.com/jQuery.post/
Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent. So your php file gets here
if (isset($_POST['btn_album'])) {
and returns false.
also you need to echo $error to get a response.

Categories