1

I am a newbie to Symfony 2. I am using Symfony 2.3.

I am using yml files for my routes. I want a certain route to be restricted for Ajax call only. How can I achieve that? I have found one similar question but the solution it suggested is for Symfony 2.4

So please help me how can I achieve it.

Currently I have written conditional code in my controller ajax action something like below, but I do not know how to handle if the call to that route is not through Ajax.

if ($request->isXmlHttpRequest()) {
   // Some operations    
   // Prepare the data array based on the Ajax request.
}

return $this->render('AcmeBundle:Ajax:index.html.twig', array('data' =>  $data));

I want that this route can be accessed only with Ajax else it should throw some exception like invalid route or redirect to some other page.

Thanks in advance.

Community
  • 1
  • 1
Krish Damani
  • 185
  • 2
  • 14

2 Answers2

3

I don't know such a way in symfony 2.3 but in the version 2.4, the below routing configuration can be used to identify ajax requests.

ajax_route:
    path:     /your-ajax-route
    defaults: { _controller: AcmeBundle:Ajax:index }
    condition: "request.isXmlHttpRequest()"

Annotation version of routing can also be used like the following:

/**
 * IndexAction
 *
 * @Route("/your-ajax-route/", name="ajax_route", condition="request.isXmlHttpRequest()")
 */

All the above is only a temporary solution for understanding the ajax request otherwise the headers can be manipulated and you never can identify if the request is xmlhttp. There is no 100% sure way to check the xml http request.

Manish Jangir
  • 5,329
  • 4
  • 42
  • 75
1

First and foremost, Headers can be manipulated. so a curl request with bunch of headers can pull an ajax request. I believe you can check the headers with Symfony 2.3

use Symfony\Component\HttpFoundation\Request;
$request = Request::createFromGlobals();

$ajax = $request->headers->get('HTTP_X_REQUESTED_WITH');
if($ajax != 'xmlhttprequest'){
 throw new \Exception("This is not an ajax request");
}

or you can use $_SERVER['HTTP_X_REQUESTED_WITH'] == "xmlhttprequest"

Rooshan Akthar
  • 401
  • 5
  • 14