yew pan
yew pan

Reputation: 61

PHP CURL redirect

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

Answers (2)

Quentin
Quentin

Reputation: 943099

There are two HTTP requests here.

  1. From the browser to your PHP
  2. From the PHP to the API

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:

  • Turn CURLOPT_FOLLOWLOCATION off
  • Read the Location header from the response to 2
  • Issue a Location header (with the header() function) in your PHP so that it appears in the response to 1

This 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:

  • Turn CURLOPT_FOLLOWLOCATION off
  • Read the Location header from the response to 2
  • Put that in the body of the response to 1 (which you might be encoding as JSON)
  • Read that response in your JavaScript and use it to set location.href to a new value

Upvotes: 6

Tan Hong Tat
Tan Hong Tat

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

Related Questions