Skip to content

Instantly share code, notes, and snippets.

@miku3920
Created September 29, 2019 16:38
Show Gist options
  • Save miku3920/725d991e7faeaad7d46a16e39b728d5d to your computer and use it in GitHub Desktop.
Save miku3920/725d991e7faeaad7d46a16e39b728d5d to your computer and use it in GitHub Desktop.
Firebase using php curl
<?php
define('FIREBASE_HOST','https://?????????????????.firebaseio.com');
define('FIREBASE_AUTH','????????????????????????????????????????');
function exec_curl_request($handle) {
$response = curl_exec($handle);
if ($response === false) {
$errno = curl_errno($handle);
$error = curl_error($handle);
error_log("Curl returned error $errno: $error\n");
curl_close($handle);
return false;
}
$http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
curl_close($handle);
if ($http_code >= 500) {
sleep(10);
return false;
} elseif ($http_code != 200) {
$response = json_decode($response, true);
error_log("HTTP Status Code: ".$http_code.". ".$response['error']."\n");
return false;
} else {
$response = json_decode($response, true);
}
return $response;
}
function FirebaseRequest($method="GET", $path="/", $parameters=""){
if (!is_string($method)) {
error_log("Method name must be a string\n");
return false;
}
if (!is_string($path)) {
error_log("Path must be a string\n");
return false;
}
if (is_array($parameters)) {
$parameters=json_encode($parameters);
}
$handle = curl_init(FIREBASE_HOST.$path.'.json?auth='.FIREBASE_AUTH);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($handle, CURLOPT_TIMEOUT, 60);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($handle, CURLOPT_POSTFIELDS, $parameters);
return exec_curl_request($handle);
}
// Write
$r = FirebaseRequest("PUT", "/path/id", 1);
// Update
$r = FirebaseRequest("PATCH", "/path", array( 'id' => 2, 'name' => "hello"));
// Lists
$r = FirebaseRequest("POST", "/path", array( 'id' => 3, 'name' => "world"));
// Read
$r = FirebaseRequest("GET", "/path");
// Delete
// $r = FirebaseRequest("DELETE", "/path");
echo "<pre>".print_r($r,true)."</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment