heaven-of-intensity
heaven-of-intensity

Reputation: 117

API has redirecting page - PHP

I need to send data to an API using PHP. The API has a redirect page before showing the final result. The following code shows the content of the redirecting page rather than the final result. How can I wait until the final result?

$url = 'https://example.com/api';
$data = array('text' => "try");

$options = array(
   'http' => array(
    'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
    'method'  => 'GET',
    'content' => http_build_query($data)
    )
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

echo $result;

P.S. I got this code from one of stackoverflow's questions.

Upvotes: 0

Views: 543

Answers (1)

Syscall
Syscall

Reputation: 19780

You could use cURL to get the final response, using CURLOPT_FOLLOWLOCATION:

From documentation :

CURLOPT_FOLLOWLOCATION: TRUE to follow any "Location: " header that the server sends as part of the HTTP header (note this is recursive, PHP will follow as many "Location: " headers that it is sent, unless CURLOPT_MAXREDIRS is set).

$url = 'https://example.com/api';
$data = array('text' => "try");

$full_url = $url . (strpos($url, '?') === FALSE ? '?' : '') 
            . http_build_query($data) ;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $full_url) ;
curl_setopt($ch, CURLOPT_HTTPHEADER, [
     'Content-type: application/x-www-form-urlencoded',
]);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close ($ch);

var_dump($response) ;

Upvotes: 2

Related Questions