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>
Related
I am building a PHP application where a new user has to upload an avatar.
I managed to save the uploaded file path into my database,
but now I have to move the uploaded image from the temporary to the permanent directory, which is the folder 'avatars'.
I have searched through many answers on the same problem but haven't managed to find a working one. Since I am really new to PHP I'm gonna need some help for a working solution.
I have also tried copy() instead of move_uploaded_file with no luck.
HTML:
<div class="input-form">
<label for="avatar">Kies een profielfoto</label>
<input type="file" id="avatar-input" name="avatar" accept="image/*" onchange="loadFile(event)">
<img id="output" width="150" />
<input type="submit" id="submit-btn" name="vervolledig-submit" value="START">
</div>
PHP:
if(!empty($_POST)){
$fileSize = $_FILES["avatar"]["size"];
if($fileSize < 2000000){
$fileSizeOk = true;
}else{
throw new Exception("Je profielfoto heeft een grotere file size dan is toegelaten (max 2MB)");
$imgSizeOk = false;
}
$img = $_FILES["avatar"]["name"];
if($imgSizeOk == true){
move_uploaded_file($_FILES["avatar"]["tmp_name"], "avatars/$img");
}
}
EDIT: was asked to share my JS code:
a function that shows a preview of the uploaded picture:
let loadFile = function(event) {
let image = document.getElementById('output');
image.src = URL.createObjectURL(event.target.files[0]);
};
Suggested solution with AJAX
$('#submit-btn').on('click', function() {
var file_data = $('#avatar-input').prop('files')[0];
var form_data = new FormData();
form_data.append('avatar', file_data);
alert(form_data);
$.ajax({
url: 'profielVervolledigen.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});
with the following php code:
if(!empty($_POST)){
if ( 0 < $_FILES['avatar']['error'] ) {
echo 'Error: ' . $_FILES['avatar']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['avatar']['tmp_name'], 'avatars/' . $_FILES['avatar']['name']);
}
}
the alert gives [object FormData]
Thanks for any help
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.
I have fair knowledge of JS, PHP and Ajax but this simple problem has driven me nuts.
I am trying to upload an image silently, without using a form. I am not using a form because that will lead to nested forms in my HTML, which I read, can cause additional issues.
I have been able to use oFReader, to preview the images.
To upload the image, I am attempting an AJAX call as given below:
HTML
<div id="loginButton2">
<div id="personalimg" >
<img src="photos/seller_photos/<?php echo $profile_pic; ?>" width="70" hight="70" />
</div>
</div>
<div id="loginBox2" style="display:none">
<div id="loginForm2" class="floatLeft" >
<fieldset>
<input id="file" type="file" name="profile_img" value="photos/seller_photos/<?php echo $profile_pic;?>"/>
<input id="file_submit" type="hidden" name="submit4" value="1" >
</fieldset>
</div>
</div>
JS
$('#file').change(function(){
var oFReader = new FileReader();
oFReader.readAsDataURL(this.files[0]);
var fd = new FormData();
var file = $("#file").prop("files")[0];
fd.append('profile_img', file);
fd.append('submit4', 1);
fd.append('filename', 1);
oFReader.onload = function (oFREvent) {
$.ajax({
url: "upload.php",
dataType: 'image',
cache: false,
contentType: false,
processData: false,
type: "POST",
data: fd,
success: function(data){
console.log(data);
},
error: function(){
console.log("image upload failed");
}
});
$('#loginForm2').toggle();
$('#personalimg').html('<img src="'+oFREvent.target.result+'" width="70" height="70">');
};
});
PHP
if(isset($_POST['submit4'])) {
$check_sql = "select profile_pic from profile where user_id=$user_id";
$check_rs = mysql_query($check_sql);
$check_num = mysql_num_rows($check_rs);
if($check_num==0) {
$sql = "insert into profile(user_id) values($user_id)";
$rs = mysql_query($sql);
}
$fName = $_FILES["profile_img"]["name"] ;
$data = explode(".", $fName);
$fileName = $user_id.'.'.$data[1];
if($fName!='')$user->update('profile_pic',$fileName);
$fileTmpLoc= $_FILES["profile_img"]["tmp_name"];
//image store path
$pathAndName = "photos/seller_photos/".$fileName;
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
if(move_uploaded_file) {
$response['status'] = '1';
header('Location: edit_profile_new.php');
} else {
$response['status'] = '0';
}
return $response;
}
But somehow, I have not been able to get this to work. I am using chrome. I get 302 Found status code and "image upload failed" in console.
Can someone please help me out?
ps: I know, mysql is deprecated and will migrate to pdo. This code is inherited and hence has old standards.
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);
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.