PHP code example of avansaber / php-reddit-api

1. Go to this page and download the library: Download avansaber/php-reddit-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

avansaber / php-reddit-api example snippets


use Avansaber\RedditApi\Config\Config;
use Avansaber\RedditApi\Http\RedditApiClient;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;

$config = new Config('avansaber-php-reddit-api/1.0; contact [email protected]');
$http = Psr18ClientDiscovery::find();
$psr17 = Psr17FactoryDiscovery::findRequestFactory();
$streamFactory = Psr17FactoryDiscovery::findStreamFactory();

$client = new RedditApiClient($http, $psr17, $streamFactory, $config);
$client->withToken('YOUR_ACCESS_TOKEN');
$me = $client->me()->get();

use Avansaber\RedditApi\Auth\Auth;
use Avansaber\RedditApi\Config\Config;
use Http\Discovery\Psr18ClientDiscovery; use Http\Discovery\Psr17FactoryDiscovery;

$http = Psr18ClientDiscovery::find();
$psr17 = Psr17FactoryDiscovery::findRequestFactory();
$streamFactory = Psr17FactoryDiscovery::findStreamFactory();
$config = new Config('yourapp/1.0 (by yourdomain.com; contact [email protected])');
$auth = new Auth($http, $psr17, $streamFactory, $config);
$accessToken = $auth->appOnly('CLIENT_ID', 'CLIENT_SECRET', ['read','identity']);
  

use Avansaber\RedditApi\Auth\Auth;
use Avansaber\RedditApi\Config\Config;
use Http\Discovery\Psr18ClientDiscovery; use Http\Discovery\Psr17FactoryDiscovery;

$http = Psr18ClientDiscovery::find();
$psr17 = Psr17FactoryDiscovery::findRequestFactory();
$streamFactory = Psr17FactoryDiscovery::findStreamFactory();
$config = new Config('yourapp/1.0 (by yourdomain.com; contact [email protected])');
$auth = new Auth($http, $psr17, $streamFactory, $config);

// Generate PKCE pair and CSRF state token
$pkce = $auth->generatePkcePair(); // ['verifier' => '...', 'challenge' => '...']
$state = Auth::generateState(); // Secure random hex string

// Store state and verifier in session for later validation
$_SESSION['oauth_state'] = $state;
$_SESSION['oauth_verifier'] = $pkce['verifier'];

$url = $auth->getAuthUrl('CLIENT_ID', 'https://yourapp/callback', ['identity','read','submit'], $state, $pkce['challenge']);
// Redirect user to $url

// In your callback handler:
try {
    Auth::validateState($_SESSION['oauth_state'], $_GET['state']); // Throws on mismatch
} catch (\InvalidArgumentException $e) {
    die('CSRF validation failed');
}
$tokens = $auth->getAccessTokenFromCode('CLIENT_ID', null, $_GET['code'], 'https://yourapp/callback', $_SESSION['oauth_verifier']);
// $tokens contains access_token, refresh_token, expires_in, scope
  

$listing = $client->search()->get('php', ['limit' => 5, 'sort' => 'relevance']);
foreach ($listing->items as $post) {
    echo $post->title . "\n";
}
  

$first = $client->search()->get('php', ['limit' => 100]);
foreach ($first->iterate(fn($after) => $client->search()->get('php', ['limit' => 100, 'after' => $after])) as $post) {
    // handle $post (Link DTO) across multiple pages
}
  

$comments = $client->user()->comments('spez', ['limit' => 10]);
$posts = $client->user()->submitted('spez', ['limit' => 10]);
  

$client->links()->upvote('t3_abc123');
$comment = $client->links()->reply('t3_abc123', 'Nice post!');
  

$post = $client->links()->submitText('test', 'My Post Title', 'Post body here', [
    'flair_id' => 'optional-flair-id',
    'nsfw' => false,
]);
  

$result = $client->comments()->get('php', 'abc123', ['sort' => 'top', 'limit' => 50]);
// $result['post'] is a Link DTO, $result['comments'] is an array of Comment DTOs
  

$hot = $client->subreddit()->hot('php', ['limit' => 25]);
$top = $client->subreddit()->top('php', ['t' => 'week', 'limit' => 10]);
  

$client->subreddit()->subscribe('php');
$client->subreddit()->unsubscribe('php');
  

$inbox = $client->messages()->inbox(['limit' => 10]);
$client->messages()->compose('username', 'Subject', 'Message body');
$client->messages()->markRead(['t4_abc123', 't4_def456']);
  

$client->moderation()->approve('t3_abc123');
$client->moderation()->remove('t3_abc123', spam: true);
$client->moderation()->lock('t3_abc123');
$client->moderation()->sticky('t3_abc123', num: 1);
$client->moderation()->distinguish('t1_comment', 'yes', sticky: true);
  

$flairs = $client->flair()->getLinkFlairs('subreddit');
$client->flair()->setLinkFlair('subreddit', 't3_abc123', $flairs[0]->id);
  

use Avansaber\RedditApi\Config\Config;
use Avansaber\RedditApi\Http\RedditApiClient;
use Http\Discovery\Psr18ClientDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;

$http = Psr18ClientDiscovery::find();
$psr17 = Psr17FactoryDiscovery::findRequestFactory();
$streams = Psr17FactoryDiscovery::findStreamFactory();
$config = new Config(getenv('REDDIT_USER_AGENT'));
$client = new RedditApiClient($http, $psr17, $streams, $config);
  

use Avansaber\RedditApi\Config\Config;
use Avansaber\RedditApi\Http\RedditApiClient;
use Http\Discovery\Psr18ClientDiscovery;
use Http\Discovery\Psr17FactoryDiscovery;

public function register(): void
{
    $this->app->singleton(RedditApiClient::class, function () {
        $http = Psr18ClientDiscovery::find();
        $psr17 = Psr17FactoryDiscovery::findRequestFactory();
        $streams = Psr17FactoryDiscovery::findStreamFactory();
        $config = new Config(config('services.reddit.user_agent'));
        return new RedditApiClient($http, $psr17, $streams, $config);
    });
}
    

'reddit' => [
    'client_id' => env('REDDIT_CLIENT_ID'),
    'client_secret' => env('REDDIT_CLIENT_SECRET'),
    'user_agent' => env('REDDIT_USER_AGENT'),
],
    

public function search(\Avansaber\RedditApi\Http\RedditApiClient $client)
{
    // For app-only reads you can fetch a token via Auth::appOnly and call withToken()
    // $token = ...; $client->withToken($token);
    return response()->json($client->search()->get('php', ['limit' => 5]));
}
    
bash
composer 
bash
composer 
bash
# After you obtain ?code=... from the authorize redirect
curl -A "macos:avansaber-php-reddit-api:0.1 (by /u/YourRedditUsername)" \
  -u 'CLIENT_ID:CLIENT_SECRET' \
  -d 'grant_type=authorization_code&code=PASTE_CODE&redirect_uri=http://localhost:8080/callback' \
  https://www.reddit.com/api/v1/access_token

export REDDIT_USER_AGENT="macos:avansaber-php-reddit-api:0.1 (by /u/YourRedditUsername)"
export REDDIT_ACCESS_TOKEN=PASTE_ACCESS_TOKEN
php examples/me.php
bash
    php artisan vendor:publish --tag=config --provider="Avansaber\\LaravelRedditApi\\RedditApiServiceProvider"
    php artisan vendor:publish --tag=migrations --provider="Avansaber\\LaravelRedditApi\\RedditApiServiceProvider"
    php artisan migrate