Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample PHP+Mongo app on Heroku

Sample PHP+Mongo app on Heroku

  1. Install any of the Mongo add-ons available at http://addons.heroku.com

  2. Vendor the Mongo driver with your application. You can download it here:

    https://github.com/wuputah/heroku-libraries/raw/master/php/mongo/mongo.so
    

    Add it to a folder like "ext".

  3. Add a php.ini file to the root of your application:

    extension_dir = "/app/www/ext/"
    extension=mongo.so
    
  4. Use it! Parse the db name out of the env var (keep in mind different Mongo providers will give you different urls, like MONGOHQ_URL or MONGOLAB_URL).

    Here's a sample index.php:

    <?php
      # get the mongo db name out of the env
      $mongo_url = parse_url(getenv("MONGO_URL"));
      $dbname = str_replace("/", "", $mongo_url["path"]);
    
      # connect
      $m   = new Mongo(getenv("MONGO_URL"));
      $db  = $m->$dbname;
      $col = $db->access;
    
      # insert a document
      $visit = array( "ip" => $_SERVER["HTTP_X_FORWARDED_FOR"] );
      $col->insert($visit);
    
      # print all existing documents
      $data = $col->find();
      foreach($data as $visit) {
        echo "<li>" . $visit["ip"] . "</li>";
      }
    
      # disconnect
      $m->close();
    ?>
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment