Detect an ajax request - php

I'm writing my own MVC framework to practice and I have a Request class. I would like to catch the type of request and parse data accordingly whether its an AJAX/JSON call or a HTML/XML request.
Im currently using:
$_SERVER['HTTP_ACCEPT']
and above when used var_dump on it returns application/json for this:
$.ajax({
type: 'post',
url: 'index',
dataType: 'json',
data: {
_method: 'put'
}
});
var_dump($_SERVER['HTTP_ACCEPT']) returns:
string(46) "application/json, text/javascript, */*; q=0.01"
Question:
is this method reliable? Does it work always? Are there any security problems with detecting ajax call like this?
Note that all my ajax calls in my framework must have dataType: 'json' unless its a different type of call like HTML or XML.

Using jQuery, you can use $_SERVER['HTTP_X_REQUESTED_WITH'] which will be set to "XMLHttpRequest." This is the most reliable method when using jQuery.

Colin Morelli answered your main question, but this should help you with your follow ups.
XMLHttpRequest means its an ajax call? How would I detect the type if
its XML or JSON
Yes. XMLHttpRequest is JavaScript object that makes the request. It's poorly named now, though, because you can have it send whatever you want. To answer your second question you'll have to do some sort of parsing attempt on the payload you receive. You can scan for XML and if not found just assume it's JSON and attempt to parse.

Related

When to use header('Content-Type: application/json') in PHP

I've been trying to figure out what's really the usage of header('Content-Type: application/json') in php scripts and I've found different questions and answers on stackoverflow about this subject but I still don't completely get it...
So here's the question : I've seen in some php projects this line of code, and I'm trying to understand
if this is used when another web page is calling this actual script (with ajax for example) so that the calling page can get a json from the php page
OR
if this script means that the php page is going to deal with json sent from another web page. Or maybe something else ???
Another thing that could help me if answered, lately I've been retrieving json from a resource (external url) with cURL and I had to put this header (Content-type:application/json) in the request. Did I send this header to the exertnal resource or was this MY header so that I can deal with the returned json ?
thanks
Ok for those who are interested, I finally figured out that header('Content-Type: application/json') is used when another page is calling the php script, so that the other page can automatically parse the result as json.
For instance i have in my test.php :
header('Content-type: application/json; charset=utf-8');
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
and in my main.js
function test() {
$.ajax({
url: 'test.php',
type: 'GET',
//dataType: 'html',
success: function (response) {
alert(response);
}
});
};
When I dont have dataType set to "json" or when I don't have the header in my test.php, the alert gives {"a":1,"b":2,"c":3,"d":4,"e":5} which is a string (tried with typeof(response), and when I have this header, or dataType:"json", I get [object Object] from the alert. So this header function is there to indicate to the calling pages which type of data it gives back, so that you can know how to deal with it. In my script, if I didn't have header('Content-Type: application/json'), I would have to parse the response in the javascript like this : JSON.parse(response) in order to make it a json, but with that header, I already have a json object, and I can parse it to html with jSON.stringify(response).
You should always set the Content-Type for any HTTP response to describe what you're serving in that response.
Whether it's JSON or something else, and whether it's for an AJAX request or any other kind of request.
You should also set the Content-Type for any request to describe your POST payload.
In PHP, if you don't specify the Content-Type header in the script, it will default to whatever you've configured default-mimetype to be in your php.ini file which is usually text/html.
Calling header('Content-Type: application/json') will override that default setting so that the script will respond with that Content-Type when requested.
Also, when calling curl with a Content-type:application/json header, you're specifying the content type for your request body and not for the expected reponse.
W3 Description For the Content-Type
The purpose of the Content-Type field is to describe the data contained in the body fully enough that the receiving user agent can pick an appropriate agent or mechanism to present the data to the user, or otherwise deal with the data in an appropriate manner.
Shortly speaking, just to inform the receiver what kind of data he received and consume it accordingly.

