Search code examples
phpcurlreddit

What am I doing wrong here (CURL), no matter what I try it returns empty/null


$url = "http://www.reddit.com/r/{mysubreddit}/new.json";
$fields = "sort=new";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

var_dump($data);

{mysubreddit} is whatever subreddit I wanna check. It works fine to just grab that url via postman, or even in the browser. But when I use PHP/CURL, it returns empty. I've tried replacing the URL, with another URL to another site, and it works fine, so the curl part is working fine.

Is there something with reddit that I have to set? headers? or explicitly tell it for JSON? Or what?

I thought it might have to do with POST, but I tried GET to, still empty/null.

$url = "http://www.reddit.com/r/{mysubreddit}/new.json?sort=new";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);

That doesnt work either


Solution

  • You just need to add:

    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);