PHP CURL Reddit API 提交到 Subreddit

PHP CURL Reddit API Submit to Subreddit

我想分享这段代码,因为我发现很难在 Reddit 上找到最新的信息和示例 API;使用 PHP.

这是一个独立的脚本,允许您 post 到任何 subreddit。 您需要在 reddit 上创建一个应用程序并导入您的 clientID 和 clientSeed。我将使用详细指南更新此 post。

<?php

$clientID = '****'; // app client id
$clientSecret = '****'; // app secret 
$redditUsername = '****'; // reddit username 
$redditPassword = '****'; // reddit password

$agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)';

$title = '****'; // post title
$r = '****'; // subreddit to post to 
$kind = '****'; // post type
$url = 'http://example.com'; // url to post
    
$ch = curl_init('https://www.reddit.com/api/v1/access_token?grant_type=password&username=' . $redditUsername . '&password=' . $redditPassword . '');
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_USERPWD, '' . $clientID . ':' . $clientSecret . '');
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
curl_close($ch);

$token = json_decode($return, true);

print_r($token);

$ch = curl_init('https://oauth.reddit.com/api/submit?kind=' . $link . '&sr=' . $r . '&title=' . $title . '&r=' . $r . '&url='.urlencode($url));
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_USERPWD, '' . $clientID . ':' . $clientSecret . '');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Authorization: bearer ' . $token['access_token'] . ''));
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec($ch);
curl_close($ch);
$response = json_decode($return, true);
echo '<br><br>';
print_r($response);

?>