Reddit API with PHP



In this post we are going to connect to the Reddit API using PHP. We will create a Reddit App, get an access token, and post to a subreddit with a PHP script using the Reddit API.

Step 1: Create a Reddit App

Before we can start coding, we need to create a Reddit App. No Reddit App, no API access. In order to connect to the Reddit API you need a client id, client secret, username, and password. To get these things you need a Reddit app.

  1. Login to reddit and go to https://reddit.com/prefs/apps.
  2. 2Under “developer applications” click “create app”.
  3. Fill out the app info like the image below and click “create app”. Make sure to select “script” as well. You don’t need to enter an “about url” but a “redirect url” is required. You can enter anything for the “redirect url” as we will not be using it at all.Create Reddit App
  4. Once your app is created you should see it listed under “developer applications” like the image below. From here we can get our client id, client secret, username, and password, for connecting to the app.Reddit App

 

Step 2: Obtain an Access Token

To make calls to the Reddit API we need an access token. That access token will then be passed along with each API call we make. Without the access token, any API call we try to make will fail. The code below will connect to the access_token endpoint on Reddit and give us an access token if we pass along the right parameters. We need to pass along our username, password, client id, and client secret. The client id and client secret come from the Reddit App created in the first step.

// reddit username
$username = 'YOUR-REDDIT-USERNAME';

// reddit password
$password = 'YOUR-REDDIT-PASSWORD';

// client id
$clientId = 'YOUR-REDDIT-APP-CLIENT-ID';

// client secret
$clientSecret = 'YOUR-REDDIT-APP-CLIENT-SECRET';

// post params 
$params = array(
    'grant_type' => 'password',
    'username' => $username,
    'password' => $password
);

// curl settings and call to reddit
$ch = curl_init( 'https://www.reddit.com/api/v1/access_token' );
curl_setopt( $ch, CURLOPT_USERPWD, $clientId . ':' . $clientSecret );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $params );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );

// curl response from reddit
$response_raw = curl_exec( $ch );
$response = json_decode( $response_raw );
curl_close($ch);

// display response from reddit
var_dump( $response );

The “var_dump( $response )” in the code above should give you an array of data back from Reddit including an access token and token type. Your response should look like the image below.

Reddit Access Token

 

Step 3: Post To A Subreddit

To post to a subreddit through the API the subreddit has to have the correct permissions for your user. For testing purposes I would suggest you just create a new subreddit at https://www.reddit.com/subreddits/create and use it for your own testing with the API. Note you do need to have some karma before you can create a subreddit.

The code snippet below will post a link to a subreddit. Step 2 gave us our access token and token type. Those need to be filled in in the code below in order for the call to go through. The subreddit post data also needs to be filled in with the post title, post url, and subreddit name, subreddit display name, and username.

// access token
$accessToken = 'ACCESS-TOKEN';

// access token type
$accessTokenType = 'ACCESS-TOKEN-TYPE';

// reddit username
$username = 'YOUR-REDDIT-USERNAME';

// subreddit name (no spaces)
$subredditName = 'SUBREDDIT-NAME';

// subreddit display name (can have spaces)
$subredditDisplayName = 'SUBREDDIT-DISPLAY-NAME';

// subreddit post title
$subredditPostTitle = 'SUBREDDIT-POST-TITLE';

//subreddit post url
$subredditUrl = 'SUBREDDIT-POST-URL';

// api call endpoint
$apiCallEndpoint = 'https://oauth.reddit.com/api/submit';

// post data: posting a link to a subreddit
$postData = array(
    'url' => $subredditUrl,
    'title' => $subredditPostTitle,
    'sr' => $subredditName,
    'kind' => 'link'
);

// curl settings and call to post to the subreddit
$ch = curl_init( $apiCallEndpoint );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, $subredditDisplayName . ' by /u/' . $username . ' (Phapper 1.0)' );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array( "Authorization: " . $accessTokenType . " " . $accessToken ) );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $postData );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, FALSE );

// curl response from our post call
$response_raw = curl_exec( $ch );
$response = json_decode( $response_raw );
curl_close( $ch );