Angularjs $http post didn't pass param?

I've been debugging this for hours. Tried to set the header etc but no luck!
My controller
$http({
url: 'http://myphp.php/api.php',
method: "POST",
data: {'wtf':'test'}
})
.then(function(response) {
console.log(response);
},
function(response) { // optional
// failed
}
);
and my php
<?php
echo "test";
echo $_POST["wtf"];
?>
In my network tab this is how it look like
Not sure what's wrong man, really exhausted, I'm stuck for hours! Why my $_POST['wtf] didn't echo?
$http is serializing the data to JSON in the request body but PHP's $_POST is looking for key/values parsed from posted form data. These are two different mechanisms for posting data so you need to choose one and use that mechanism on both sides.
You have two options to solve this:
In your PHP code, parse the request body as JSON data and then use that object to retrieve your data. See this StackOverflow question for more information.
Modify your $http request to post the data as form data. See this StackOverflow question for more information.
$http.post (by default) does not send the data as key/value pairs. It sends it as post request.
Therefore, in your php script you should consume it like this:
$input = file_get_contents('php://input');
And then parse it like this:
$data = json_decode($input, true);

Laravel doesn't read HTTP request payload for PUT request

So I am stumbling a bit here, as I have figured out that PHP will not read the HTTP request body from a PUT request. And when the Content-Type header in the request is set to application/json, there doesn't seem to be any way to get the body.
I am using Laravel, which builds their request layer on top of Symfony2's HttpFoundation lib.
I have debugged this a bit with jQuery, and these are some example requests:
Doing a request like this, I can find the content through Input::getContent()
$.ajax({
url: 'http://api.host/profiles/12?access_token=abcdef',
type: 'PUT',
data: {"profiles":[{"name":"yolanda ellis","email":"yolanda.ellis12#example.com"}]}
});
I cannot get the content with file_get_contents('php://input') though. jQuery per default sends the data as application/x-www-form-urlencoded.
It becomes even more mindboggeling when I pass another Content-Type in the request. Just like Ember-Data does:
$.ajax({
url: 'http://api.host/profiles/12?access_token=abcdef',
type: 'PUT',
data: {"profiles":[{"name":"yolanda ellis","email":"yolanda.ellis12#example.com"}]},
contentType: 'application/json'
});
The data seems nowhere to be found, when doing it like this. This means that my Ember.js app does not properly work with my API.
What on earth is going on here?
Edit
Here's a full request example as seen in Chrome DevTools: http://pastebin.com/ZEjDAsmJ
I have found that this is a Laravel specific issue.
Edit 2: Answer found
It appears that there's a dependency in my project, which reads from php://input when the Content-Type: application/json header is sent with the request. This clears the stream—as pointed out in the link provided by #Mark_1—causing it to be empty when it reaches Laravel.
The dependency is bshaffer/oauth2-server-php
You should be able to use Input::json() in your code to get the json decoded content.
I think you can only read the input stream once, so if a different package read the input stream before you, you can't access it.
Are you using OAuth2\Request::createFromGlobals() to create the request to handle your token? You should pass in the existing request object from Laravel, so both have access to the content.
Did you read this? http://bshaffer.github.io/oauth2-server-php-docs/cookbook/laravel/
That links to https://github.com/bshaffer/oauth2-server-httpfoundation-bridge which explains how to create a request object from an httpfoundation request object (which Laravel uses).
Something like this:
$bridgeRequest = \OAuth2\HttpFoundationBridge\Request::createFromRequest($request);
$server->grantAccessToken($bridgeRequest, $response);
So they both share the same content etc.
I found the following comment at http://php.net/manual/en/features.file-upload.put-method.php
PUT raw data comes in php://input, and you have to use fopen() and
fread() to get the content. file_get_contents() is useless.
Does this help?

Custom PHP "API" JSON response jQuery

Im not quite sure how to explain this but im experimenting with creating my own API. At the moment things are working quite well by doing cURL requests or jQuery AJAX requests.
My problem is I see using other APIs that you specify you want a JSON response in the arguments root of the jQuery object. With my API I have to specify I want a JSON response in the data argument. How exactly are APIs picking up this JSON argument? Example:
$.ajax({
url: 'url',
type: 'POST',
data: {dataType : 'json'}, //I need this for PHP to know I want a JSON response
dataType: 'json' //how do other APIs grab this on the API side?
}).
done(function(response){
console.log(response);
});
In PHP I can only pickup the data object VIA $_POST. If I remove the data object from the AJAX request I dont get data back. So what should I do in PHP to pickup the "root" dataType argument to know to return JSON?
<?php echo serialize($_POST) ?>
When you set dataType, jQuery sends that info as part of the Accept header, it probably looks something like this: Accept: application/json, text/javascript, */*; q=0.01.
On the PHP side of things, you can access it with the $_SERVER superglobal:
$accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null;
if ($accept && false !== stripos($accept, 'application/json')) {
// send back JSON
}
If you happen to be using Symfony's HttpFoundation component, it has some nice facilities to deal with Accept headers:
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\AcceptHeader;
$r = Request::createFromGlobals();
$accept = AcceptHeader::fromString($r->headers->get('Accept') ?: '*/*');
if ($accept->has('application/json')) {
// send json
} elseif ($accept->has('application/xml')) {
// send xml
} else {
// send whatever
}

Ajax call with contentType: 'application/json' not working

I have an ajax call, that sends form data to a php function. Since I read a lot that using contentType: 'application/json' is best practice I wanted to give it a try as well. But unfortunately my script doesn't return anything when I use it. If I remove it, the script does what it is supposed to do.
Do you have any idea what the reason might be and why? Thank you!
$('#Form').submit(function(e) {
e.preventDefault();
var content = $(this).serialize() + "&ajax=1";
$.ajax('app/class/controller/contactForm.php', {
type: "POST",
//contentType: 'application/json',
dataType: 'json',
data: content,
success: function(result) {
console.log(result);
}
});
})
and my PHP:
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
echo json_encode(validateForm($_POST));
}
When using contentType: 'application/json' you will not be able to rely on $_POST being populated. $_POST is only populated for form-encoded content types.
As such, you need to read your data from PHP raw input like this:
$input = file_get_contents('php://input');
$object = json_decode($input);
Of course if you want to send application/json you should actually send JSON, which you are not doing. You either need to build the object serialization to JSON directly, or you need to do something like this - Convert form data to JavaScript object with jQuery - to serialize the object from the form.
Honestly in your case, since you are dealing with form data, I don't quite think the use case for using application/json is there.
The best practice you refer to is about the server script setting the Content-Type for JSON to "application/json":
Header('Content-Type: application/json; charset=UTF8');
This is because otherwise a default Content-Type will be sent, often a catch-all text/html, and this could lead to an incomprehension with the client.
If you do not specify yourself a Content-Type in the jQuery request, jQuery will determine the most appropriate one. The problem here is that you were sending a POST form, for which the default Content-Type set by jQuery is application/x-www-form-urlencoded, which tells PHP to decode the data as POST fields and populate $_POST. Your script would have then recovered its parameters from $_POST (or maybe $_REQUEST).
By changing it to application/json, $_POST will no longer be populated, the receiving script operation won't receive the parameters where it was expecting to, and the operation breaks.
So you either need to:
not specify the Content-Type yourself (better, IMHO)
set a Content-Type of application/x-www-form-urlencoded; charset=UTF-8
set a Content-Type of application/json; charset=UTF-8 and modify the script to parse the POST stream and decode the JSON data; see this answer.
The third option requires proper handling of php://input.
The PHP script should be setting the Content-Type header.
if(isset($_POST['ajax']) && $_POST['ajax'] === '1') {
header('Content-Type: application/json');
echo json_encode(validateForm($_POST));
}

Categories