Giter Site home page Giter Site logo

kreait / firebase-php Goto Github PK

View Code? Open in Web Editor NEW
2.2K 35.0 422.0 3.81 MB

Unofficial Firebase Admin SDK for PHP

Home Page: https://firebase-php.readthedocs.io/

License: MIT License

PHP 100.00%
firebase php firebase-admin firebase-admin-sdk google-firebase firestore cloud-messaging firebase-auth firebase-authentication firebase-database

firebase-php's People

Contributors

ankurk91 avatar bithai avatar cblavi-skitude avatar davidblnc avatar dependabot[bot] avatar github-actions[bot] avatar hoogi91 avatar i3130002 avatar imlolman avatar jeromegamez avatar kitro avatar mgparisi avatar nhaynes avatar phpgangsta avatar rjgoolsby avatar rmsj avatar rvanlaarhoven avatar saishsali avatar saurabh-vijayvargiya avatar shinhan avatar sk-ip avatar slaci avatar snapshotpl avatar stanogurnik avatar szepeviktor avatar therohitdas avatar timz99 avatar tomykho avatar vladnev avatar wadewomersley avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firebase-php's Issues

SSL Error when trying to execute a query

As we're rolling PHP 5.6, I'm currently using the 1.x branch of the code. That said, when trying to execute a query on my database I'm receiving an error 51 curl response.

The issue appears to be that certificate validation is failing for whatever reason.

[Kreait\Firebase\Exception\FirebaseException]                                                                                                                                                                                              
  HTTP Error: An error occurred when fetching the URI "https://abstract-key-xxxxx.firebaseio.com/metafile.json?orderBy=%22symbol%22&equalTo=%22IFAN%22" with the adapter "guzzle6" ("cURL error 51: SSL: certificate verification failed (result: 5) (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)").                                                                                                                                                                       



  [Ivory\HttpAdapter\HttpAdapterException]                                                                                                                                                                                                   
  An error occurred when fetching the URI "https://abstract-key-xxxxx.firebaseio.com/metafile.json?orderBy=%22symbol%22&equalTo=%22IFAN%22" with the adapter "guzzle6" ("cURL error 51: SSL: certificate verification failed (result: 5) (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)").

Now keep in mind that if I paste that query into a browser, it executes and works just fine so the query is actually ok.

As well, I'm using Guzzle elsewhere without incident. Any assistance would be greatly appreciated.

