public
Created

Reddit Oauth in PHP

  • Download Gist
cb.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
<?
session_start();
if(isset($_REQUEST['state'])) {
if($_REQUEST['state'] != $_SESSION['state']) {
die("Oy, <a href=\"/reddit\">get yourself a proper state token, noob</a>");
}
} else {
die("Oy, <a href=\"/reddit\">get yourself a state token, noob</a>");
}
 
require_once("../requests/library/Requests.php");
Requests::register_autoloader();
$code = $_GET['code'];
$client_id = "hax";
$client_secret = "morhax";
$access_token_url = "https://oauth.reddit.com/api/v1/access_token";
$options = array('auth' => array($client_id, $client_secret));
$token_request = Requests::post($access_token_url, array(), array("grant_type" => "authorization_code","code" => $code, "redirect_uri" => "PATH TO REDIRECT URL"), $options);
$response = json_decode($token_request->body);
if(!isset($response->error)) {
$headers = array("Authorization" => "bearer ".$response->access_token);
$me = Requests::get("https://oauth.reddit.com/api/v1/me.json",$headers);
$user = json_decode($me->body);
echo "Hello <a href=\"http://www.reddit.com/user/".$user->name."\">".$user->name."</a><br />";
echo "Attempting to post...";
$submitdata = array("thing_id" => "t3_yqfb4","text" => "Wangs. Wangs wangs wangs. ".uniqid());
$post = Requests::post("https://oauth.reddit.com/api/comment",$headers,$submitdata);
$result = json_decode($post->body);
echo "<pre>";
print_r($result);
echo "</pre>";
} else {
echo "Error: ".$response->error;
}
?>
index.php
PHP
1 2 3 4 5 6
<?
session_start();
$state = uniqid();
$_SESSION['state'] = $state;
header("Location: https://ssl.reddit.com/api/v1/authorize?scope=identity,comment&state=".$state."&redirect_uri=YOUR REDIRECT URI&response_type=code&client_id=hax");
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.