Introduction
Since couchdb provides a REST interface, it is tempting use AJAX to query the database directly to display data on your webpage. This is not always possible though. If my database runs on port 5555 then this means that my webpage will need access to port 5555 on my server. It's not always possible if firewalls are in the way. We know at least that port 80 should always be accessible. For several security reasons too, we might want the CouchDB to be hidden behind the public network and only accessible by the web server internally. Just as we would do with a SQL server.
Code
- Retrieve a document
$h = curl_init("http://server/db1/document1"); curl_setopt($h, CURLOPT_RETURNTRANSFER, true); curl_setopt($h, CURLOPT_CUSTOMREQUEST, "GET"); $response = curl_exec($h); $obj = json_decode($response);
- Create views
Json file:{ "language": "javascript", "views": { "view1": { "map": "function(doc){emit(doc._id,doc);}" }, "view2": { "map": "function(doc){emit(doc._id,doc);}", "reduce": "function (key, values){return null;}" } } }
PHP script:$json = file_get_contents("views.json"); $h = curl_init("http://server/db1/_design/designdoc1"); curl_setopt($h, CURLOPT_RETURNTRANSFER, true); curl_setopt($h, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($h, CURLOPT_POSTFIELDS,$json); curl_setopt($h, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); $response = curl_exec($h);
- Create doc
$obj = array("field1"=>"val1","field2"=>"val2"); $json = json_encode($obj); $h = curl_init("http://server/db1/document1"); curl_setopt($h, CURLOPT_RETURNTRANSFER, true); curl_setopt($h, CURLOPT_CUSTOMREQUEST, "PUT"); curl_setopt($h, CURLOPT_POSTFIELDS,$json); curl_setopt($h, CURLOPT_HTTPHEADER, array("Content-Type: application/json")); $response = curl_exec($h);
- Query a view
$h = curl_init("http://server/db1/_design/document1/_view/view1?reduce=true&group=true"); curl_setopt($h, CURLOPT_RETURNTRANSFER, true); curl_setopt($h, CURLOPT_CUSTOMREQUEST, "GET"); $response = curl_exec($h); $json=json_decode($response);
Retrieving attachments
Let's say we have an attachment that can be reachable at http://couchdbServer/database1/document1/image1.jpg. If "document1" is a blog post that show "image1", it is tempting to put a <img src=database1/document1/image1.jpg > But this is impossible, because that server is inaccessible from the outside world. So we might wanna do a proxy script:
$att = $_GET["a"];
$article = $_GET["art"];
$h = curl_init("http://".COUCHDB_SERVER."/".COUCHDB_DATABASE."/$article/$att");
curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
curl_setopt($h, CURLOPT_CUSTOMREQUEST, "GET");
$response = curl_exec($h);
$contentType = curl_getinfo($h, CURLINFO_CONTENT_TYPE);
header("Content-type: $contentType");
echo $response;
That way we can use our image like this: <img src=attachment.php?doc=document1&attachment=image1.jpg >