Don't know where to start?

Begin by checking out the Stack.PHP website.
Then head over here for a quick tutorial on setting up and using Stack.PHP.


Why you should use Stack.PHP:

Stack.PHP has been completely rewritten from scratch to facilitate a comprehensive restructuring of the code. These new changes allow certain tasks to be coded in a much more logical manner while still providing full access to all routes in the API.

Here are just some of the features Stack.PHP offers:

  • A flexible caching system. Stack.PHP is designed to use as few API requests as possible. The library comes with two classes that can be set to automatically cache the responses of all API requests made: an SQL cache class (compatible with all database systems that have a PDO driver) and a filestore class (which stores the cached data on the filesystem). If none of the classes meets your needs, you can easily implement the CacheBase class in one of your own classes and customize it to your heart's content.
  • An intuitive pagination class. All requests (with perhaps one or two exceptions) return an instance of a Response or PagedResponse object. This object provides an easy means of stepping through the objects returned. In the case of a PagedRequest object, additional pages of data are automatically fetched as needed as you step through the data returned. This code that uses a Response and PagedResponse object is basically identical.
  • Fully tested. The archives available for download and the code on Launchpad come with a tests folder. This folder contains an exhaustive test suite for Stack.PHP that runs through every API route, comparing the responses against expected output. These tests also make sure the utility code (such as the cache management code) is functioning as expected.
  • Fully documented. The entire codebase makes use of Doxygen comments throughout, making it easy to quickly generate HTML pages that describe in detail what each of the methods, enumerations, etc. do and any potential side effects you might encounter. The documentation can be found in the doc folder in the archives.
  • Easy to pick up and learn. To commemorate the first release in the 0.4 series, I have written a 7 page document on Google Docs which guides you through the basics of using the library.
  • Complete support for authentication. Stack.PHP supports the API's OAuth 2.0 methods out-of-the-box and without any third-party libraries. Everything just works - and you can immediately get a feel for how authentication works by dropping an API key / ID into one of the examples and trying it out. Both the implicit and explicit authentication flows are supported.
  • An organized exception class. Exceptions can come from all over the place in Stack.PHP (from cURL, from the cache classes, etc.), so it made sense to create a flexible exception class that captured the relevant information. You can see how this works by examining the test suite that is included with the library.
  • OutputHelper class to save you from writing HTML / CSS / JS. When designing a web application that uses Stack.PHP, you will find yourself writing certain snippets of code again and again. Stack.PHP saves you from having to do this by offering a simple OutputHelper class that generates HTML / CSS / JS code for you. Do you want to generate a <select> containing all Stack Exchange sites without their corresponding Metas? No problem - this can be solved with one line of code.
  • A full slate of real-world examples. It's one thing to know how to use Stack.PHP in theory. It's another thing to understand what typical and proper usage of the library looks like. That's why the library ships with a number of examples that demonstrate best practices and usage patterns - examples that range from really simple to very complex.

Code Snippet

Simple example demonstrating usage:


// Imports all of the files we need
require_once 'path_to_stackphp/api.php';

// Create a Site object for Stack Apps and get the questions tagged 'app'
$stackapps = API::Site('stackapps');
$apps      = $stackapps->Questions()->Tagged('app')->Exec();

// Notice that we are fetching ALL apps across ALL pages here
while($app = $apps->Fetch())
    echo "{$app['title']}\n";



How can I use Stack.PHP?

Stack.PHP is available under the MIT License - you are free to make any modifications to the code and use the library in a commercial application.


Where can I get Stack.PHP?

The latest beta release is 0.5 beta 1 and can be downloaded here:

The previous stable release can be found here:

Even older versions:


What do I need to run Stack.PHP?

PHP 5.2 or higher is required for most of the library. The SQLite driver for the cache class has a bug that prevents it from working in PHP 5.2, however.


Who do I talk to if I have a question?

I can be reached at [email protected].


Gimme teh codez!!11!

The code can be retrieved from http://launchpad.net/stackphp

