Skip to content

Instantly share code, notes, and snippets.

@creesch
Created October 6, 2012 21:20
Show Gist options
  • Save creesch/3846170 to your computer and use it in GitHub Desktop.
Save creesch/3846170 to your computer and use it in GitHub Desktop.
Reddit api frankenstein wrapper
<?php
/***************************************************************************
* Class name: Reddit
* Description: Frankenstein combination of https://github.com/jcleblanc/reddit-php-sdk
* and https://gist.github.com/3845707
* Goal: Expand on Flotwig's code to be able to use data only avalaible while logged in.
* Usage:
* $reddit->urlApi('message/inbox/')
***************************************************************************/
class reddit{
//private $apiHost = "http://www.reddit.com/api";
private $apiHost = "https://ssl.reddit.com/api";
private $modHash = null;
private $session = null;
/***************************************************************************
* Function: Class Constructor
* Description: Construct the class and simultaneously log a user in.
* API: https://github.com/reddit/reddit/wiki/API%3A-login
* Params: username (string): The username to be logged into
* password (string): The password to be used to log in
**************************************************************************/
public function __construct($username = null, $password = null){
$urlLogin = "{$this->apiHost}/login/$username";
$postData = sprintf("api_type=json&user=%s&passwd=%s",
$username,
$password);
$response = $this->runCurl($urlLogin, $postData);
if (count($response->json->errors) > 0){
return "login error";
} else {
$this->modHash = $response->json->data->modhash;
$this->session = $response->json->data->cookie;
return $this->modHash;
}
}
// Here we use flotwig's heavily modified code to fit it in with the rest of the wrapper
public function urlApi($call,$domain='www.reddit.com') {
$redditurl = 'http://' . $domain . '/' . $call . '.json';
$result = $this->runCurl($redditurl);
return $result;
}
/***************************************************************************
* Function: cURL Request
* Description: General cURL request function for GET and POST
* Params: url (string): URL to be requested
* postVals (NVP string): NVP string to be send with POST request
**************************************************************************/
private function runCurl($url, $postVals = null){
$ch = curl_init($url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_COOKIE => "reddit_session={$this->session}",
CURLOPT_TIMEOUT => 3
);
if ($postVals != null){
$options[CURLOPT_POSTFIELDS] = $postVals;
$options[CURLOPT_CUSTOMREQUEST] = "POST";
$options[CURLOPT_USERAGENT] = "u/creesch";
}
curl_setopt_array($ch, $options);
$response = json_decode(curl_exec($ch),TRUE);
curl_close($ch);
return $response;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment