Can't access the PHP external API when calling from another page in the same domain?

I am trying to make several cross-site scripts using Jquery and PHP / Symfony ( HttpFoundationComponent), but I can not get the server to return the necessary data.

My goal is for jQuery to retrieve JSON from the local domain: PHP by accessing an external API server. I opened the header Access-Control-Allow-Originup *to let CORS work fine and everything works fine with dummy data. However, using the JSON endpoint through jQuery fails. Everything happens in one domain.

So, this dummy JSON data looks great if I manually create a JSON response:

$data = json_decode('{
        "foo": "bar",
        "items": [
            {
                "id": "1234",
                "foo": "bar",
                "baz": "bingo",
            },
            {
                "id": "4567",
                "foo": "blork",
                "baz": "fladdurk",
            }
    }', true);

$response = JsonResponse::create($data, 200);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->send();

JSON http://localhost/json_endpoint?q=stuff. JSON:

{"foo":"bar","items":[{"id":"1234","foo":"bar","baz":"bingo"},{"id":"4567","foo":"blork","baz":"fladdurk"}]}

JQuery . , ; Symfony JSON, API.

, PHP- API ( ):

protected function url_tools__request($url, $timeout=10, $headers=array()) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //suppress output.
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $ch_exec = curl_exec($ch);
    curl_close($ch);
    return $ch_exec;
}

$url = "http://api.example.com/?q=more+stuff";
$headers = array("Accept:application/json");

$xsr = $this->url_tools__request($url, 10, $headers);
$data = [
    "foo" => "bar",

    // here the rub
    "items" => json_decode($xsr, true),
];

$response = JsonResponse::create($data, 200);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->send();

http://localhost/json_endpoint?q=stuff. , API . ​​ JSON, :

{"foo":"bar","items":[{"id":"1234","foo":"bar","baz":"bingo"},{"id":"4567","foo":"blork","baz":"fladdurk"}]}

JQuery AJAX (, http://localhost/another_page.html), JSON - "":

{"foo":"bar","items":[]}

JQuery :

xhr = $.ajax({
    url: '/json_endpoint',
    data: {q: "more+stuff"},
    type: "GET",
    dataType : "json"
})
.done(function(data, textStatus, request) {
    console.log(data)
}

, , PHP/Symfony, , (XSS) . , - .

, ? .

+4
1

, CORS .

JQuery URL- , PHP . - CORS; .

, URL- :

$url = "http://api.example.com/?q=stuff";

URL-, . :

$url = "http://api.example.com/?q=more+stuff";

JQuery :

more%sBstuff

... PHP. , :

$url = urlencode($request->get('q'));

urldecode

$query = urlencode(urldecode($request->get('q')));

. , - - .

+1

Source: https://habr.com/ru/post/1660549/


All Articles