Contributions to stack.PHP are always welcome.
Contact me at the above address or on LaunchPad if you are interested.

  • 1
    Sweet, thanks. I'm way too lazy to do this on my own so I'll use your library to change the front page of column80.com (I'll keep the main app as the other library though) Commented Jun 24, 2010 at 9:28
  • @Bill: Marco Ceppi and I are working on a bunch of new changes and they should be ready in a day or two. Commented Sep 16, 2010 at 18:22
  • Thanks for the notification, I'll check it out and let you know when I have some free time. Right now I'm only using the StackAuth part, but that could change as my little side project grows. Commented Sep 19, 2010 at 23:42
  • The "Don't know where to start" box at the top is not so useful now, seeing as the first link is broken. Commented Aug 22, 2013 at 5:27
  • @Scott: Actually the link is valid - the website just happens to be down at the moment. Commented Aug 22, 2013 at 5:33
  • Ah, okay. Perhaps someone can delete these comments once it's back up. Commented Aug 22, 2013 at 8:38
  • How would we set a new cache expire time? Is it just a matter of doing API::$cache_ttl = 86400; in our config.php? . . . Sweet stuff, btw, thanks! I was trying to do it my way for this plugin and the throttle was just like doing_it_wrong() ;)
    – brasofilo
    Commented Aug 26, 2013 at 14:45
  • 1
    For the curious, the entire site has been moved to a new server now. Commented Oct 3, 2013 at 4:09
  • Any way this could be used to retrieve comments?
    – user18962
    Commented Oct 3, 2013 at 21:30
  • @Undo: Sure! Take a look here. Commented Oct 4, 2013 at 1:14
  • Hmm... I'm more interested in just getting a list of the most recent comments. Any way to do that?
    – user18962
    Commented Oct 4, 2013 at 1:17
  • @Undo: Perhaps something like this: $response = API::Site('stackoverflow')->Comments()->Exec(); Then you can loop over them with while($comment = $response->Fetch(FALSE)) { .... Commented Oct 4, 2013 at 1:55
  • OK, looks great! Will test tomorrow.
    – user18962
    Commented Oct 4, 2013 at 2:59
  • is this project still maintained?
    – m.s.
    Commented Oct 19, 2015 at 12:19
  • @m.s. it should still work since v2.0 of the API is still around. I'm not actively developing it but I'm also not aware of any open bugs or issues. Commented Oct 19, 2015 at 17:40

6 Answers 6


Mkay, I've only used the part of the code that relates to StackAuth:

  1. You forgot to update the version number for SitesMethod and UsersByIdAssociatedMethod
  2. SitesMethod and UsersByIdAssociatedMethod both take $key as a parameter, but seeing as we've already inited the stackPHP object with the key, seems a bit redundant. I changed my SitesMethod function to read:


public function SitesMethod(){
    $data = $this->FetchData('http://stackauth.com/0.9/sites?key=' . $this->$key);

    if(get_class($data) !== FALSE && property_exists($data,'error'))
        $this->Error("There was an error retrieving the data from the API servers.<br><br><code>" . $data->error->message . "</code>");

    return $data;
  • Ah. Good spotting. My bad. I'll try to fix those two problems tonight :) Commented Jun 25, 2010 at 2:47
  • 1
    All good, it was very useful to not have to roll my own StackAuth functions. Commented Jun 25, 2010 at 4:52
  • 1
    The library is released under the MIT license, so please feel free to publish the code on GitHub if you wish. Commented Sep 12, 2013 at 15:18

Not sure if this is the right place for it, but I'm having some issues when I try and deploy this wrapper on a server as opposed to my local environment.

First of all, I don't have SQLite3 on my server and do not have the ability to install it so I've set the caching to 0.

Second, I have got it working perfectly on my local dev server that has internet access (for api connectivity), but when I run the exact script on my server it returns a curl error of an 'empty reply from server' error.


  • Hmmm... I don't have SQLite3 on my server either and it runs fine. Can you wait a day or two for me to look into this? I have some new changes to push anyway. Commented Feb 12, 2011 at 8:35
  • sure thing man, appreciate the response and the code :) Commented Feb 12, 2011 at 14:50
  • Okay, I've updated the library to support v1.1 of the API. You can test it on your server by doing the following: 1) download the .tar.gz listed at the top of this page 2) change the 10 on line 18 and 44 of examples/auth_example.php to 0 3) copy the /examples and /StackExchange folder to a folder on your server 4) visit the auth_example.php page in your browser. Hopefully that works and you see some diagnostic info printed to the page. Commented Feb 13, 2011 at 2:54
  • are there any common curl pitfalls you have come across with this library? it seems like on my live server, the 31st request is failing, the curl error is "empty reply from server". Commented Feb 13, 2011 at 5:41
  • You may have to slow down the requests since the API will stop replying if you send too many requests too quickly. Commented Apr 22, 2011 at 1:31
  • The new version of Stack.PHP (0.4beta1) now automatically throttles requests to comply with the rate-limitting. Commented Oct 7, 2011 at 6:36

I've already used the Stack.PHP library in a WordPress plugin and am deploying a second one. They had a class conflict and using class_exists before require_once/stackphp* didn't work.
I had to do this at the beginning of the file output_helper.php:

if( !class_exists( 'API' ) ):
require_once 'api.php';
require_once 'auth.php';
require_once 'combobox_output.php';
require_once 'table_output.php';

I ended also adding this to all files:

if( !class_exists( 'StackPHPClass' ) ):
class StackPHPClass {}

Thinking about it, the class names are quite simple (API, Auth, etc) and I'm afraid of conflicts with other plugins in the wild (I'm about to publish both on the official Repo). My OOP skill are limited, but would it be possible to add a Namespace or something like that without breaking backwards compatibility?

