Skip to content


Accessing CouchDB with PHP

I decided that I was ready to start integrating PHP with CouchDB. Using the Getting Started with PHP wiki page, I tried running the first example listed on the page to at least make sure everything was set up correctly. However, I quickly hit a snag with this response from CouchDB:
string(64) “{“error”:”unauthorized”,”reason”:”You are not a server admin.”} ”

Okay, fair, I don’t want just anyone making changes to the database. However, I thought CouchDB accepted connections from localhost by default? With that in mind I went back to the third chapter of the CouchDB book. The PHP script is trying to add a new database, and chapter 3 had me adding a new database by command line. So let’s try running that command again:
curl -X PUT http://127.0.0.1:5984/baseball

And the response:
{“error”:”unauthorized”,”reason”:”You are not a server admin.”}

Definitely not the same response when I ran the command back in chapter 3, but at least it’s consistent with what I got from PHP.

So I put my thinking cap on. I remembered that in chapter 5 I made a change to the local.ini file adding an [admins] section. Maybe it’s not happy about that? How about if we modified the curl command to this:
curl -X PUT http://admin:ihavenosecrets@127.0.0.1:5984/baseball

Response?
{“ok”:true}

Much better! Okay, so the PHP script isn’t working because we need to provide a username and password and we’re not. Now, I could just go back and remove the [admins] section from local.ini, but I kind of like that it’s prompting for authentication. So how do we get it working?

The script is using PHP’s fsockopen function. After some reading on php.net it would seem that fsockopen doesn’t let you pass along a username and password by default, unless you want to start messing with headers and whatnot. That really doesn’t sound very fun.

The next option in line would be adding in the cURL library to use cURL instead of fsockopen. However, I’ve never used it before, and after reviewing the documentation it doesn’t look immediately straightforward. So in the interest of speed over correctness I’m going to forgo using authentication. I went back to /usr/local/etc/couchdb/local.ini, commented out the [admins] section, and restarted the CouchDB instance using:
sudo /usr/local/etc/init.d/couchdb restart

Running the PHP script again yields… success! Woo!

Posted in development.

Tagged with , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.