Skip to content

Instantly share code, notes, and snippets.

Created January 5, 2013 17:02
Show Gist options
  • Save anonymous/4462529 to your computer and use it in GitHub Desktop.
Save anonymous/4462529 to your computer and use it in GitHub Desktop.
Write to MongoLab REST API from PHP
// Get this at your MongoLab.com user page
$MONGOLAB_API_KEY = 'XXXXXXXXXXXXXX';
$DB = 'mydb';
$COLLECTION = 'mycollection';
$name = $_POST['fullName'];
$email = $_POST['email'];
$phone = $_POST['phoneNumber'];
$src = $_POST['src'];
$milliseconds = round(microtime(true) * 1000);
$data = json_encode(
array("fullname" => $name,
"email" => $email,
"phone" => $phone,
"src" => $src,
// see http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON
"date" => array('$date' => $milliseconds)
)
);
$url = "https://api.mongolab.com/api/1/databases/$DB/collections/$COLLECTION?apiKey=$MONGOLAB_API_KEY";
try {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data),
)
);
$response = curl_exec($ch);
$error = curl_error($ch);
$response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "OK";
} catch (Exception $e) {
echo "FAIL";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment