Take the 2-minute tour ×
Stack Apps is a question and answer site for apps, scripts, and development with the Stack Exchange API. It's 100% free, no registration required.

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 admin@quickmediasolutions.com.


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.

share|improve this question
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) –  Mark Henderson Jun 24 '10 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. –  Nathan Osman Sep 16 '10 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. –  Bill the Lizard Sep 19 '10 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. –  Scott Morrison Aug 22 '13 at 5:27
@Scott: Actually the link is valid - the website just happens to be down at the moment. –  Nathan Osman Aug 22 '13 at 5:33
Ah, okay. Perhaps someone can delete these comments once it's back up. –  Scott Morrison Aug 22 '13 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 Aug 26 '13 at 14:45
For the curious, the entire site has been moved to a new server now. –  Nathan Osman Oct 3 '13 at 4:09
Any way this could be used to retrieve comments? –  Undo Oct 3 '13 at 21:30
@Undo: Sure! Take a look here. –  Nathan Osman Oct 4 '13 at 1:14
Hmm... I'm more interested in just getting a list of the most recent comments. Any way to do that? –  Undo Oct 4 '13 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)) { .... –  Nathan Osman Oct 4 '13 at 1:55
OK, looks great! Will test tomorrow. –  Undo Oct 4 '13 at 2:59
add comment

4 Answers

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.

share|improve this answer
add comment

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/") ) {
            // ...
share|improve this answer
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. –  Nathan Osman Apr 20 '11 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. –  Nathan Osman Apr 20 '11 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. –  Nathan Osman Oct 14 '11 at 6:26
add comment

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.


share|improve this answer
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. –  Nathan Osman Feb 12 '11 at 8:35
sure thing man, appreciate the response and the code :) –  jondavidjohn Feb 12 '11 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. –  Nathan Osman Feb 13 '11 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". –  jondavidjohn Feb 13 '11 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. –  Nathan Osman Apr 22 '11 at 1:31
The new version of Stack.PHP (0.4beta1) now automatically throttles requests to comply with the rate-limitting. –  Nathan Osman Oct 7 '11 at 6:36
add comment

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;
share|improve this answer
Ah. Good spotting. My bad. I'll try to fix those two problems tonight :) –  Nathan Osman Jun 25 '10 at 2:47
All good, it was very useful to not have to roll my own StackAuth functions. –  Mark Henderson Jun 25 '10 at 4:52
The library is released under the MIT license, so please feel free to publish the code on GitHub if you wish. –  Nathan Osman Sep 12 '13 at 15:18
add comment

You must log in to answer this question.

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