0

I want to use cURL to get the JSON response from a public available instagram profile. I'm stuck to the response, because If I try to var_dump the data it will result in nothing, a blank string. Is there something wrong in my code?

$url = 'https://instagram.com/'.$instance['username'].'/?__a=1';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Accept: application/json') );
$data = curl_exec($ch);
curl_close($ch);
var_dump( $url );

The $instance variable is set using a wordpress widget input form and is correct. My problems are only with the curl beahviour.

Thanks for the help

Hossein Zare
  • 580
  • 4
  • 17
sisaln
  • 210
  • 4
  • 16
  • Seems to work fine for me, make sure the `$instance['username']` is actually set and doesn't contain any whitespace and that the profile is public – brombeer Dec 21 '19 at 10:09
  • I've tried using `file_get_contents` and it's working, but with curl not. I'm implementing this inside a wordpress widget on the front-end part of the code. I've vardumped the $url variable and it's set when the request is made, but I can't get a response back. – sisaln Dec 21 '19 at 10:19
  • @kerbholz do you tested it? – sisaln Dec 21 '19 at 10:22
  • 1
    May be worth looking at https://stackoverflow.com/questions/3987006/how-to-catch-curl-errors-in-php and see if there are any errors. – Nigel Ren Dec 21 '19 at 10:26
  • 1
    Yep, tested it, as it is, worked without `CURLOPT_FOLLOWLOCATION` - but the problem seems to be solved anyway. – brombeer Dec 21 '19 at 11:03

1 Answers1

2

The script needs a CURLOPT_FOLLOWLOCATION parameter to be set.

$url = 'https://instagram.com/'. $instance['username'] .'/?__a=1';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json') );
$data = curl_exec($ch);
curl_close($ch);

var_dump($data); // Show the response
Hossein Zare
  • 580
  • 4
  • 17
  • Can you explain to me why please?Thanks for the help – sisaln Dec 21 '19 at 10:24
  • 1
    @sisaln, the `CURLOPT_FOLLOWLOCATION` tells the library to follow any Location: ... read more: https://curl.haxx.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html – Hossein Zare Dec 21 '19 at 10:27