MongoClient, connect with '#' in password - mongodb-php

I've been trying to experiment with MongoDb, and when I run the script to connect, it can't because the password uses the # symbol.
To connect to MongoDb
mongodb://username:password#localhost
But as my password to connect to MongoDb uses the # symbol, it can't connect due to the # symbol.
For example;
new MongoClient("mongodb://mongo:p#assword#localhost);
Will throw the following error;
PHP Fatal error: Uncaught exception 'MongoConnectionException' with message 'Failed to connect to: assword!#localhost:27017: Couldn't get host info for assword!#localhost'
As you can see, it thinks the first # in the password is the seperator for password and host.
Is there a way to connect, and allow the # symbol in the password when using MongoClient?

http://uk3.php.net/manual/en/mongoclient.construct.php you can pass the username and password as an options array
new MongoClient("mongodb://localhost:27017", array("username" => "joe", "password" => "test"));

You can try by this code. Just pass your input as per dynamic value.
try {
$m = new MongoClient("mongodb://HOST:" . MNG_PORT, array(
"username" => MNG_USER,
"password" => MNG_PWD
)); // connect local Mongo
$db = $m->selectDB("DBNAME"); // select DB
$collection = $db->collections; // connect to collection
} catch ( MongoConnectionException $e ) {
echo 'Couldn\'t connect to mongodb, is the "mongo" process running?';
exit();
}

Related

Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user 'dbuser'#'localhost' (using password: YES)

Most answers were that it would be a right issue. But I assume not in this case, because mysql-connection still worked.
I am trying to connect to a mariadb10, which was on a server in my network
I am trying to connect from my localhost.
If I try in my terminal:
myuser#mylocalComputer ~ $ mysql -h myserver -P 3307 -u mydbuser -pmyconfidentalpassword
everything works fine!!
But If I try to connect by php scrypt by pdo I get the error:
<?php
$dsn = 'mysql: host=myserver:3307;dbname=mydbname';
$username = 'mydbuser';
$password = 'myconfidentalpassword';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'select * from foo;';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not select data: ' . mysql_error());
}
echo "Synced data successfully\n";
mysql_close($conn);
?>
The Error was:
PHP Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access
denied for user 'mydbuser'#'localhost' (using password: YES) in
/home/myuser/Projekte/Hibiscus_extend/Hib_Nightly_sync.php:8
Stack trace:
/home/myuser/Projekte/Hibiscus_extend/Hib_Nightly_sync.php(8):
PDO->__construct('mysql: host=myse...', 'mydbuser',
'myconfidentalpassword', Array) {main} thrown in
/home/myuser/Projekte/Hibiscus_extend/Hib_Nightly_sync.php on line 8
What did I do wrong, and where?
Oh Oh Oh!
I found the solution!
The reason for the connection problem were just the empty spaces in $dsn
Wrong:
$dsn = 'mysql: host=myserver:3307;dbname=mydbname';
works fine
$dsn = 'mysql:host=myserver:3307;dbname=mydbname';

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

Magento Soap API 1.9 - failed to load external entity

when i tried to connect to Soap Api, i'm getting this error :
SOAP-ERROR: Parsing WSDL: Couldn't load from 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl' : failed to load external entity "https://www.lignedublanc.fr/index.php/api/soap/?wsdl
i tried with soap UI and same errors.
i tried everything on the net but nothing helped.
Maybe someone here can help me ?
<?php
ini_set('soap.wsdl_cache_enabled',0);
ini_set('soap.wsdl_cache_ttl',0);
$url = 'https://www.lignedublanc.fr/index.php/api/soap/?wsdl=1';
$MagentoAPILogin = '';
$MagentoAPIPass = '';
$context = stream_context_create([
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
]
]);
try {
echo "Connecting to : $url\n";
//$client = new SoapClient($url);
$client = new SoapClient($url, ['stream_context' => $context]);
echo $client->login($MagentoAPILogin, $MagentoAPIPass)."\n";
echo 'Login successful';
} catch (Exception $e) {
echo 'Login fail'."\n";
echo $e->getMessage()."\n";
echo $e->getTraceAsString()."\n";
}
I believe the problem is caused by the server not being able to access the API from the local machine. It is actually the .htaccess file that blocking any hosts except the development machines. Hence, it results in a 403 Forbidden error which is actually the SOAP error. For more reference, have a look:
Unable to connect to Magento SOAP API v2 due to "failed to load external entity"

