5

I have use following to add object to Firebase database.

$url = "https://myfb.firebaseio.com/api/types/ty/packs.json";
 $ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, $url);                               
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_POSTFIELDS, $userData);
 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        $jsonResponse = curl_exec($ch);
        if(curl_errno($ch))
        {
            echo 'Curl error: ' . curl_error($ch);
        }
 curl_close($ch);

The $userData will be kept under uniquely generated node in our database as follows. enter image description here

I want to give my custom key to that node. How I do this?

isuru
  • 3,385
  • 4
  • 27
  • 62

3 Answers3

2

If you are using Firebase REST API to insert data in Firebase using your custom Id and without any child(auto-generated) id, use 'Put' Instead of 'Post'.

Rida Noor
  • 61
  • 5
0

Change your url to the Id you want:

$url = "https://myfb.firebaseio.com/api/types/ty/packs/MY_CUSTOM_ID.json";

See the similar answer by Franke van Puffelen here: Saving data to Firebase with REST

Community
  • 1
  • 1
Mathew Berg
  • 28,625
  • 11
  • 69
  • 90
  • 1
    But there is another uniquely generated node within MY_CUSTOM_ID. Cant we prevent this? I need to keep my data within MY_CUSTOM_ID. Not MY_CUSTOM_ID -> uniquely generated -> My_Data. – isuru Dec 22 '16 at 04:27
  • I'm not user what your user_data looks like. The docs explain how to do this though. – Mathew Berg Dec 22 '16 at 11:05
  • Did you ever find a solution to this? I'm running into the same issue. – cramroop Nov 30 '17 at 20:18
0

The Firebase documentation says to us "if use rest api so some methods will be override" so you must use header X-HTTP-Method-Override:PUT or add custom method for php curl.

For example;

function saveObject(){
    $KEY ='YOUR_FIREBASE_SERVER_KEY';
    $headers = array('Content-Type:application/json', 'Authorization:key='.$KEY);

    //$object = new StdClass();
    //$object->key = "value";

    // or array....

    $object = array('key' => 'value');

    $data = json_encode($object);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://YOURFIREBASEURL/YOUR_ROOT.json");
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); // <--- This line important
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    // <--- This line to
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);

    if(curl_errno($ch)){
        return false;
    }

    curl_close($ch);

    return $response;
}
Phd. Burak Öztürk
  • 1,727
  • 19
  • 29