- Detecting AJAX requests with PHP.
- Spoofing AJAX requests with PHP.
- Проверка ajax запрос php
- Фильтрация данных с помощью zend-filter
- Контекстное экранирование с помощью zend-escaper
- Подключение Zend модулей к Expressive
- Совет: отправка информации в Google Analytics через API
- Подборка PHP песочниц
- Совет: активация отображения всех ошибок в PHP
- Detect an AJAX Request in PHP
- Recent Features
- Creating Scrolling Parallax Effects with CSS
- I’m an Impostor
- Incredible Demos
- jQuery Wookmark
- Unicode CSS Classes
- Discussion
Detecting AJAX requests with PHP.
This is a guide on how to detect AJAX requests with PHP.
Please note that there is NO sure-fire way of detecting AJAX requests. This is because it is extremely easy to spoof HTTP headers.
In other words, do NOT rely on this code for security.
In the vast majority of cases, JavaScript frameworks and libraries such as JQuery will automatically add the X-Requested-With header to their HTTP requests.
If you use Chrome Developer tools to inspect the AJAX requests that they send, you will find that they set the X-Requested-With header to “XMLHttpRequest“:
X-Requested-With: XMLHttpRequest
This means that you can detect AJAX requests with PHP by checking the HTTP_X_REQUESTED_WITH value in the $_SERVER superglobals array.
Here is a PHP code sample.
As I said above, you cannot trust this header, as the client can easily set the “xmlhttprequest” value to anything that they want to.
Spoofing AJAX requests with PHP.
Let’s take a look at how easy it is to fake / simulate an AJAX request using cURL and PHP.
"XMLHttpRequest" )); //Execute the request. curl_exec($ch);
See how easy that was? In this case, we were able to change the “X-Requested-With” header to “XMLHttpRequest” using the CURLOPT_HTTPHEADER option.
If I wanted to, I could also spoof the referrer field or modify the User Agent so that the server is fooled into thinking that my simulated XHR request came from a browser.
So be warned! Do not use this type of check for security purposes.
Проверка ajax запрос php
В этом разделе помещены уроки по PHP скриптам, которые Вы сможете использовать на своих ресурсах.
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
Совет: активация отображения всех ошибок в PHP
При поднятии PHP проекта на новом рабочем окружении могут возникнуть ошибки отображение которых изначально скрыто базовыми настройками. Это можно исправить, прописав несколько команд.
Detect an AJAX Request in PHP
I like using the same PHP script for both AJAX and non-AJAX content requests. Using one script just makes everything easier because it’s only one file to update/edit and it’s one more cache-able request. One way to try detect an AJAX request (as opposed to a regular page load) is by using the following PHP code:
/* decide what the content should be up here . */ $content = get_content(); //generic function; /* AJAX check */ if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') < /* special ajax here */ die($content); >/* not ajax, do more. */
$_SERVER[‘HTTP_X_REQUESTED_WITH’] is the golden ticket but not all servers provide this variable so having other checks in place will be important.
Recent Features
Creating Scrolling Parallax Effects with CSS
I’m an Impostor
Incredible Demos
jQuery Wookmark
Unicode CSS Classes
Discussion
Gosh, David! Your commenting system sucks. Can’t even post the NAME of the var (without dollar sign and stuff…). Anyway, this is just set by jQuery, isn’t it?
You could spoof that header remotely. This works fine as a rudimentary check, but shouldn’t be relied on for security purposes.
You shouldn’t rely on any kind of check for security issues. Using different urls is just as fragile and can be spoofed too. But why at all would you write a security check based on whether a request is an Ajax request or not?
“This url is an ajax webservice – direct access is denied”. Think of it as an additional layer. Edit: two years later, and for the record
$http.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
Yeah I felt really dumb when I found about this one a few month ago. All this time I had been using javascript to add an extra parameter to queries which I would test for on the server side. Still works, but not nearly as simple as this one
HTTP_X_REQUESTED_WITH is sent by ALL recent browsers supporting ajax requests 😉
it’s the comment field used to check is request is standard or xhttprequest
Is this guarenteed to work. The frameworks may all send it but can you get round it with raw javascript.
I don’t think it has anything to do with frameworks. it’s just sent with any ajax request generated by the browser
I know dojo doesn’t sends it (but I could be wrong) You will have to do something like this to work in dojo:
Very nice post, thanks for sharing! I’m a huge fan of the blog, really like the design and you’ve got some great content on here. If you’d be interested, I’d love to have an interview with you on my web 2.0 blog. Just let me know if you’re interested – http://www.insidethewebb.com/
Very nice ! I didn’t know about this. That’s going to be very helpfull !
Just a question about your if statement. I never understood why people made double checks like this one:
if(!empty($var) && $var == “Hello World”)
Why not just check it like this:
if($var == “Hello World”)
Isn’t it exactly the same, or even better for performance ?
Thanks and again, great article !
No, empty($undeclared) does not trigger a notice, and that’s part of its point. I use empty() all the time to check if something has been set/provided.
ok… Shame on me… xD
It has become a reflex to use if(isset()), I guess that’s why I forgot why it was necessary 😉
So if you’re using this do you think its time to stop supporting people with javascript turned off? I still see lots of people supporting it.
@Dev Words: yes, stop if you want to leave Google out of the door. 🙂
However, it seems that Dojo sends this header since Zend Framework components check for X-Requested-With and dojo has a out-of-the-box integration with ZF.
Be careful when using the same URL for AJAX and non-AJAX requests. This could cause some strange behavior at a proxy cache on the client’s network. Imagine if a proxy cache were to cache your AJAX response when one user was interacting with your application, and then another user behind the same proxy cache goes to access your application. He’ll see the AJAX response instead of the markup for your application. You can discourage caching by sending the appropriate cache control headers, but I’ve seen proxy caches that seem to ignore these directives, so you might get some undesired caching anyway…
This is a good idea to implement, but isn’t something i would rely when it comes to security. Remember that client headers can be faked to look like something else. However this is just one more thing to kink the system when being attacked.
Like Jonathan Yarbor said. Only use this for user-friendliness, never use it for security purposes as everything sent by client can be faked easily nowadays.
Looks like jQuery doesn’t send back HTTP_X_REQUESTED_WITH on 302 redirections (eg : php function header(‘Location: page.php’) ) occuring on $.load() calls. So be carefull with automatic redirections in your code… Does anyone knows a way to forward HTTP_X_REQUESTED_WITH even through redirections ?
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
The condition would fail under IE7.
It appears that IE7 doesn’t recognize the header.
IE needs to say hello to the 21st century 🙂
@Ben: That maybe so but unfortunately, they seem to stick to their own standards which leads to bad practice such as CSS hacks for example.
It seems as though IE7 not recognizing the header may be cache related.
I need to investigate this more.
@scvinodkumar, like 10 other people before me i’ll say that this header is sent by the javascript framework with which you’re making the ajax call. You can’t ‘enable’ it in your server, the js framework does…
That’s awesome.
Just used it on a website I’m making at the moment (mine) Works great with Drupal templates.
Just to make sure everyone’s aware this header can be spoofed from another site or within the certain browser extensions. it’s not an end all be all, it’s just a rudimentary check.
Very true fleh, but the worst thing that can happen, in this example, would be just outputting contentHTML and not the wrapping code.
The best solution for this would be to just add a parameter say:
if (isset($_GET[‘ajax’]) && $_GET[‘ajax’] == TRUE) // Process AJAX request
> else // Process non-AJAX request
>
This should also prevent the cache problem Jason spoke of as using a new URL parameter requires the page to be reprocessed due to the browser being unable to determine what is going on in the server.
By default, ajax using header: Accept:application/json, text/javascript, */*
and not ajax have header like Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
css header: Accept:text/css,*/*; it depending file your request. If you using php framework like CodeIgniter, you can use $this->input->is_ajax_request() . See http://codeigniter.com/user_guide/libraries/input.html By the way, $_SERVER[‘HTTP_X_REQUESTED_WITH’] is best way for detecting ajax request.
Dont use jquery or other large frms only to manage ajax, much better to use what ONLY what you need, for example ajax is a simple function, for ajax i prefer Jxs at openjs.com
I was not aware of the existence of $_SERVER[‘HTTP_X_REQUESTED_WITH’]
but…..
i do not see the value of using it.
For security reasons i am completely paranoid about ANY data from the outside world.
So i consider every outside value as a an attack on my websites. So i dont care HOW i got an outside value, i just check everything if it is what i expect it should be, i just never trust my visitors, they are my enemies. Always trying to destroy my hard work,but at the end i love them:) So, i am an heavy user of isset() , ctype_xxx() and for database security prepared statement . lesson 1: don’t care HOW you data came in, JUST BE PARANOID OF YOUR LOVELY VISITORS!
I’m seeing a few different topics mixed here so after working with this *header* and diffferent libraries for a while now I’d like to comment as follows:
(1) X-Requested-With is a header that’s being set (by consensus of their respective developers) by most high profile JS libraries and frameworks. I found it documented for jQuery, YUI 2/3, mootols and dojo. “the net” seems to agree that jQuery had the idea first. IF it is set, it’s content should be “XMLHttpRequest” and the PHP runtime will make it available as $SERVER[‘X-Requested-With’]
(2) It’s NOT set by any current browser to denote a request as coming from an XMLHttpRequest object or IE-pre-7 ActiveX pendant. Which means there is no browser configuration for this. It’s between your JS framework of choice and your server script.
(3) There is a relevant caching issue here because IE agressively (and by default) caches AJAX requests. Detecting such AJAX requests and setting appropriate caching headers is a browser-agnostic solution to this (Firefox and WebKit based browsers just happen to handle this the way most developers want them to) and is widely considered the most appropriate solution, rather than manually appending superfluous request parameters.
(4) Simply testing a request for a header can hardly be considered a security issue. The issue arises when it comes to what your code does with that request. Which is where https, cookie encryption and responsible right lease handling come in. But that’s actually a very different issue.
Just curious – does anybody know if there’s a reason to lowercase the response? I haven’t checked extensively but in all cases I’ve seen where the header is sent, it’s always been capitalized in the exact same way («XMLHttpRequest») ..