WP error connecting to DB

I get this message when I try to access my site.
The site was working properly, and I tried to add google analytics...
Anyway, sodabrasil was a site created out of WP.
sodabrasil.com/paskin was WP.
We did the integration of logins. Everything was working.
When I run http://sodabrasil.com/dbtest.php, it says it's connected.
this is the debug code.
<?php
//connect to MySQL Server
$conn = mysql_connect("localhost", "*****", "******");
if (!$conn)
{
die(mysql_error());
}
else
{
echo "1. Successfully connected to MySQL database server.<br /><br />";
}
// select database
$db_sel = mysql_select_db('*********', $conn);
if (!$db_sel)
{
die ('cant\'t use database: ' . mysql_error());
}
else
{
echo "2. WordPress database selected. <br />";
}
?>
the database * is the DB sodabrasil uses for the login.
But accessing sodabrasil is blocked even before the login!!!
I am not a professional coder, which makes things a lot harder.
This is the real config file:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
define('WP_USE_THEMES', false);
//echo $_SERVER['DOCUMENT_ROOT'];
//die;
//require_once('./blog/wp-blog-header.php');
require_once('/home/houswe5/public_html/sodabrasil.com/paskin/wp-blog-header.php');
global $mysqli;
$server = 'localhost'; // The host you want to connect to.
$username = '****'; // The database username.
$password = '*****'; // The database password.
$database = '*******'; // The database name.
$dbms = 'MySQL 5';
$dbport = '3306';
//$dbh = mysql_connect($server, $username, $password) or die("Unable to connect to SQL server");
//$my_db = #mysql_select_db($database) or die("Unable to select database");
$mysqli = new mysqli($server, $username, $password, $database);
//$mysqli = mysqli_connect($server, $username, $password, $database) or die("Error " . mysqli_error($link));
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;die;
}
// If you are connecting via TCP/IP rather than a UNIX socket remember to add the port number as a parameter.
?>
Exact same credentials.
But this url (http://sodabrasil.com/db_connect.php) throws the error message in regards to DB.
Thank you for you help.
G.

Apache Directory studio ldap bind from php

I am new to Apache Directory Studio and ldap. I am running a ldap server from Apache Directory studio. I have a user in ldap and i am trying to bind to the uid from a php script.Not sure where i am going wrong.
I am using username as "uid=admin,ou=user"
password as "secret"
I also tried username as "uid=arone_a,ou=users,dc=example,dc=com"
and password as "password"
Password attribute was set manually and arone_a is the user uid.
I am trying to write a php script which can pull all users in the ldap server.
Thanks in advance.
My PHP script is:
$ldaphost = "localhost";
$ldapport = 10389;
$ldaprdn='uid=admin,ou=system';
$ldappass='secret';
$ldapconn = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");
if($ldapconn)
{
$ldapbind=ldap_bind($ldapconn,$ldaprdn,$ldappass);
if($ldapbind)
{
echo "success";
}
else
{
echo "not success";
}
}
Connection goes through but bind is not going through.
I was having a similar issue and the problem was that I added to the userPassword attribute an additional param specifying the language, resulting in userPassword;lang-ca-ES (the wizard shows a form to add it).
That provoked that using Apache Directory Studio the "Verify" was working good, but it failed in the "Bind" check (you can do both in the password editor, double clicking the userPassword attribute.
I finally left userPassword without additional attributes and it binded perfectly :)
Just add the ldap set option, it worked for me
<?php
$ldaphost = "localhost";
$ldapport = 10389;
$ldaprdn='uid=admin,ou=system';
$ldappass='secret';
$ldapconn = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");
if($ldapconn) {
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
$ldapbind=ldap_bind($ldapconn,$ldaprdn,$ldappass);
if($ldapbind) {
echo "success";
} else {
echo "not success";
}
}
?>
The simple BIND request requires the DN, not the RDN. Should your BIND DN be something like uid=admin,ou=system,dc=example,dc=com?
see also
LDAP: Authentication best practices
LDAP: Programming practices