MongoDB connection using PHP Driver - Fatal Error Class ‘MongoDB\Driver\Manager’ - php

I am trying to connect MongoDB to my Wordpress via PHP native driver. I am working on macOS Monterey version 12.6 and PHP version 8.1.10.
Following MongoDB's documentation I have installed all prerequisites:
Installed php extension using pecl install mongodb
Added extension=mongodb.so to the php.ini file
Installed MongoDB Library using composer require mongodb/mongodb in the root project directory
I then tried to connect to Atlas using the following code (note: I replaced the inputs db, password, and cluster in the actual code):
<?php
require_once __DIR__ . '/vendor/autoload.php';
$client = new MongoDB\Client(
'mongodb+srv://<my-database>:<my-password>#<my-cluster>.lkffbtl.mongodb.net/?retryWrites=true&w=majority');
var_dump( $client );
After running this code, I receive a fatal error:
Fatal error: Uncaught Error: Class 'MongoDB\Driver\Manager' not found in /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/vendor/mongodb/mongodb/src/Client.php:124 Stack trace: #0 /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/conf.php(6): MongoDB\Client->__construct('mongodb+srv://c...') #1 /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/mongodb.php(28): require_once('/home3/coradase...') #2 /home3/coradase/public_html/cora-staging/wp-includes/class-wp-hook.php(307): cora_mongodb_admin_page('') #3 /home3/coradase/public_html/cora-staging/wp-includes/class-wp-hook.php(331): WP_Hook->apply_filters('', Array) #4 /home3/coradase/public_html/cora-staging/wp-includes/plugin.php(476): WP_Hook->do_action(Array) #5 /home3/coradase/public_html/cora-staging/wp-admin/admin.php(259): do_action('toplevel_page_c...') #6 {main} thrown in /home3/coradase/public_html/cora-staging/wp-content/plugins/MongoDB/vendor/mongodb/mongodb/src/Client.php on line 124
This error seems to stem from the Client.php file that was installed as a part of the MongoDB Library through composer. Within Client.php, line 124 (referenced in the error) is contained in the following function:
public function __construct($uri = 'mongodb://127.0.0.1/', array $uriOptions = [], array $driverOptions = [])
{
$driverOptions += ['typeMap' => self::$defaultTypeMap];
if (! is_array($driverOptions['typeMap'])) {
throw InvalidArgumentException::invalidType('"typeMap" driver option', $driverOptions['typeMap'], 'array');
}
if (isset($driverOptions['autoEncryption']['keyVaultClient'])) {
if ($driverOptions['autoEncryption']['keyVaultClient'] instanceof self) {
$driverOptions['autoEncryption']['keyVaultClient'] = $driverOptions['autoEncryption']['keyVaultClient']->manager;
} elseif (! $driverOptions['autoEncryption']['keyVaultClient'] instanceof Manager) {
throw InvalidArgumentException::invalidType('"keyVaultClient" autoEncryption option', $driverOptions['autoEncryption']['keyVaultClient'], [self::class, Manager::class]);
}
}
$driverOptions['driver'] = $this->mergeDriverInfo($driverOptions['driver'] ?? []);
$this->uri = (string) $uri;
$this->typeMap = $driverOptions['typeMap'] ?? null;
unset($driverOptions['typeMap']);
$this->manager = new Manager($uri, $uriOptions, $driverOptions);
$this->readConcern = $this->manager->getReadConcern();
$this->readPreference = $this->manager->getReadPreference();
$this->writeConcern = $this->manager->getWriteConcern();
}
Line 124 specifically is:
$this->manager = new Manager($uri, $uriOptions, $driverOptions);
Again, this code comes directly from the composer installation of MongoDB Library, and has not been edited.
I appreciate any insight in trying to debug so that the code will properly establish the connection to the database.
Thank you!

Related

Cant access Firestore documents from PHP scripts with API key