PS: Just a personal, unrelated, note; I miss the project being in GitHub instead of Launchpad.


@Nathan Osman, I have been trying to get authentication working with your library (which is very useful BTW). However, whenever I use the explicit flow I end up with an error on the stack exchange.com/oauth/submit page saying:

Cannot return to provided redirect_uri

The uri I am attempting to provide is generated using BeginExplicitFlow in auth.php from Stack.PHP and I have checked that it is correct (uses the same protocol, same subdomain). However I can't get it to work, I just get the "Cannot return to provided redirect_uri" error. I have also tried the implicit flow but that doesn't work for me either.

Since this library hasn't been updated in a while, I was wondering if you (or other helpful samaritans) could confirm that the authentication part of this library still works so that I can be sure it is something wrong with my setup.

To clarify, my redirect_uri uses a subdomain, and this is also specified in my app's "OAuth Domain". The page from which I am attempting to authenticate from does reside under my "OAuth Domain", I cannot think what could be wrong with my setup...

I have been struggling with this for weeks and have searched online for hours and don't know what else to try, I have found similar problems but nothing that solved my issues. Thanks for the help.

  • I have now discovered that it is an issue with the domain I am hosting my site on (subdomain of the University website), it likely has security restrictions of some form that don't allow the authentication to work correctly. Unfortunately that is only speculative as I haven't received a response from the IT staff. But fortunately, having set up a free domain myself and hosting it elsewhere I was able to get it all working! So no problem with the API whatsoever :), it was just difficult to discern where the issue was coming from. Commented Dec 1, 2015 at 8:53

Thanks for your library first of all.

I am not very comfortable posting this doubts here, doesn't seem the right place... let know if you want me to delete this "answer".

I had a problem with the cache while instantiating UserExchange:

$so = new UserExchange('stackoverflow','myapikey', 0);

But I realized the cache was still active even when passed $cache_ttl=0 as above (I wanted it disable for testing). I checked out your constructor of UserExchange and see that you are calling the parent StackBase constructor with ttl=10 , overriding any value that is passed in the constructor of a UserExchange. Is this intentional?

UserExchange.php line 20:

parent::__construct( $site, $key, $cache_ttl = 10 );

And another doubt about the caching. In the StackBase class you set up:

public $_cache_path = "cache/";

but then I can't see $_cache_path being used anywhere, the cache methods use hard coded paths. I guess this is just because you haven't have the time to complete this part?

Lines 437 to 439 in StackBase.php (startCache method):

if( !is_dir("cache/") )
        if( !mkdir("cache/") ) {
            // ...
  • 1
    Thanks for the feedback! To answer your first question (regarding the constructor) - yes, that is a bug and although it has been fixed in the repository, the ZIP archives haven't been updated yet. Commented Apr 20, 2011 at 21:11
  • ...as for the second question (about the cache path) I'm not quite sure why that path is there. The cache code actually was written by someone else and integrated into the library. I will certainly look into that and see if it needs to be removed or not. Commented Apr 20, 2011 at 21:12
  • The entire library has been rewritten from scratch by me and now features an entirely new set of cache classes which are far more flexible and easier to use. Please see the update above for more information. Commented Oct 14, 2011 at 6:26

This is probably a dumb question, but: How do you retrieve the body of a post?

For example, I have:

$questionList = $api->Questions()->SortByActivity()->Exec();
while($question = $questionList->Fetch(TRUE)){

But... how do I get the question body? It doesn't seem to be in the API reponse that I can see. I remember in the v1 API you had to explicitly request that the API include the question body. Do you have to do the same thing here somehow?

OK I've now two different filters on the same page for two different requests. A contrived example:

    $qstFilter = new Filter();

    $ansFilter = new Filter();

    $questionObj = $api->Questions($qstID); 
    $question = $questionObj->Filter($qstFilter->GetID())->Exec()->Fetch();
    $answers = $questionObj->Answers()->Filter($ansFilter->GetID())->SortByVotes()->Exec();

However, when I am using the FileSystem cache (I have not tried the SQL Cache) I seem to be able to only use one filter at a time - both of the filters show exactly the same content (whichever one is set last).

Commenting out

API::SetCache(new FilestoreCache('stackcache'));

fixes this. So I've just turned the cache off for now.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .