Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send ajax request through CURL

An API request needs to be sent. For some reason, the server is blocking CURL request, but it approves an XHR ajax request. I could send an ajax request, but another problem arises - Mixed content my website is served over HTTPS but the request that needs to be sent is over HTTP so I cannot use ajax.

I am looking for a way to simulate ajax request through CURL, in some way, trick the server to believe that the CURL request is indeed an ajax request.

Here's what I have tried.

This is my CURL request.

    $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Linux x86_64)');
        curl_setopt($ch, CURLOPT_REFERER, 'server's url');
        curl_setopt($ch, CURLOPT_AUTOREFERER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Accept:application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding:gzip, deflate',
        'Accept-Language:en-US,en;q=0.9',
        'Connection:keep-alive',
        'Content-Type: application/json; charset=utf-8',
        'X-Requested-With: XMLHttpRequest',
        '__RequestVerificationToken: $token'
        ));
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_COOKIEJAR, base_path().'/cookies.txt');
        curl_setopt($ch, CURLOPT_COOKIEFILE, base_path().'/cookies.txt');
        $buffer = curl_exec($ch);
        if(curl_error($ch))
        {
        $buffer =   curl_error($ch);
        }
        curl_close($ch);

return $buffer;

This curl request is blocked

But, this ajax request goes through my localhost, but since my live website uses HTTPS I cannot really use it.

     $.ajax({
          type: "get",
          xhrFields: { withCredentials:true },
          url: http://apiendpoint.com,
          success: function(data)
          {
           // console.log(data);
          }
    })
like image 222
Dhiraj Avatar asked Jan 11 '18 19:01

Dhiraj


1 Answers

in chrome, you can copy a working curl expression from developer toolbar. Try with that one from cli. If that works, you can figure out which parts are required and which parts are not. Then you can transcript it to php.

developer toolbar -> network -> select a file -> right click - copy -> copy as curl

If you have doubts if the same thing happens from php than from curl, just try it with requestbin.

like image 55
lintabá Avatar answered Oct 19 '22 20:10

lintabá