PHP not able to read $_FILES - php

I'm trying to read $_FILES uploaded by my AJAX upload form. This is the POST request:
POST myhost.net/csv.php
Host: myhost.net
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:36.0) Gecko/20100101 Firefox/36.0
Accept: application%2Fjson%2C%20text%2Fjavascript%2C%20*%2F*%3B%20q%3D0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
X-File-Name: Europe_1351.csv
Content-Type: multipart/form-data; charset=UTF-8
Pragma: no-cache
Cache-Control: no-cache
Referer: http://myhost.net
Content-Length: 26
Cookie: PHPSESSID=kourjvs7rm980d2cg4qvaav965
Connection: keep-alive
And on the server side, I got:
var_dump( $_FILES );
Even though 'multipart/form-data' is set, there aren't any data in $_FILES variable. Does this have something to do with PHP configuration? Thanks!
EDIT:
Here is my code:
<script src="//raw.githubusercontent.com/LPology/Simple-Ajax-Uploader/master/SimpleAjaxUploader.js">
$(document).ready(function()
{
var sizeBox = document.getElementById('sizeBox');
var uploader = new ss.SimpleUpload({
button: 'uploadButton', // file upload button
url: 'csv.php', // server side handler
name: 'uploadfile', // upload parameter name
contentType: 'multipart/form-data',
responseType: 'json',
allowedExtensions: ['csv'],
maxSize: 10 * 1024, // kilobytes
hoverClass: 'ui-state-hover',
focusClass: 'ui-state-focus',
disabledClass: 'ui-state-disabled',
onSubmit: function(filename, extension)
{
this.setFileSizeBox(sizeBox); // designate this element as file size container
},
onComplete: function(filename, response)
{
if (!response) {
alert(filename + 'upload failed');
return false;
}
alert( 'file ' + response.data + ' uploaded successfully ');
// do something with response...
}
});
});
</script>
<div id='uploadButton'>
CSV
</div>
<div id='sizeBox'>
size
</div>

Use php inbuilt function print_r();
print_r($_FILES);

Related

POST Empty Regardless of Request [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 1 year ago.
I am using jQuery to submit the following request:
$.ajax({
url: encodeURI('/server/api/user/update.php/'),
method: 'POST',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + utility.getJsonWebToken()
},
data: JSON.stringify(e.model),
dataType: 'json'
})
And I have the following PHP code that verifies that the request is valid and contains the necessary body:
// check for bad method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
$returnedJson['error'] = 'The supplied request method is not supported for the requested resource. This resource expects a POST request.';
echo json_encode($returnedJson);
return;
}
// check for bad request
$errors = array();
$user = new UserModel();
foreach (UserModel::$RequiredColumnNames as $property) {
$success = ControllerUtility::isValueInRequest($_POST, $property);
if (!$success) {
array_push($errors, $property);
continue;
}
$user->$property = $_POST[$property];
}
if (count($errors) > 0) {
http_response_code(400);
$returnedJson['error'] = 'Malformed request syntax. The following properties are missing from the request: ' . join(', ', $errors);
echo json_encode($returnedJson);
return;
}
Every time I submit the request, I get 400 error with the 'Malformed request syntax. The following properties are missing from the request: ...' error message.
I echoed the $_POST and $_REQUEST but in both instances and empty array is returned.
I verified that the request headers is a POST:
POST /server/api/user/update.php/ HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json
Authorization: Bearer -removed-
X-Requested-With: XMLHttpRequest
Content-Length: 180
Origin: http://localhost
Connection: keep-alive
Referer: -removed-
Sec-GPC: 1
And the fields are included in my request JSON:
{
"CreatedBy": null,
"CreatedOn": "2021-02-28 13:53:54",
"DeletedOn": null,
"Email": "-removed-",
"ModifiedBy": "1",
"ModifiedOn": "2021-02-28 16:35:51",
"UserId": "1",
"Username": "Adminn"
}
I have even removed the content-type header from my PHP without success. I've also tried just passing e.model instead of calling stringify in the AJAX request. At this point I'm at a loss as to what I'm doing wrong.
// echo the json string from php://input.
file_get_contents('php://input');

Why do I get "POST http://54.xx.xx.xx/wp-admin/admin-ajax.php 500 (Internal Server Error)" when using Wordpress+Ajax?

It's the first time for me using ajax on WP.
I am working on a simple contact form, and for some reason whenever I click submit I get an error:
on console:
POST http://54.xxx.xx.xx/wp-admin/admin-ajax.php 500 (Internal Server Error)jquery.js?ver=1.11.1:4 m.ajaxTransport.sendjquery.js?ver=1.11.1:4 m.extend.ajaxmain.js:66 (anonymous function)jquery.js?ver=1.11.1:3 m.event.dispatchjquery.js?ver=1.11.1:3 m.event.add.r.handle
on chromes "Networks":
Remote Address:54.xx.xx.xx:80
Request URL:http://54.xx.xx.xx/wp-admin/admin-ajax.php
Request Method:POST
Status Code:500 Internal Server Error
Request Headersview source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:73
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:wp-settings-1=editor%3Dtinymce%26posts_list_mode%3Dlist; wp-settings-time-1=1424359234
Host:54.xx.xx.xx
Origin:http://54.xxx.xx.xx
Referer:http://54.xxx.xx.xx/?page_id=73
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Dataview sourceview URL encoded
action:submit_contact_form
fullname:test
email:test#gmail.com
text:test
Response Headersview source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://54.xxx.xx.xx
Cache-Control:no-cache, must-revalidate, max-age=0
Connection:close
Content-Length:0
Content-Type:text/html; charset=UTF-8
Date:Thu, 26 Feb 2015 16:10:19 GMT
Expires:Wed, 11 Jan 1984 05:00:00 GMT
Pragma:no-cache
Server:Apache/2.4.7 (Ubuntu)
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Powered-By:PHP/5.5.9-1ubuntu4.5
X-Robots-Tag:noindex
This is my ajax part:
//send info to php
$.ajax({
beforeSend: function() {
if ( IsEmail(email) == false) {
$('#aboutUnsuccess').show("slow");
$('.form_content').hide("slow");
}
},
url: document.location.protocol+'//'+document.location.host+'/wp-admin/admin-ajax.php',
type: "POST",
/*action: 'submit_contact_form',*/
data: ({ "action": "submit_contact_form", "fullname": fullname, "email": email, "text": text }),
success: function (results){
if ( IsEmail(email) == true) {
//hide table
$('.form_content').hide('slow', function() {
$('.form_content').hide( "slow" );
});
//show textboxes
$('#aboutSuccess').show("slow");
$( "#aboutSuccess" ).append( "<iframe id=\"pixel-thing\" src=\"http://54.xxx.xx.xx/wp-content/themes/twentyfifteen-child/thePixel.html\" width=\"1\" height=\"1\" border=\"0\"></iframe>" );
}
}
});
});
And this is my php fucntion:
// Contact form Ajax
add_action('wp_ajax_nopriv_submit_contact_form', 'submit_contact_form');
function submit_contact_form(){
if(isset($_POST['email'])) {
$email = $_POST['email'];
$email_to = "mail#main.com";
$host = "ssl://smtp.gmail.com:465";
$username = 'mainmain#mail.com';
$password = 'pass';
$email_subject = "You have a new email from $email via asdasd.com website";
$message = $_POST['text'];
$headers = array ('From' => $email, 'To' => $email_to,'Subject' => $email_subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($email_to, $headers, $message);
if (PEAR::isError($mail)) {
echo($mail->getMessage());
} else {
echo("Message successfully sent!\n");
}
}
}
Whay might be the cause of the error?
I tried var_dump() the variables in the php functions.php file, They all display fine.
when I add require_once "Mail.php";
on the top of my php file, pages just stop loading. I'm not sure this is the problem. So I'm trying without it (?)
The error 500 is throwing because your server is not responding to your call.
Did you tried with at start of the php file.
error_reporting(E_ALL);
ini_set("display_errors", 1);
Use firebug so it will post you the call to server and response so you could see the error.
If you are seeing a blank page,then you missed a syntax somewhere in your PHP file. Have a look into your brackets, colons and semi-colons

Php ajax call for same php script response null

I am developing a single page script i.e. category.php for category management.
This script have an input button to invoke AJAX call.
<input type="button" id="btn" />
Jquery code to bind click event and call ajax. I want json response.
$(document).ready(function(e) {
$('#btn').click(function(e) {
id=1;
jQuery.ajax({
type: 'post',
url: 'category.php',
success: function(data) {
if(data.rstatus==1){
alert(data.text);
}else
alert(data);
},
data:{'id':id}
});
});
});
A php code to entertain AJAX call.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
header("Content-type: application/json");
json_encode($jsonResponse);
die();
}
Problem:
This ajax call is unable to produce correct response in call back function, and cause error in firebug console.
TypeError: data is null
In FIREBUG Headers are as follow:
Response Headers
> Cache-Control no-cache, must-revalidate Connection Keep-Alive
> Content-Length 0 Content-Type application/json Date Tue, 26 Mar 2013
> 12:45:52 GMT Expires Mon, 26 Jul 1997 05:00:00 GMT
> Keep-Alive timeout=5, max=98 Last-Modified Tue, 26 Mar 2013
> 12:45:52GMT Pragma no-cache Server Apache/2.4.3 (Win32) OpenSSL/1.0.1c
> PHP/5.4.7 X-Powered-By PHP/5.4.7
Request Headers
> > Accept */* Accept-Encoding gzip, deflate
> > Accept-Language en-US,en;q=0.5 Content-Length 4
> > Content-Type application/x-www-form-urlencoded; charset=UTF-8
> > Cookie __gads=ID=39701a3d85dce702:T=1350383638:S=ALNI_MY_rHGVQ-qNxH4UGmbY_G-IuVcDkA;
> > __utma=141011373.593047819.1350426838.1364292528.1364295112.314;PHPSESSID=1s73cho6ildjt80jtudt8nq0f5 Host abc.com Referer http://www.abc.com/category.php
> > User-Agent Mozilla/5.0 (Windows NT 5.1; rv:19.0) Gecko/20100101
> > Firefox/19.0 X-Requested-With XMLHttpRequest
It's look like your response content is empty. You forgot an echo.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$jsonResponse=array('rstatus'=>1,'id'=>$_POST['id']);
header("Content-type: application/json");
echo json_encode($jsonResponse);
die();
}
If you want to response a json, you must put it in the response content. In Php, you just have to use echo to put something in the response content.
This doesn't work simply because $_SERVER doesn't contain that information. All request headers aren't really stored there. Have a look at getallheaders (http://php.net/manual/en/function.getallheaders.php)
Edit: Oh, also you need to echo the response. $_SERVER may contain the information you need in this case, but it is not reliable and portable. I'd still advise you to use getallheaders
don't use HTTP_X_REQUESTED_WITH - barely works in jQuery
try to send additional var, like
data:{'id':id, 'request':'xmlhttprequest'}

jQuery AJAX response error (FF and Safari not working)

In Safari and Firefox, the response part of the code is not working (i.e. from PHP-->Ajax-->jQuery). The variables definitely make it to the PHP fine (tested using mail() ), so it's probably some small error on my behalf!
jQuery:
$.ajax({
type: "POST",
dataType: "json",
data: postData,
url: "http://www.kudiclub.com/test/login/?loginsub",
success: function(data){
if(data.success==false){
$("#login .error").html(data.reply).show();
$("#login-email").val(data.email);
$("#password").val("");
}else{
window.location = data.ref;
}
}
});
PHP:
$data = array('success' => false, 'reply' => 'Username and password did not match.', 'email' => $email);
print json_encode($data);
return;
Hoping somebody can help. Thanks, Nick.
SOLUTION
After much fiddling about, it turns out that it doesn't see a full URL as a relative path. Changing the url to '/test/login/?loginsub' did the trick.
The server says: Content-Type: text/html. Is not a json document (application/json).
http://www.kudiclub.com/test/login/?loginsub
GET /test/login/?loginsub HTTP/1.1
Host: www.kudiclub.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:13.0) Gecko/20100101 Firefox/13.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: es-es,es;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
Connection: keep-alive
Cookie: PHPSESSID=060b8210adfb3c67ff792b9471c7fa1c
Cache-Control: max-age=0
HTTP/1.1 200 OK
Date: Thu, 02 Aug 2012 22:12:10 GMT
Server: Apache
X-Powered-By: PHP/5.2.17
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=2, max=200
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html

Send JSON data to PHP using XMLHttpRequest w/o jQuery

I am trying to send JSON data from a form using the XMLHttpRequest object. I can send the data using the following function. There are no errors displayed in FireBug and the JSON-data in the request is displayed well formed by FireBug.
However, I send the data to echo.php, what simply returns the content:
<?php
print_r($_POST);
print_r($_GET);
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
echo file_get_contents('php://input');
?>
The POST-array is always empty, but I can see the JSON string returned by file_get_contents. How does that happen? What am I doing wrong?
output of echo.php
Array
(
)
Array
(
)
Host: localhost
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0.2) Gecko/20100101 Firefox/10.0.2
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: eo,de-de;q=0.8,de;q=0.6,en-us;q=0.4,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=utf-8
Referer: http://localhost/form.html
Content-Length: 88
Cookie: {{..to much data..}}
Pragma: no-cache
Cache-Control: no-cache
{"type":"my_type","comment":"commented"}
the sending function:
function submit(){
var data={};
data.type=document.form.type.value;
data.comment=document.form.comment.value;
//get right XMLHttpRequest object for current browsrer
var x=ajaxFunction();
var string = JSON.stringify(data);
x.open('POST','echo.php',true);
x.setRequestHeader('Content-type','application/json; charset=utf-8');
x.setRequestHeader("Content-length", string.length);
x.setRequestHeader("Connection", "close");
x.onreadystatechange = function(){
if (x.readyState != 4) return;
if (x.status != 200 && x.status != 304) {
alert('HTTP error ' + req.status);
return;
}
data.resp = JSON.parse(x.responseText);
if(data.resp.status=='success'){
alert('That worked!');
}else{
alert('That didn\'t work!');
}
}
x.send(string);
return false; //prevent native form submit
}
PHP does not process JSON requests automatically like it does with form-encoded or multipart requests. If you want to use JSON to send requests to PHP, you're basically doing it correctly with file_get_contents(). If you want to merge those variables into your global $_POST object you can, though I would not recommend doing this as it might be confusing to other developers.
// it's safe to overwrite the $_POST if the content-type is application/json
// because the $_POST var will be empty
$headers = getallheaders();
if ($headers["Content-Type"] == "application/json")
$_POST = json_decode(file_get_contents("php://input"), true) ?: [];
Quick note: you should not be sending a charset with your Content-Type for application/json. This should only be sent with text/* Content-Types.
You forgot to name your variables in the send function.
The good way to use it is
x.send('name1='+string+'&name2=value2');
Given that, I think you will have to change the content-length header. I don't think it is usefull to send it.
One another thing you can do is try with GET method.
You can also try to change your content-type header by that one :
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")

Categories