I am new to Firebase/Firestore. I have created 2 projects that access the same data in Firestore.
One is in android and the other a web app in php. I am able to access data in android app but in PHP app
i had to create an API key in the credentials page. I want to use Firestore on trial basis initially but am not able to access the documents . It gives an error
Fatal error: Uncaught RuntimeException: Credentials fetcher does not implement Google\Auth\UpdateMetadataInterface in C:\xampp\htdocs\FirestoreProject\vendor\google\auth\src\FetchAuthTokenCache.php:190 Stack trace: #0 C:\xampp\htdocs\FirestoreProject\vendor\google\gax\src\CredentialsWrapper.php(197): Google\Auth\FetchAuthTokenCache->updateMetadata(Array, 'https://firesto...') #1 [internal function]: Google\ApiCore\CredentialsWrapper->Google\ApiCore{closure}(Object(stdClass)) #2 C:\xampp\htdocs\FirestoreProject\vendor\grpc\grpc\src\lib\ServerStreamingCall.php(44): Grpc\Call->startBatch(Array) #3 C:\xampp\htdocs\FirestoreProject\vendor\grpc\grpc\src\lib\BaseStub.php(364): Grpc\ServerStreamingCall->start(Object(Google\Cloud\Firestore\V1\BatchGetDocumentsRequest), Array, Array) #4 C:\xampp\htdocs\FirestoreProject\vendor\grpc\grpc\src\lib\BaseStub.php(589): Grpc\BaseStub->Grpc{closure}('/google.firesto...', Object(Google\Cloud\Firestore\V1\BatchGetDocumentsRequest), Array, Array, Array) #5 C:\xampp\htdocs\FirestoreProject\ve in C:\xampp\htdocs\FirestoreProject\vendor\google\auth\src\FetchAuthTokenCache.php on line 190
I have installed composer and updated the dependencies and gRPC.
My index.php file reads
<?php
session_start();
require_once 'vendor/autoload.php';
require_once "Firestore.php";
$apiKey = 'WWWWWWWWWWWWWWWWWWWWWW';
$url ='https://console.firebase.google.com/project/prject-ID/firestore?
key=Aasdads';
$fs = new Firestore('Users');
print_r($fs->getDocument('9427349073'));
return;
?>
My Firestore.php file reads
<?php
use Google\Cloud\Core\Exception\GoogleException;
use Google\Cloud\Firestore\FirestoreClient;
class Firestore
{
protected $db;
protected $name; // $name is name of collection
public function __construct(string $collection) // $collection =
// 'Users'
{
if (isset($this)) {
try {
$this->db = new FirestoreClient([
'projectId' => 'XXXXXXXXXXXXXXXXXXX'
]);
$this->name = $collection;
} catch (GoogleException $e) {
print_r($e->getMessage());
}
}else{
}
}
public function getDocument(string $name) // $name is name of document
{
return $this->db->collection($this->name)->document($name)-
>snapshot()->data();
}
}
?>
I tried activating the Credentials Page but they are asking for Credit card for billing to start trial , which i dont have. Cant we test the database without activating the Credentials? What is the difference between testing and trial basis usage ?
Please help
regards
Sanjish
I have made a test.php file after creating a service account and pointing to the key.json file on command prompt using set GOOGLE_APPLICATION_CREDENTIALS
<?php
require_once 'vendor/autoload.php';
session_start();
use Google\Cloud\Firestore\FirestoreClient;
initialize();
function initialize()
{
// Create the Cloud Firestore client
$db = new FirestoreClient([
'projectId' => 'Valbhai-xxx'
]);
$usersRef = $db->collection('Users'); // This works
$snapshot = $usersRef->documents(); // This does not work , gives
// the same error
foreach ($snapshot as $user) {
printf('User: %s' . PHP_EOL, $user->client_name());
}
}
?>
I reproduced your issue on my computer and I noticed that this is because PHP is ignoring the environment variable GOOGLE_APPLICATION_CREDENTIALS, because this is not defined for the user Apache(or httpd) in order to fix this I modified the initialization by using this code block
$db = new FirestoreClient([
'keyFilePath' => '/path/to/credentials.json',
'projectId' => 'my-project-id'
]);
With keyFilePath (this parameter is documented here), Firestore library going to search the GCP credentials using the string of the path instead the environment variable

How to fix "Class not found" Error for the Google Sheets API?

I am trying to set up a website that has google sheets API functionality, due to the constraints of the hosting service, I installed the API on my local computer with Composer before uploading everything onto the site. However, when I try creating the Google_Service_Sheets object, it says that the class cannot be found.
I've tried recreating the autoload.php file, and also adding a seperate require function:
require_once "./googleapi/google-api-php-client-2.2.3/vendor/google/apiclient-services/src/Google/Service/Sheets.php";
Main code:
require_once $configs["googleapifilev2"];
require_once "./googleapi/google-api-php-client-2.2.3/vendor/google/apiclient-services/src/Google/Service/Sheets.php";
$client = new \Google_Client();
$client->setApplicationName('test');
$client->setScopes([\Google_Service_Sheets::SPREADSHEETS]);
$client->setAccessType('offline');
$client->setAuthConfig($configs["googlecredentials"]);
$service = new \Google_Service_Sheets($client);
autoload.php code:
<?php
// autoload.php #generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit68a7a3a3b2a74c49476ad55dd7b1c990::getLoader();
An error occurs only when I call the Google_Service_Sheets object, but not the Google_Client.
Error message:
Fatal error: Uncaught Error: Class 'Google_Service_Sheets_Resource_Spreadsheets' not found in /storage/ssd3/963/10211963/public_html/googleapi/google-api-php-client-2.2.3/vendor/google/apiclient-services/src/Google/Service/Sheets.php:69
Stack trace:
#0 /storage/ssd3/963/10211963/public_html/twowvotingaction.php(56): Google_Service_Sheets->__construct(Object(Google_Client))
#1 {main} thrown in /storage/ssd3/963/10211963/public_html/googleapi/google-api-php-client-2.2.3/vendor/google/apiclient-services/src/Google/Service/Sheets.php on line 69
(Related lines in the API sheets.php file):
public function __construct(Google_Client $client, $rootUrl = null)
{
parent::__construct($client);
$this->rootUrl = $rootUrl ?: 'https://sheets.googleapis.com/';
$this->servicePath = '';
$this->batchPath = 'batch';
$this->version = 'v4';
$this->serviceName = 'sheets';
$this->spreadsheets = new Google_Service_Sheets_Resource_Spreadsheets( //Line 69
$this,
$this->serviceName,
'spreadsheets',
For some reason, when uploading the files, I accidentally put the ./googleapi/google-api-php-client-2.2.3/vendor/google/apiclient-services/src/Google/Service/Sheets folder, which defines the class, in the wrong directory, I moved it, and it now works.

Getting error while trying to connect to a node server in php using elephantIO

I am trying to connect to a node server using ElephantIO in php
Here is the code
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
use ElephantIO\Client,
ElephantIO\Engine\SocketIO\Version1X,
ElephantIO\Exception\ServerConnectionFailureException;
require __DIR__ . '/vendor/autoload.php';
$client = new Client(new Version1X('http://localhost:3001'));
try
{
$client->initialize();
$client->emit('new_order', ['foo' => 'bar']);
$client->close();
}
catch (ServerConnectionFailureException $e)
{
echo $e;
}
And i am getting an error on connection
ElephantIO\Exception\ServerConnectionFailureException: An error occurred while trying to establish a connection to the server in /var/www/html/Socket/vendor/wisembly/elephant.io/src/Engine/SocketIO/Version1X.php:167 Stack trace: #0 /var/www/html/Socket/vendor/wisembly/elephant.io/src/Engine/SocketIO/Version1X.php(48): ElephantIO\Engine\SocketIO\Version1X->handshake() #1 /var/www/html/Socket/vendor/wisembly/elephant.io/src/Client.php(60): ElephantIO\Engine\SocketIO\Version1X->connect() #2 /var/www/html/Socket/emit_test.php(47): ElephantIO\Client->initialize() #3 {main}

Mink + Driver couldn't connect to host

I am trying to get Mink working on Centos/Apache, but it cannot connect. I have tried with Selenium2Driver, ZombieDriver and last Sahi but I always get a different error.
Right now with Sahi:
require __DIR__ . '/vendor/autoload.php';
$driver = new \Behat\Mink\Driver\SahiDriver('firefox');
$session = new \Behat\Mink\Session($driver);
$session->start();
$session->visit('http://google.it');
echo $session->getStatusCode();
and generate this error:
Fatal error: Uncaught exception 'Buzz\Exception\RequestException' with
message 'couldn't connect to host' in
/var/www/html/Test/vendor/kriswallsmith/buzz/lib/Buzz/Client/Curl.php:29
Stack trace: #0
/var/www/html/Test/vendor/kriswallsmith/buzz/lib/Buzz/Browser.php(130):
Buzz\Client\Curl->send(Object(Buzz\Message\Request),
Object(Buzz\Message\Response)) #1
/var/www/html/Test/vendor/kriswallsmith/buzz/lib/Buzz/Browser.php(82):
Buzz\Browser->send(Object(Buzz\Message\Request)) #2
/var/www/html/Test/vendor/kriswallsmith/buzz/lib/Buzz/Browser.php(36):
Buzz\Browser->call('http://localhos...', 'POST', Array, '') #3
/var/www/html/Test/vendor/behat/sahi-client/src/Connection.php(268):
Buzz\Browser->post('http://localhos...', Array, '') #4
/var/www/html/Test/vendor/behat/sahi-client/src/Connection.php(150):
Behat\SahiClient\Connection->post('http://localhos...') #5
/var/www/html/Test/vendor/behat/sahi-client/src/Client.php( in
/var/www/html/Test/vendor/kriswallsmith/buzz/lib/Buzz/Client/Curl.php
on line 29
I have installed with composer:
behat/behat
behat/mink
behat/mink-sahi-driver
behat/sahi-client
Why it cannot connect?

Issue with PHP Script to reboot Rackspace server

I have been struggling to write a PHP script that will reboot a server using the 1.6.0 version of the Rackspace API (I can't install Composer on my server needed for 1.7.0). Unfortunately it does not want to recognize my credentials and keeps throwing this error:
Fatal error: Uncaught exception 'OpenCloud\Common\Exceptions\CredentialError' with message 'Unrecognized credential secret' in /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php:694 Stack trace: #0 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/Rackspace.php(66): OpenCloud\OpenStack->credentials() #1 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php(714): OpenCloud\Rackspace->Credentials() #2 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php(591): OpenCloud\OpenStack->authenticate() #3 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php(652): OpenCloud\OpenStack->checkExpiration() #4 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/Common/Service.php(337): OpenCloud\OpenStack->serviceCatalog() #5 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/Common/Service.php(68): OpenCloud\Common\Service->getEndpoint('compute', 'cloudServersOpe...', 'ORD', 'publicURL') #6 /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/ in /home/sandbox/public_html/rackspaceapi/lib/OpenCloud/OpenStack.php on line 694
Here is my PHP script (I did not include my credentials)
require_once "php-opencloud.php";
// The AUTHURL used for the US was: https://identity.api.rackspacecloud.com/v2.0/
putenv("RAX_USERNAME=$username");
putenv("RAX_API_KEY=$apikey");
putenv("RAX_TENANT_NAME=$tenantname");
putenv("RAX_AUTH_URL=$authurl");
define('USERNAME', $_ENV['RAX_USERNAME']);
define('APIKEY', $_ENV['RAX_API_KEY']);
define('TENANT', $_ENV['RAX_TENANT_NAME']);
define('AUTHURL', 'RAX_AUTH_URL');
$rackspace = new \OpenCloud\Rackspace(AUTHURL,
array( 'username' => USERNAME,
'apiKey' => APIKEY ));
$cservers = $rackspace->Compute('cloudServersOpenStack', 'ORD');
$list = $cservers->ServerList();
while($server = $list->Next()) {
if ($server->name == 'My_Server')
$server->Reboot('hard');
}
echo "Reboot sequence complete.";
Any help anyone can offer would be greatly appreciated.

Categories