I just created php web server and connected it to firebase. when I tried authentication, Sign up works just fine. but the problem is in Sign in. it keeps getting this error:
Fatal error: Uncaught Error: Call to undefined method Kreait\Firebase\Auth::signInWithEmailAndPassword() in /Applications/XAMPP/xamppfiles/htdocs/firebase_series/authActions.php:24 Stack trace: #0 {main} thrown in /Applications/XAMPP/xamppfiles/htdocs/firebase_series/authActions.php on line 24
here my authentication code:
<?php
include("includes/db.php");
if(isset($_POST['signup']))
{
$email = $_POST['emailSignup'];
$pass = $_POST['passSignup'];
$auth = $firebase->getAuth();
$user = $auth->createUserWithEmailAndPassword($email,$pass);
header("Location:index.php");
}
else
{
$email = $_POST['emailSignin'];
$pass = $_POST['passSignin'];
$auth = $firebase->getAuth();
$user = $auth->getUserWithEmailAndPassword($email,$pass);
if($user)
{
session_start();
$_SESSION['user'] = true;
header("Location:home.php");
}
}
?>
and here's my database connection code:
<?php
require __DIR__.'/vendor/autoload.php';
use Kreait\Firebase\Factory;
use Kreait\Firebase\ServiceAccount;
use Kreait\Firebase\Auth;
// This assumes that you have placed the Firebase credentials in the same directory
// as this PHP file.
$serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/google-service-account.json');
$apiKey = 'AIzaSyCHULFKW6Kl7FXZc3ZUTYL8fq0f90-kAJ0';
$firebase = (new Factory)
->withServiceAccount($serviceAccount, $apiKey)
// The following line is optional if the project id in your credentials file
// is identical to the subdomain of your Firebase project. If you need it,
// make sure to replace the URL with the URL of your project.
->withDatabaseUri('https://phpserver-f35e3.firebaseio.com/')
->create();
$database = $firebase->getDatabase();
?>
👋 I'm the maintainer of the SDK (kreait/firebase-php) you're using :)
Your error says
Call to undefined method Kreait\Firebase\Auth::signInWithEmailAndPassword()
but I don't actually see this method called in your code. A method called signInWithEmailAndPassword() doesn't exist as well, and you're using methods to initialize the SDK that have been deprecated for quite some time now - please make sure to be on the latest release of the SDK (4.40 at the time of this comment).
Once you have, you will have access to the Auth::verifyPassword($email, $password) method.
Your code could then look like this:
<?php
// includes/db.php
require __DIR__.'/vendor/autoload.php';
use Kreait\Firebase\Factory;
$factory = (new Factory())->withServiceAccount(__DIR__.'/google-service-account.json');
$auth = $factory->createAuth();
// no closing "?>"
<?php
include("includes/db.php");
// Have a look at https://www.php.net/filter_input to filter user input
if (isset($_POST['signup'])) {
$email = $_POST['emailSignup'];
$pass = $_POST['passSignup'];
$user = $auth->createUserWithEmailAndPassword($email,$pass);
header("Location:index.php");
exit;
}
$email = $_POST['emailSignin'];
$pass = $_POST['passSignin'];
if ($email && $pass && $user = $auth->verifyPassword($email, $pass)) {
session_start();
$_SESSION['firebase_user_id'] = $user->id;
header("Location:home.php");
exit;
}
echo "Authentication failed";
If you have further questions concerning the SDK, I'd like to invite you the Discord community dedicated to the SDK.
Related
I need to access a file on SharePoint and I have installed phpSPO via Composer.
I use this code:
require_once('/vendor/autoload.php');
$username = 'myUsername';
$password = 'myPassword';
$fileUrl = "file-url";
$fileUrl = end(explode("https://xxxxxxxx.sharepoint.com", $fileUrl));
use Office365\PHP\Client\Runtime\Auth\AuthenticationContext;
use Office365\PHP\Client\SharePoint\ClientContext;
use Office365\PHP\Client\SharePoint\ListCreationInformation;
use Office365\PHP\Client\SharePoint\SPList;
$authCtx = new AuthenticationContext('https://xxxxxxxx.sharepoint.com');
But I get this error: Fatal error: Uncaught Error: Class "Office365\PHP\Client\Runtime\Auth\AuthenticationContext" not found ...
From composer.json:
{
"require": {
"vgrem/php-spo": "^2.5"
}
}
Any ideas?
Solution:
use Office365\Runtime\Auth\AuthenticationContext;
use Office365\SharePoint\ClientContext;
use Office365\SharePoint\ListCreationInformation;
use Office365\SharePoint\SPList;
I added a namespace to my user.php file, this causes an error to be displayed :
Fatal error: Uncaught Error: Class 'User' not found in /var/www/html/login.php:9 Stack trace: #0 {main} thrown in
/var/www/html/login.php on line 9
I tried changing "new Database\Database();" to "new \PDO();" but that causes another error which I've been unable to resolve after spending hours on google, if anyone could help I'd much appreciate it, thank you.
user.php
<?php
namespace User;
// 'user' object
class User
{
login.php
<?php
include_once "config/core.php";
$page_title = "Login";
$require_login = false;
include_once "login_checker.php";
include_once "config/database.php";
include_once "objects/user.php";
include_once "libs/php/pw-hashing/passwordLib.php";
$database = new Database\Database();
$db = $database->getConnection();
$user = new User($db);
use User\User;
$user = new User($db);
I'm coming from Java programming and I'm trying to apply my knowledge in OOP style programming in PHP.
So, I tried to create a utility class to connect to database just like how I usually do it in Java where I create a static method to get the database connection.
However, after spending hours I still can't fix the error.
DBHelper.php
<?php
class DBHelper
{
protected $db_name = 'myDb';
protected $db_user = 'root';
protected $db_pass = '';
protected $db_host = 'localhost';
public function obtainConnection()
{
$mysqli_instance = new mysqli($this->db_host, $this->db_user, $this->db_pass, $this->db_name);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
return $mysqli_instance;
}
}
?>
There are no errors in this file
Then I tried to use it on another file called login.php
login.php
<?php
if (isset($_POST['submit'])) {
include "/DBUtility/DBHelper.php";
$username = $_POST['username']; //s means string
$password = $_POST['password']; // s means string
echo "<br/> Username value: " . $username;
echo "<br />Password value: " . $password;
}
if (empty($username) || empty($password) ) {
echo "Fill out the fields!";
} else {
//PREPARE THE PreparedStatment or Stored Procedure
$dbHelper = new DBHelper();
$connection = $dbHelper->obtainConnection();
$preparedStatement = $connection->prepare('CALL getUserRoleByLogin(?, ?)'); //getUserRoleByLogin() is the name of stored proc in mysql db
$preparedStatement->bind_param('ss', $username, $password); //assign arguments to ? ?
$preparedStatement->execute();//execute the stored procedure. This will return a result
$userRole = $preparedStatement->store_result();
$countOfRows = $preparedStatement->num_rows;
?>
I read every related question about the Fatal error: Cannot redeclare class CLASSNAME error. I tried following the instructions given by many which is to use require_once("DBHelper.php"); instead of include("DBHelper.php");
but still can't get rid of the error.
I tried making the obtainConnection() static and called it via DBHelper::obtainConnection(); but with no luck. Same error message.
I get the error on opening brace of class DBHelper {
I hope you can help me with this.
Thank you.
A couple tips you should do when doing OOP in PHP:
1) I would maybe rethink about not baking the db credentials into your class directly, it makes it harder/more cumbersome to modify them via UI if you wanted to implement a UI control mechanism down the line. Instead, try making a define or maybe a json pref file or a dynamically-created php file that contains an array, something like that. I will do a define because it's the easiest to demonstrate:
/config.php
# You can create a series of defines including the database
define('DB_HOST','localhost');
define('DB_NAME','dbname');
define('DB_USER','root');
define('DB_PASS','dbpassword');
# To maximize compatibility it's helpful to define fwd/back slash
define('DS',DIRECTORY_SEPARATOR);
# It is helpful to create path defines for easy file inclusion
define('ROOT_DIR',__DIR__);
define('CLASSES',ROOT_DIR.DS.'classes');
# Start session
session_start();
2) Create a class autoloader in the config.php file which then allows you to not have to manually include/require classes in pages. It will automatically include them:
spl_autoload_register(function($class) {
if(class_exists($class))
return;
# This will turn a namespace/class into a path so should turn:
# $db = new \DBUtility\DBHelper();
# into:
# /var/www/domain/httpdocs/classes/DBUtility/DBHelper.php
$path = str_replace(DS.DS,DS,CLASSES.DS.str_replace('\\',DS,$class).'.php');
# If the class file is located in the class folder, it will include it
if(is_file($path))
include_once($path);
});
3) I am going to create a static connection so you don't create a new connection every time (also I will use PDO):
/classes/DBUtility/DBHelper.php
<?php
namespace DBUtility;
class DBHelper
{
protected $query;
private static $con;
public function connection()
{
# This will send back the connection without making a new one
if(self::$con instanceof \PDO)
return self::$con;
# I like to catch any pdo exceptions on connection, just incase.
try {
# Assign the connection
self::$con = new \PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
}
catch(\PDOException $e) {
# Here you can just die with a more user-friendly error.
# It would be helpful to save the actual error to a log file
$msg = $e->getMessage();
# I would put your log outside the root or in a protected folder
$txt = realpath(ROOT_DIR.DS.'..').DS.'errors'.DS.'sql.txt';
# Make a directory if none set
if(!is_dir(pathinfo($txt,PATHINFO_DIRNAME))) {
# Make the directory
if(mkdir(pathinfo($txt,PATHINFO_DIRNAME),0744,true)) {
# Save to log file
file_put_contents($txt,$msg.PHP_EOL);
}
}
else {
# Save to log file
file_put_contents($txt,$msg.PHP_EOL);
}
die("Site is under maintenance.");
}
}
# It would be helpful to create a query that will bind and not bind
public function query($sql,$bind = false)
{
if(is_array($bind)) {
foreach($bind as $key => $value) {
$sKey = ":{$key}";
$bindArr[$sKey] = $value;
}
$this->query = $this->connection()->prepare($sql);
$this->query->execute($bindArr);
}
else {
# The second "query" on this is the method from PDO, not the
# "query" method from this class
$this->query = $this->connection()->query($sql);
}
return $this;
}
public function getResults()
{
if(empty($this->query))
return false;
while($result = $this->query->fetch(\PDO::FETCH_ASSOC)) {
$row[] = $result;
}
return (isset($row))? $row : false;
}
}
# If your page ends with a php tag, you should just remove it. It will
# protect against empty spaces that may cause "header already sent" errors
3a) I use something similar to this to autoload functions:
/classes/Helper.php
class Helper
{
public static function autoload($function)
{
if(function_exists($function))
return;
$path = ROOT_DIR.DS.'functions'.DS.$function.'.php';
if(is_file($path))
include_once($path);
}
}
4) Create useful/reusable functions or class/methods
/functions/getUserRole.php
function getUserRole($username,$password,\DBUtility\DBHelper $DBHelper)
{
return $DBHelper->query('CALL getUserRoleByLogin(:0, :1)',array($username,$password))->getResults();
}
/index.php
# Include the config file
require_once(__DIR__.DIRECTORY_SEPARATOR.'config.php');
if (isset($_POST['submit'])) {
# No need for this line ->> include "/DBUtility/DBHelper.php";
# Use trim to remove empty spaces on the left and right
$username = trim($_POST['username']);
$password = trim($_POST['password']);
}
if (empty($username) || empty($password) ) {
echo "Fill out the fields!";
} else {
# User our function autoloader to include this function
Helper::autoload('getUserRole');
# Use the function and inject the DB class
$userRoles = getUserRole($username,$password,new \DBUtility\DBHelper());
$count = count($userRoles);
echo "Count: {$count}";
echo '<pre>';
print_r($userRoles);
echo '</pre>';
}
I'm using MongoDB with php - I'm trying to get the id of the user who has logged in with a username & password and store it as a session variable.
I keep getting this error and I don't understand why.
<?php
session_start();
$dbhost = 'localhost';
$dbname = 'story';
$mongo = new MongoClient("mongodb://$dbhost");
$db = $mongo->$dbname;
$collection = $db->users;
$email=$_POST['email'];
$password=$_POST['password'];
$user = $collection->find(array("email" => $email, "password" => $password));
$user->limit(1);
if ($user->count(true) > 0){
$_SESSION['user']['userid']=iterator_to_array($user['_id']->{'$id'});
header("Location:../webpages/master.php?page=home");
}else{
echo "Wrong username or password";
}
?>
find() returns a cursor, on which you can iterate to retrieve results.
While in case of single document retrieval,use findOne()
$user = $collection->findOne(array("email" => $email, "password" => $password));
And you need not to use following line :
$user->limit(1); // Don't use limit() with findOne()
As Sammaye has indicated the find() function returns a cursor that you then iterate over to find documents. If you know there is only one document then rather than using find(...)->limit(1), which still returns a cursor, you can use findOne(), which returns the document itself.
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
require_once('/include/adLDAP.php');
$adldap = new adLDAP();
$username = "user123";
$password = "pass123";
$authUser = $adldap->authenticate($username, $password);
if ($authUser === true) {
echo "<p>User authenticated successfully</p>";
}
else {
echo "User authentication unsuccessful";
}
$result=$ldap->user_groups($username);
print_r($result);
?>
I am using this class http://adldap.sourceforge.net/ and authentication works fine, but it gives me the following error:
Notice: Undefined variable: ldap in /web/protected/protected.php on line 18
Fatal error: Call to a member function user_groups() on a non-object in /web/protected/protected.php on line 18
Line 18 is:
$result=$ldap->user_groups($username);
Never used this class before, so I am unsure of why it is giving me that error, any help is appreciated.
When instanciating the adLDAP class, you're storing the instance object in $adldap :
$adldap = new adLDAP();
But, later, you are trying to use $ldap :
$result=$ldap->user_groups($username);
That $ldap variable doesn't exist -- hence the notice.
And as it doesn't exist, PHP considers it's null
And null is not an object -- which means you cannot call a method on it -- which explains the Fatal Error.
I suppose you should replace this line :
$result=$ldap->user_groups($username);
By this one :
$result=$adldap->user_groups($username);
Note the $adldap instead of $ldap, to use the instance of your adLDAP class, instead of a non-existing variable.