Here is my test code (as I'm just getting started with your library):

        $fbConfig = new Configuration();
        $fbConfig->setAuthConfigFile(__DIR__.'/app/config/firebase.conf.json');
        $firebase = new Firebase('https://abstract-key-xxxxxxx.firebaseio.com', $fbConfig);
        $fbReference = $firebase->getReference("metafile");

        $fbQuery = new Query();
        $fbQuery->orderByChildKey("symbol");
        $fbQuery->equalTo('IFAN');

        $fbReference->query($fbQuery);

Any help would be appreciated.

how to authenticate user using email and password

Hello
i am new in using firebase and interested in using this library i try to create user using eamil and password but find no thing about this in your document

i currently using google api to signup new user and login in this reference

Registration
Method: POST
URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=<my-firebase-api-key>

Login Method: POST URL: https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=<my-firebase-api-key>
but can not work with rules to check if authenticated

"users" : {
        "$uid":{
          ".read":"auth.uid != null",
          ".write":"auth.uid != null",

        }
      }

please help to get the best way to do auth
Note : i am using version 1
Regards

Add documentation showing how to use custom JWT's with this library

Hey it would be really awesome if you could outline if your implementation supports custom JWT's and how you would foresee these integrating? I am happy to contribute to the project and write documentation etc.

Still trying to wrap my head around the final touches and any help that could lead to me taking the time to contribute would be awesome.

should getResultFromResponse method use array_filter?

I just downloaded kreait/firebase-bundle. After playing around with some code of the example section I got an "Warning: strlen() expects parameter 1 to be string" error

i tracked down the error until Firebase@getResultFromResponse line 175.
$rawResult is an array when it gets there after call, by example:

$firebase->get('services', array('shallow' => true));

not updating record but adding data.

<?php
require __DIR__.'/vendor/autoload.php';
use Kreait\Firebase\Configuration;
use Kreait\Firebase\Firebase;

$firebase = new Firebase('LINKL');
$users = $firebase->get('/users');

foreach($users as $key => $element) {
    $st = 'users/'.$key.'/presence/status';
    $nodeUpdateContent = $firebase->update(['status' => '0'], $st);
    print_r($nodeUpdateContent);
}
?>

It is not updating record. just adding one more row.

404 Bad Request

In my first attempt to use:

$sortedUsers = $users
            ->orderByChild('username', SORT_DESC)
            ->limitToFirst(10)
            ->getValue(); // shortcut for ->getSnapshot()->getValue()

I get the following error:

PHP Fatal error:  Uncaught GuzzleHttp\Exception\ClientException: Client error: `GET {MyProjectURL}/users?orderBy=%22username%22` resulted in a `400 Bad Request` response:
{
  "error" : "Index not defined, add \".indexOn\": \"username\", for path \"/users\", to the rules"
}

If I comment out ->orderByChild('username', SORT_DESC) and try again I get:

_PHP Fatal error:  Uncaught GuzzleHttp\Exception\ClientException: Client error: `GET {MyProjectURL}/users?limitToFirst=10` resulted in a `400 Bad Request` response:
{
  "error" : "orderBy must be defined when other query parameters are defined"
}

Is the syntax of .../user?orderby=%22username%22 getting corrupted by the %22 values? If so is this something that is causing the problem on my server setup?

Error: Permission denied.

After follow the tutorial I get the error Permission denied. This is my code:

    $firebase = Firebase::fromServiceAccount(__DIR__.'/service_account.json');

    $database = $firebase->getDatabase();


    $event = $database->getReference('/');
    $event->getSnapshot();

I validate and the JSON file is found it and open it.

Permission denied using $firebase->set ๏ฝž5% of the times

Here's the log with sensitive information removed:

2016-08-15T11:34:42.296710+00:00 app[web.1]: [15-Aug-2016 11:34:42 UTC] PHP Fatal error:  Uncaught Kreait\Firebase\Exception\FirebaseException: Server error (403) for URL https://*.firebaseio.com/*.json with data "*": Permission denied. in /app/vendor/kreait/firebase-php/src/Exception/FirebaseException.php:82
2016-08-15T11:34:42.296726+00:00 app[web.1]: Stack trace:
2016-08-15T11:34:42.296830+00:00 app[web.1]: #0 /app/vendor/kreait/firebase-php/src/Firebase.php(249): Kreait\Firebase\Exception\FirebaseException::httpError(Object(Ivory\HttpAdapter\Message\Request), Object(Ivory\HttpAdapter\Message\Response))
2016-08-15T11:34:42.296917+00:00 app[web.1]: #1 /app/vendor/kreait/firebase-php/src/Firebase.php(132): Kreait\Firebase\Firebase->send('https://*.f...', 'PUT', Array)
2016-08-15T11:34:42.296992+00:00 app[web.1]: #2 /app/*/api.php(176): Kreait\Firebase\Firebase->set(Array, '*/me...')
2016-08-15T11:34:42.297037+00:00 app[web.1]: #3 /app/*/api.php(184): onReceive()
2016-08-15T11:34:42.297040+00:00 app[web.1]: #4 {main}
2016-08-15T11:34:42.297112+00:00 app[web.1]:   thrown in /app/vendor/kreait/firebase-php/src/Exception/FirebaseException.php on line 82
2016-08-15T11:34:42.297290+00:00 app[web.1]: 10.69.216.189 - - [15/Aug/2016:11:34:39 +0000] "POST /* HTTP/1.1" 500 706 "-" "Mozilla/4.0

Cannot set configuration file with 1.x

Hi
I tried to set up firebase-php using a service account, but I keep getting this error:

PHP Fatal error: Call to undefined method Google_Client::setAuthConfigFile() in .../vendor/kreait/firebase-php/src/Configuration.php on line 143

Is the service account auth method not supported in 1.x?

Very slow to get data

I use the symfony-bundle - i think there is a problem with this main library.
If it's a problem in the bundle I will open the issue on the other repo.

With following code I have to wait > 15 sec to get the response:

$tokenGenerator = $this->firebase->getConfiguration()->getAuthTokenGenerator();
$token = $tokenGenerator->createToken($id, $provider);
$this->firebase->setAuthToken($token);
$user = $this->firebase->getReference('users/'.$userId)->getData();

Generating the token works very fast, but for the call

$this->firebase->getReference('users/'.$userId)->getData();

I have to wait > 15sec.

The same request over to the firebase api:

https://*.firebaseio.com/users/1.json?auth=123

takes < 300ms

In the next days i will take a look inside the library to find the problem.

Any Idea where is the problem or where do I make a mistake?

Problem with composer install

Something is wrong with egeloen/http-adapter dependency:

  Problem 1
    - Installation request for kreait/firebase-php ~0.4 -> satisfiable by kreait/firebase-php[0.4.0].
    - kreait/firebase-php 0.4.0 requires egeloen/http-adapter dev-feature/tape-recorder-subscriber as 0.5 -> no matching package found.

update records in firebase database

How to update status = 0 in firebase database where status = 1?

What I have tried is:

<?php
require __DIR__.'/vendor/autoload.php';
use Kreait\Firebase\Configuration;
use Kreait\Firebase\Firebase;
$firebase = new Firebase('LINK', $configuration);
$users = $firebase->get('/users');
for ($i=0; $i < count($users) ; $i++) {
    $data = array('status' => '0');
    $nodeUpdateContent = $firebase->update(['status' => '1'],$users[$i].'/presence/status');
    print_r($nodeUpdateContent);
}
?>

But when I see in the firebase database, it is not updating anything. Why so?

I am following this link: Firebase-php

Update data using this link: Update-data

I am getting in $users:

<?php
[1] => Array
(
    [presence] => Array
    (
        [loginTimestamp] => 1460117596561
        [status] => 1
    )

)

[2] => Array
(
    [presence] => Array
    (
        [loginTimestamp] => 1460117596561
        [status] => 1
    )
)

[3] => Array
(
    [presence] => Array
    (
        [loginTimestamp] => 1460117596561
        [status] => 1
    )
)

?>

I am getting response for this:
$nodeUpdateContent = $firebase->update(['status' => '1'],$users[$i].'/presence/status');

Array
(
    [status] => 1
)
Array
(
    [status] => 1
)
Array
(
    [status] => 1
)
Array
(
    [status] => 1
)
Array
(
    [status] => 1
)

It is just printing the status which value is 1, but not updating it.

getting error here: Array to string conversion --> $nodeUpdateContent = $firebase->update(['status' => '1'],$users[$i].'/presence/status');

$reference->getData() is always blocked

Here is my code:

$config = new Configuration();
$config->setAuthConfigFile('path/to/json');

$firebase = new Firebase('https://my_project_id.firebaseio.com', $config);

$reference = $firebase->getReference("path/to/location");

$data = $reference->getData(); // <-- always blocked here

I tried this way equivalent by java (on the same json & firebase_url) then everything worked fine.

egeloen/http-adapter deprecated

Would be nice to go over to httpplug.

This message is outputted when doing a composer install/update

Package egeloen/http-adapter is abandoned, you should avoid using it. Use php-http/httplug instead.

Ability to generate custom token (JWT) to use elsewhere in application

With the Official SDK for node and Java it's possible to use the SDK to create a custom token to be used in other places of the application. For example automatically log in a user against Firebase that is already logged-in in "my"-system.

It would be fantastic to have this functionality as part of the PHP SDK as well.

I'm currently doing this manually in my code to accomplish it (pretty much a standard JWT encode with the private key from the service account file):

        $serviceAccount = $this->getServiceAccount();
        $serviceAccountEmail = $serviceAccount['client_email'];
        $privateKey = $serviceAccount['private_key'];

        $nowSeconds = time();
        $payload = array(
            "iss" => $serviceAccountEmail,
            "sub" => $serviceAccountEmail,
            "aud" => "https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",
            "iat" => $nowSeconds,
            "exp" => $nowSeconds + (60 * 60),  // one hour
            "uid" => $userId
        );
        return JWT::encode($payload, $privateKey, 'RS256');

Composer require works on brand new project, fails on existing

When I use composer require kreait/firebase-php ^2.0@beta on a brand new project (laravel) all is well, but when there are already packages installed, "laravel/cashier": "~7.0" and "laravel/spark": "*@dev", the composer require script gives the below errors:

Problem 1
    - kreait/firebase-php 2.0.0-beta1 requires firebase/token-generator ^3.0 -> satisfiable by firebase/token-generator[v3.0.0].
    - kreait/firebase-php 2.0.0-beta2 requires firebase/token-generator ^3.0 -> satisfiable by firebase/token-generator[v3.0.0].
    - Conclusion: don't install firebase/token-generator v3.0.0
    - Installation request for kreait/firebase-php ^2.0@beta -> satisfiable by kreait/firebase-php[2.0.0-beta1, 2.0.0-beta2].

Let me know if you need anything further - cheers guys

How to create a child node off the parent?

So the scenario is this. I need to create a child off of the root node. I am however getting a permission denied when attempting to do so.

I'm attempting this using a push right now thinking it would create the path if it doesn't already exist?

$fbConfig = new Configuration();
$fbConfig->setAuthConfigFile(__DIR__.'/app/config/firebase.conf.json');
$firebase = new Firebase('https://abstract-key-nnnnn.firebaseio.com', $fbConfig);

$metaArray = array(' .... ');

$firebaseId = $firebase->push($metaArray, 'metadata');

In the scenario above, metadata does not yet exist in the first iteration. The push above is contained in a foreach where a large volume of records will be written to /metadata

Am I missing something? Somewhat new to Firebase so forgive any ignorrance.

Getting Permission Denied while getting reference data

First of all thanks for the contribution.

I'm getting permission denied while fetching reference from Firebase. Steps to reproduce.

  • Install firebase-php via Composer
  • Setup Service account in Google
  • Get .JSON file for service account creation and set it up in my project folder
$config = new Configuration();
$config->setAuthConfigFile(__DIR__.'google-service-account.json');
$firebase = new Firebase(FIREBASE_URL, $config);
$result = $firebase->get('test');

Exact Error Received:
Fatal error: Uncaught exception 'Kreait\Firebase\Exception\PermissionDeniedException' with message 'Server error (401) for URL FBURL_HERE/test.json with data "": Permission denied' in C:\wamp\www\test_firebase_api\vendor\kreait\firebase-php\src\Exception\FirebaseException.php on line 80

Using version 1.x

Am I doing anything wrong or any steps missing??

Firebase authentication and database access

I used the prescribed method of authentication on Firebase as below (I'm using version 1.x as I'm on PHP v 5.6 and I understand the latest firebase-php version requires PHP v 7)

use Kreait\Firebase\Configuration;
use Kreait\Firebase\Firebase;

$config = new Configuration();
$config->setAuthConfigFile(__DIR__.'/google-service-account.json');

$firebase = new Firebase('https://<my-app>.firebaseio.com', $config);
$firebase->get('/');

At first I had a permission denied error, but after several frustrating attempts to overcome it, I decided to make my read access public, but even after doing so, I was returned with an empty json. As I understand now, I have 2 issues - the first being an authentication issue, and later on a data retrieval issue.

I have tried successfully using NodeJS and the same credentials to access the same firebase database and am quite perplexed with regard to the current issues. The difference (as I noticed) is that in NodeJS, I first initialized my firebase app with the configuration json, then authenticate myself by signing in with email and password before I proceed to retrieve data.

Is there a possibility that version 1.x might have some peculiarities that need some special configuration?

Automatic updates of Firebase rules

Background: Data must be indexed to be queriable or sortable. If you try to query a yet unindexed dataset, the Firebase REST API will return an error. With this feature, the SDK could execute an error, and if an error occurs, update the Firebase Rules as needed and retry.

request it too slow in a specific time of day

Hello
I build some API depends on data in firebase its work fine all days hours but in mid of day in specific time it work slow and after it work fine back
i check my server its work fine and build test serves to test server ( no database connection inside ) and it work fine
I guess it may some thing happened in connection that cause this problem
is there is way to test it or check it to find the real reason ?

I try to query equalTo many columns but return [ ]

Hello
I try to query equal many column but return [ ]

example :

$query = new Query();
$query->orderByChildKey('isBusyDriver')
      ->equalTo('false')
      ->orderByChildKey('isOnline')
      ->equalTo('true');

$result = $firebase->query('/Driver', $query);
return $result;

please any help in this case or sample ?!
Regards

how to retrieve data from child of child

hello
i have driver table like that
driver=>

            -KQBWNv6sZWuh-x9QYUS
                    city:  "value"
                    companyID:   "-KQBWNv6sZWuh-x9QYUS"
                    createdAt: 
                    driverFacebookTokenID: 
                    driverLicenseNumber: 11231231
                    driverPhoto: "iamge"
                    firstName:"waleed"
                    insuranceCertificate: 
                    status: 0
                    uid: "-KQBWNv6sZWuh-h9QYUS"
                    updatedAt: "asdasd"
                    vehicle: "vicle id"

             -KQBWNv6sZWuh-x9QYaa
                    firstName:"waleed"
                    insuranceCertificate: 
                    status: 0
                    uid: "-KQBWNv6sZWuh-h9QYUS"

I try to build query to get drivers where sub child uid = eg.(-KQBWNv6sZWuh-h9QYUS)
how to fetch that without get all data for loop it to get my records
note : i am using version 1
regards

404 Not Found using firebase-php 2.0-beta1

2016-08-16T07:54:22.313212+00:00 heroku[router]: at=info method=GET path="/wogleaderboard/refresh/" host=zh.mygod.tk request_id=2b166b0e-4d23-4a17-822d-bb29313344dd fwd="210.140.195.107,108.162.226.55" dyno=web.1 connect=0ms service=330ms status=500 bytes=201
2016-08-16T07:54:22.310262+00:00 app[web.1]: [16-Aug-2016 07:54:22 UTC] PHP Fatal error:  Uncaught GuzzleHttp\Exception\ClientException: Client error: `GET https://firebase-mygod.firebaseio.com/wogleaderboard/players` resulted in a `404 Not Found` response:
2016-08-16T07:54:22.310274+00:00 app[web.1]: {
2016-08-16T07:54:22.310280+00:00 app[web.1]:   "error" : "404 Not Found
2016-08-16T07:54:22.310309+00:00 app[web.1]: 
2016-08-16T07:54:22.310292+00:00 app[web.1]: }
2016-08-16T07:54:22.310373+00:00 app[web.1]:  in /app/vendor/guzzlehttp/guzzle/src/Exception/RequestException.php:107
2016-08-16T07:54:22.310514+00:00 app[web.1]: #0 /app/vendor/guzzlehttp/guzzle/src/Middleware.php(65): GuzzleHttp\Exception\RequestException::create(Object(GuzzleHttp\Psr7\Request), Object(GuzzleHttp\Psr7\Response))
2016-08-16T07:54:22.310393+00:00 app[web.1]: Stack trace:
2016-08-16T07:54:22.310597+00:00 app[web.1]: #1 /app/vendor/guzzlehttp/promises/src/Promise.php(203): GuzzleHttp\Middleware::GuzzleHttp\{closure}(Object(GuzzleHttp\Psr7\Response))
2016-08-16T07:54:22.310731+00:00 app[web.1]: #2 /app/vendor/guzzlehttp/promises/src/Promise.php(156): GuzzleHttp\Promise\Promise::callHandler(1, Object(GuzzleHttp\Psr7\Response), Array)
2016-08-16T07:54:22.310809+00:00 app[web.1]: #3 /app/vendor/guzzlehttp/promises/src/TaskQueue.php(61): GuzzleHttp\Promise\Promise::GuzzleHttp\Promise\{closure}()
2016-08-16T07:54:22.311056+00:00 app[web.1]: #5 /app/vendor/guzzlehttp/promises/src/Promise.php(223): GuzzleHttp\Promise\P in /app/vendor/kreait/firebase-php/src/Firebase/Database/ApiClient.php on line 120
2016-08-16T07:54:22.310907+00:00 app[web.1]: #4 /app/vendor/guzzlehttp/promises/src/Promise.php(246): GuzzleHttp\Promise\TaskQueue->run(true)
2016-08-16T07:54:22.311272+00:00 app[web.1]: 10.137.144.23 - - [16/Aug/2016:07:54:21 +0000] "GET /wogleaderboard/refresh/ HTTP/1.1" 500 13 "https://zh.mygod.tk/wogleaderboard/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.8 Safari/537.36

The problem is that I'm using a project migrated from the old firebase.com. And probably because of the duplicate names, it got renamed to firebase-mygod. But the url is still mygod.firebaseio.com instead of firebase-mygod.firebaseio.com.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.