Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

351
Visualizações
Symfony2 - file_get_contents() fails on same project api url

I try to execute file_get_contents() on my own route used for AJAX mostly:

file_get_contents($this->router->generate('ajax_get_provinces', array('country' => $country->getName()), true));

I get an error:

Warning: file_get_contents(http://symfony.trainingexperience.org/ajax/get-provinces/Spain): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request

Action:

/**
 * GET method
 *
 * @Route("/ajax/get-provinces/{country}", name="ajax_get_provinces")
 *
 * @param $country
 * @param Request $request
 *
 * @return JsonResponse
 */
public function getProvinces($country, Request $request)
{
    $translator = $this->get('translator');

    if (!$request->isXmlHttpRequest()) {
        return new JsonResponse(array('message' => $translator->trans('ajax.access.error')), 400);
    }

    ...

    return new JsonResponse($provinces, 200);
}
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

This is your problem i would say:

if (!$request->isXmlHttpRequest()) {
    return new JsonResponse(array('message' => $translator->trans('ajax.access.error')), 400);
}

file_get_contents does not set the required headers for the request to be identified as XmlHttpRequest (X-Requested-With)

/**
 * Returns true if the request is a XMLHttpRequest.
 *
 * It works if your JavaScript library sets an X-Requested-With HTTP header.
 * It is known to work with common JavaScript frameworks:
 *
 * @see http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
 *
 * @return bool true if the request is an XMLHttpRequest, false otherwise
 */
public function isXmlHttpRequest()
{
    return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
}

Try executing your request through curl with the correct headers or remove the XMLHttpRequest check in your action.

Here you can read how to make the request through curl: PHP: Simulate XHR using cURL

Edit: To set the required header with file_get_contents you could try this

$options = array(
    'http' => array(
        'header'  =>  "Accept:application/json\r\n" .
                      "X-Requested-With:XMLHttpRequest\r\n",
        'method'  => 'GET'
    ),
);

$context = stream_context_create($options);

file_get_contents($this->router->generate('ajax_get_provinces', array('country' => $country->getName()), true, $context));

This could work if no other headers are missing.

over 4 years ago · Santiago Trujillo Relatório

0

I found this at file_get_contents throws 400 Bad Request error PHP

I quote: You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 
$this->router->generate('ajax_get_provinces', array('country' => $country->getName()), true)); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch);   

// convert response
$output = json_decode($output);

// handle error; error output
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {

  var_dump($output);
}

curl_close($ch);

This may give you a better idea why you're receiving the error. A common error is hitting the rate limit on your server.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda