Reputation: 61
im pretty new in php. Current I'm facing problem about php curl post and redirection. I had wrote plenty of code to connect a cross-domain api. In this API, the response will be redirect my page into another page.
so, now what I'm facing was I can't follow the api response as well. It means in my php scripts, my curl had receive the redirection page web content but my page still remaining.
May I know is php curl can be follow the API redirection?
Is there anyone know how to solve this issue?
Below will be my code.
$url = "http://www.google.com.my"; //example this is an API
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_TIMEOUT, 60);
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, $url);
curl_setopt ($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt ($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_string)));
$result = curl_exec($ch);
$response = curl_getinfo($ch);
curl_close($ch);
In the $result, i had receive the API redirect page. But it is only web content.
Upvotes: 6
Views: 14635
Reputation: 943099
There are two HTTP requests here.
The two requests are independent. They have their own responses and there is no connection between them that you don't create yourself.
If response 2 says "redirect" then that isn't going to automatically make response 1 also say "redirect".
To do that:
header()
function) in your PHP so that it appears in the response to 1This assumes that the response to your request is being shown in the browser directly. i.e. that you were submitting a form in the browser or similar.
If Request 1 was an Ajax request, then redirecting it would just cause the redirected page to be passed to JavaScript. It wouldn't load a new page in the browser. If you want to tell JavaScript to load a new page then:
location.href
to a new valueUpvotes: 6
Reputation: 6864
Set CURLOPT_FOLLOWLOCATION
to true
to make cURL follow a redirect.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
Source: http://php.net/manual/en/function.curl-setopt.php
Upvotes: 9