After running the post to reddit script above, check the subreddit  and make sure the post worked! Here is a screenshot of my successful Reddit post!

Reddit Post

We have successfully posted to Reddit with PHP using their API! Here are some helpful links relating to this blog post.

YouTube Video

Code on GitHub

Reddit API Documentation

That is going to do it for this post! Leave any comments/questions/concerns below and thanks for stopping by the blog!

283 comments

  1. Wow, amɑᴢing Ƅⅼog layout! How lengthy haѵe yoս ever been running a blog fоr?

    yoս mаke running a blog glance easy. The overall glance of
    your web sіte іѕ magnificent, as neatly as the content materiаl!

    my web blog; inmate texting

  2. Everyting is very open wirh a vewry clear clarification of thhe issues.

    It waas really informative. Youur ebsite iss extremely helpful.
    Thanks foor sharing!

  3. excellent points altogether, you just won a logo new reader.What may you recommend about your submit that you made afew days ago? Any certain?Review my blog – tillernatural.com

  4. Heya just wantdd to give yyou a brief heads up and let you knowa few oof the pictures aren’t loading correctly.I’m not sure why but I thjnk its a linking issue.I’ve trtied it in two different internet browsers and both show the sameoutcome.

  5. Hey there! I’m at work surfing around your blog from my new iphone 4!Just wanted to say I love reading your blog and look forward toall your posts! Keep up the fantastic work!

  6. I’d need to verify with you here. Which is not one thing I normally do! I enjoy studying a submit that can make individuals think. Also, thanks for allowing me to comment!

  7. Good blog you have got here.. Itís difficult to find high-quality writing like yours these days. I honestly appreciate individuals like you! Take care!!

  8. Hola! I’ve been following your blog for a while now and
    finally got the bravery to go ahead and give you a shout out from Atascocita Tx!
    Just wanted to tell you keep up the fantastic job!

  9. Hi there, its good piece of writing on the topic of media print, we all know mediais a wonderful source of information.

  10. Hi there, just turned into aware of your weblog via Google, and located that it is truly informative. I am gonna be careful for brussels. I will be grateful in the event you proceed this in future. A lot of people can be benefited from your writing. Cheers!

  11. Hi my loved one! I want to say that this article is awesome, great written and come with approximately all vital infos. I’d like to look extra posts like this .

  12. I liked as much as you will receive performed right here. The comic strip is tasteful, your authored material stylish. nonetheless, you command get got an nervousness over that you want be turning in the following. sick definitely come more until now once more as exactly the same just about a lot often inside case you shield this hike.

  13. Hello there, You’ve done an incredible job. I will definitely digg it and personally suggest to my friends. I’m sure they will be benefited from this site.

  14. Hello, i think that i saw you visited my blog thus i came to “return the favor”.I’m trying to find things to enhance my site!I suppose its ok to use a few of your ideas!!

  15. What’s Happening i am new to this, I stumbled upon this I have found It absolutely helpful and it has helped me out loads. I hope to contribute & help other users like its helped me. Good job.

  16. It’s a pity you don’t have a donate button! I’d certainly donate to this fantastic blog! I guess for now i’ll settle for bookmarking and adding your RSS feed to my Google account. I look forward to fresh updates and will share this site with my Facebook group. Talk soon!

  17. Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains. If you know of any please share. Appreciate it!

  18. This is really attention-grabbing, You are an excessively skilled blogger. I have joined your rss feed and look forward to in search of more of your excellent post. Additionally, I’ve shared your site in my social networks!

  19. Hello, after reading this amazing piece of writing iam also delighted to share my familiarity here with friends.Feel free to surf to my blog … car repair woodbridge

  20. Thanks , I’ve recently been searching for info about this topic for ages and yours is the best I have discovered so far. But, what about the bottom line? Are you sure about the source?

  21. Aw, this was an exceptionally nice post. Spending some time and actual effort to make a superb article… but what can I say… I put things off a lot and never manage to get anything done.

  22. Whoah this blog is magnificent i really like reading your articles. Keep up the good paintings! You realize, a lot of persons are searching round for this information, you could aid them greatly.

  23. An interesting discussion is definitely worth comment. I believe that you need to write more on this subject matter, it may not be a taboo subject but generally people don’t talk about such topics. To the next! Cheers!!

  24. A motivating discussion is definitely worth comment. I think that you should publish more on this issue, it might not be a taboo matter but usually people don’t discuss these issues. To the next! Kind regards!!

  25. I like the valuable info you supply for your articles.I’ll bookmark your blog and take a look at once more hereregularly. I’m relatively certain I will be told plenty ofnew stuff proper here! Good luck for the following!

  26. I love what you guys are usually up too. This kind of clever work and exposure!Keep up the good works guys I’ve incorporated you guys to my own blogroll.

  27. Hey there are using WordPress for your blog platform? I’m new to the blog worldbut I’m trying to get started and create my own. Do you require any coding expertiseto make your own blog? Any help would be really appreciated!

  28. Excellent blog you’ve got here.. Itís hard to find good quality writing like yours nowadays. I truly appreciate individuals like you! Take care!!

  29. That is a really good tip especially to those new to the blogosphere. Short but very precise information… Thank you for sharing this one. A must read article.

  30. I like the helpful information you provide in your articles. I will bookmark your blog and check again here regularly. I am quite sure I will learn many new stuff right here! Best of luck for the next!

  31. Aw, this was an exceptionally good post. Taking a few minutes and actual effort tomake a superb article… but what can I say… I put things off a lot and don’t manage to get anything done.

  32. It as hard to come by well-informed people for this topic, however, you sound like you know what you are talking about! Thanks

  33. Generally I do not read article on blogs, but I would liketo say that this write-up very forced me to try and do so!Your writing style has been amazed me. Thanks, quite nice article.

  34. Xoilac Tv Trực Tiếp đá Bóng 12betĐội tuyển nước Việt Nam chỉ cần thiết một kết quả hòa có bàn thắng nhằm lần loại hai góp mặt tại World Cup futsal. Nhưng, để làm được điều này

  35. Your style is unique compared to other people I have read stuff from.Many thanks for posting when you have the opportunity, Guess I will just bookmark this blog.

  36. I do trust all of the concepts you’ve introduced to your post. They’re really convincing and can definitely work. Still, the posts are very quick for novices. May you please lengthen them a little from subsequent time? Thanks for the post.

  37. hello!,I love your writing very a lot! percentage we keerp upa correspondence more approximately your article on AOL?I need an expert on this space to unravel my problem. Maybe that’s you!Haviing a look forward to see you.

  38. Generally I don’t learn article on blogs, but I wish to say thatthis write-up very forced me to take a look at and do it!Your writing style has been amazed me. Thanks,quite great post.

  39. Very great post. I simply stumbled upon your blog and wanted to mention that I’ve really enjoyed surfing around your blog posts. In any case I will be subscribing in your rss feed and I am hoping you write once more very soon!

  40. Whats Taking place i’m new to this, I stumbled upon this I’ve discovered It positively helpful and it has aided me out loads. I am hoping to give a contribution & assist other customers like its helped me. Good job.

  41. Howdy! I know this is somewhat off topic but I was wondering if you knew where Icould get a captcha plugin for my comment form?I’m using the same blog platform as yours and I’m having difficulty finding one?Thanks a lot!

  42. This is a very good tip particularly to those fresh to the blogosphere. Brief but very accurate info… Thanks for sharing this one. A must read post!

  43. scoliosisHi there! I simply would like to offer you a big thumbsup for your excellent info you have got right here on this post.I’ll be coming back to your blog for more soon. scoliosis

  44. Howdy! I could have sworn I’ve visited this website before but after browsing through many of the posts I realized it’s
    new to me. Anyhow, I’m certainly happy I discovered it and I’ll be book-marking it and checking back frequently!

  45. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several e-mails with thesame comment. Is there any way you can remove people from that service?Thanks a lot!

  46. Oh my goodness! Impressive article dude! Thanks, However I am having difficulties with your RSS. I donít know why I can’t join it. Is there anybody else having the same RSS problems? Anyone who knows the solution will you kindly respond? Thanx!!

  47. I wanted to thank you for this great read!! I absolutely enjoyedevery little bit of it. I have you bookmarked to check out newstuff you post?Review my blog … clubriders.men

  48. Nice post. I learn something new and challenging on sites I stumbleupon everyday.

    It will always be exciting to read articles from other authors and practice
    a little something from other websites.

  49. Good day! This is my first visit to your blog! We are a group of volunteers and starting a new project in a community in the sameniche. Your blog provided us valuable information to work on. Youhave done a marvellous job!

  50. I do not even know how I ended up here, but I thought thispost was good. I do not know who you are but definitely you’re going toa famous blogger if you are not already 😉 Cheers!

  51. Great post and right to the point. I don’t know if this is truly the best place to ask but do you folks have any thoughts on where to hire some professional writers? Thanks 🙂

  52. Thanks a lot for sharing this with all folks you
    actually know what you are talking approximately!
    Bookmarked. Please additionally seek advice from my website =).
    We will have a hyperlink trade contract among us

  53. An interesting discussion is worth comment. I think that you should publish more on this subject, it may not be a taboo subject but usually people don’t discuss these issues. To the next! Cheers!!

  54. Hi, I do think this is a great blog. I stumbledupon it 😉 I may revisit once again since i have book marked it. Money and freedom is the best way to change, may you be rich and continue to guide others.

  55. I do agree with all the concepts you’ve introducedin your post. They are really convincing and will certainly work.Nonetheless, the posts are too short for starters.Could you please lengthen them a little from subsequent time?Thanks for the post.

  56. Good day! Do you know if they make any plugins to help withSearch Engine Optimization? I’m trying to get my blog to rankfor some targeted keywords but I’m not seeing verygood gains. If you know of any please share. Kudos!

  57. hello!,I like your writing so much! share
    we keep up a correspondence more approximately your post on AOL?

    I need an expert on this area to unravel my problem.
    Maybe that is you! Looking ahead to peer you.

  58. great put up, very informative. I wonder why the other experts of this sector do not realize this. You should continue your writing. I am confident, you have a huge readers’ base already!

  59. Thanks for helping out, fantastic information. “Our individual lives cannot, generally, be works of art unless the social order is also.” by Charles Horton Cooley.

  60. I am often to blogging and i really appreciate your content. The article has really peaks my interest. I am going to bookmark your site and keep checking for new information.

  61. Hey there! I could have sworn I’ve been to this site before but after reading through some of the post I realized it’s new to me.
    Anyways, I’m definitely delighted I found it and I’ll be bookmarking and
    checking back frequently!

  62. This pumping helps to take care of long-lasting
    pumps with glucose and oxygen which is rapidly delivered to the
    muscle tissue. Some of the most effective legal steroid alternate options in the marketplace come
    from manufacturers like Crazy Bulk and Flexx Labs.

    These include Crazy Bulk’s D-Bal, Testo-Max, Trenorol, Anadrol, and the Crazy Mass finest complement for muscle mass.

    Flexx Labs additionally has aggressive alternate options, Dianabol,
    and the slicing stack. By and large alluded as D-bol in bodybuilding
    circles, Dianabol steroid goes probably as varied physique processes concurrently to
    assist muscle creation and fat reduction.
    Trenbolone is an exceptionally androgenic steroid, with
    restricting to the Androgen Receptor in the space of quite a few events as high as testosterone.
    Trenbolone is perhaps the most outstanding steroids out
    there at present and might lead fast muscle achieve.
    Trenbolone greatest different is Trenorol in Thailand from “Loopy Bulk Thailand”.
    There are many people who are happy to utilize Trenorol
    for varied benefits without any unhealthy side effects..

    Cray Bulk NO2 Max is a top quality muscle constructing complement
    in South Africa for better power, endurance, and faster muscle restoration.
    It is formulated with pure Tribulus terrestris focus to increment luteinizing hormone
    creation and raises testosterone ranges which helps in choosing up quality, bulk, vitality
    and performance. Quite A Few People are stuned to experience the results of “Testo-Max”.
    The nature of HGH Releaser are known in steps on the human progress hormone fuel, beginning up muscle progress and consuming fats shops for
    an even bigger, much less fatty edge and quickened recovery instances.
    The powerful combine and novel detailing of HGH-X2 drives t quality and slender muscle features.
    It additionally helps in fast fats burning and quick recovery time.
    HGH Booster likewise has the character of consuming
    the put away fats in the physique. Crazy Bulk is an organization that has been within the
    bodybuilding legal supplements industry since 2004.
    Gynectrol addresses this by boosting testosterone and lowering estrogen, creating a better overall hormonal balance.
    Many mix totally different Loopy Bulk merchandise for even better
    results. This technique guarantees protected purchases, enhancing purchaser
    satisfaction. Clear insurance policies additionally boost belief, making Loopy
    Bulk a prime pick for safe, effective, and legal complement options.
    Loopy Bulk is a standout in health dietary supplements because of
    its legal compliance and strict oversight.

    It could naturally improve testosterone ranges, improving stamina, power and endurance.
    This ingredient is commonly present in sexual enhancement merchandise, for its effect on male sexual performance.

    The outcomes of 1 studystudy[6] on men confirmed important enhancements in erections and sexual satisfaction with Tribulus Terrestris.
    The products increase performance at the gym, allowing the consumer to maximize workouts, and pace up recovery.
    CrazyBulk has been a leader within the field of pure muscle-strengthening
    dietary supplements for over a decade now. I actually
    have tried this product for a couple of weeks and have
    determined to write a review already as I am seeing
    seen results which must imply that it works.
    Complementary to D-Bal and Testo-Max was the ‘Ultimate
    Fitness Stack’, armed with protein powder, pre-workout, and creatine complement.
    This trio was poised to optimize every facet of my muscle-building—from supporting protein synthesis to enhancing exercise efficiency.
    I was on the cusp of possibly reshaping my physique more profoundly than I may have achieved through weightlifting alone.

    Like many other anabolic steroids, Sustanon is often injected into the bloodstream for effective outcomes.
    These authorized have been researched to just do the same and they are more highly
    effective than another products available available in the market.
    Our merchandise contain the proper amount of components to offer your
    body the boost it wants.
    As most people who find themselves in search of steroids are both bulking or chopping.
    Following are the most effective authorized steroids for bulking,
    chopping and power that can meet your wants in a technique or one other.
    Furthermore, the effectiveness of Crazy Bulk dietary supplements extends beyond the
    mirror. Users often spotlight feeling extra energetic and targeted, which could be attributed to the adaptogenic properties
    of ingredients similar to Ashwagandha. When comparing Flexx Labs and
    Loopy Bulk, it’s essential to peel again the layers and scrutinize the
    components and their formulation. In my expertise, this is where
    the rubber meets the street in figuring out the quality and efficacy
    of legal steroids.
    Although steroids can provide some incredible outcomes,
    especially for those looking to build mass throughout bulking, it’s
    not probably the most suggested choice, because it comes with many problems and points.
    Also, note that it is not unusual to realize more fat and muscle throughout bulking.
    Following your bulk problem With steroids (kleineitaliaansecampings.nl) a well-planned
    cutting interval will even the scales and permit you to see
    your muscle definition once more. In this timeframe, you’re imagined to eat extra calories than your
    body needs over a set interval to help facilitate the growth of
    muscle tissue. In principle, those further calories will overwhelm your metabolism and pressure your body to retailer them as muscle.
    P.S Crazybulk don’t declare they’re steroids or associated to steroids.

    You can minimize body fats and achieve muscle mass, displaying off an excellent, beautifully minimize physique.

    Indeed, within the above loopy bulk evaluations, it is clearly
    said d that it is legal/Alternative steroids from Crazy Bulk are exceptionally protecting.
    Their recipes just do contain common and safe ingredients with no reactions.
    While concluding these Crazy bulk critiques, I can securely say that Crazy Bulk is
    a corporation with a decent reputation amongst athletes and bodybuilders.

    The group moreover offers a Buy 2 get 1 Free association on each request.

Leave a Reply

Your email address will not be published. Required fields are marked *