Modern, fluent, framework-agnostic Reddit API client for PHP (PSR-18/PSR-7/PSR-3).
Modern, fluent, framework-agnostic Reddit API client for PHP (PSR-18/PSR-7/PSR-3).
avansaber/php-reddit-api
Modern, fluent, framework-agnostic Reddit API client for PHP (PSR-18/PSR-7/PSR-3).
Features
Requirements
php-http/discovery)Installation
composer require avansaber/php-reddit-apiTo run the examples, install a PSR-18 client implementation (discovery will find it):
composer require php-http/guzzle7-adapter guzzlehttp/guzzleGetting Reddit API credentials
https://www.reddit.com/prefs/apps.yourapp/1.0 (by yourdomain.com; contact [email protected]).Quickstart
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();Authentication
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']);
- Using an existing user token:
- Set `REDDIT_ACCESS_TOKEN` and run `examples/me.php`.
Authorization Code + PKCE (with CSRF protection)
- Generate PKCE pair, state parameter, and build the authorize URL. Validate state on callback:
…
Temporary manual Authorization Code exchange (for testing)
```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.phpScopes
| Scope | Description | Used by |
|---|---|---|
| identity | Verify the current user | me() |
| read | Read public data | search(), subreddit(), user(), comments() |
| vote | Vote on posts and comments | links()->upvote(), downvote(), unvote() |
| submit | Submit links or comments | links()->submitText(), submitLink(), reply() |
| edit | Edit posts and comments | links()->edit() |
| save | Save/unsave content | links()->save(), unsave() |
| privatemessages | Send/read private messages | messages()->inbox(), sent(), compose(), markRead() |
| subscribe | Subscribe to subreddits | subreddit()->subscribe(), unsubscribe() |
| modposts | Moderate posts/comments | moderation()->approve(), remove(), lock(), sticky() |
| flair | Manage flair | flair()->setLinkFlair(), setUserFlair() |
Common usage
$listing = $client->search()->get('php', ['limit' => 5, 'sort' => 'relevance']); foreach ($listing->items as $post) { echo $post->title . "\n"; }
- Pagination helper example:
```php
$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]);
- Subreddit info: `$sr = $client->subreddit()->about('php');`
- User info: `$u = $client->user()->about('spez');`
- Voting and replying (requires user-context token with proper scopes):
```php
$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, ]);
- Get comments on a post:
```php
$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]);
- Subscribe/unsubscribe:
```php
$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']);
- Moderation:
```php
$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);
Rate limiting and retries
- Reddit returns `x-ratelimit-remaining`, `x-ratelimit-used`, `x-ratelimit-reset` headers.
- The client parses these headers and exposes the latest via `$client->getLastRateLimitInfo()`.
- The client retries 429/5xx with exponential backoff and respects `Retry-After` when present.
Error handling
- Methods throw `Avansaber\RedditApi\Exceptions\RedditApiException` on non-2xx.
- You can inspect `getStatusCode()` and `getResponseBody()` for details.
HTTP client setup
- By default we use discovery to find a PSR-18 client and PSR-7/17 factories.
- Alternatively, install and wire your own (e.g., Guzzle + Nyholm PSR-7) and pass them to the constructor.
### Framework integration (Laravel, CodeIgniter, etc.)
- Works in any framework as long as a PSR-18 client and PSR-7/17 factories are available (use discovery):
```php
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);Laravel bridge (first-class)
composer require avansaber/avansaber-laravel-reddit-apiphp artisan vendor:publish --tag=config --provider="Avansaber\\LaravelRedditApi\\RedditApiServiceProvider"
php artisan vendor:publish --tag=migrations --provider="Avansaber\\LaravelRedditApi\\RedditApiServiceProvider"
php artisan migrate/reddit/connect, /reddit/callbackREDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET, REDDIT_REDIRECT_URI, REDDIT_USER_AGENT, REDDIT_SCOPESreddit_tokens. Resolve Avansaber\RedditApi\Http\RedditApiClient from the container and call APIs.Laravel (manual wiring, if not using the bridge)
App\Providers\AppServiceProvider → register():…config/services.php:'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])); } ```
For user-context (vote/reply), obtain a user access token (e.g., Socialite Providers: Reddit, or README’s temporary curl step) and call $client->withToken($userAccessToken).
CodeIgniter 4
app/Config/Services.php that returns RedditApiClient using discovery (same as above), then type-hint it in controllers.REDDIT_USER_AGENT, REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET.Examples
examples/app_only_search.phpexamples/me.phpexamples/pkce_auth.phpexamples/voting.phpexamples/pagination.phpexamples/auto_refresh.phpexamples/moderation.phpLaravel
Troubleshooting (403 "whoa there, pardner!")
macos:avansaber-php-reddit-api:0.1 (by /u/YourRedditUsername).Security notes
Contributing
Changelog
CHANGELOG.md. We follow Conventional Commits and tag releases.Security
License
No open issues yet, or sync has not completed.