Create mysql DB with PHP through cPanel and import *.sql file - php

I want to create a DB for each user who wants to register to my Web-app. When i try this local everything perfectly works. A User can register with his email and pw. A DB is created and a import.sql file is imported so that the DB created for the User is empty on data but the tables and realtioships are given.
My Host uses cPanel and phpMyAdmin to create DB and db-user. I want to do this with php like i do it local. Does anyone have an idea how i get this done?
I've already searched and tryed stuff out but nothing works for me.
If possible some explanations on cPanel maybe would be enough.

<?php
require("xmlapi.php"); // this can be downlaoded from https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php
$xmlapi = new xmlapi("cpanlel host name");
$xmlapi->set_port( 2083 );
$xmlapi->password_auth('cpanel username','cpanel passsword');
$xmlapi->set_debug(0);//output actions in the error log 1 for true and 0 false
$cpaneluser='cpanel username';
$databasename="something";
$databaseuser="database username";
$databasepass= 'database password';
//create database
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
//create user
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
//add user
$addusr = $xmlapi->api1_query($cpaneluser, 'Mysql', 'adduserdb', array('' . $databasename . '', '' . $databaseuser . '', 'all'));
?>
Using the above code you will be able to create new database, add new user to database and give all access to user on database.

Related

Which username/password do I use to connect to mySQL

So, I'm SUPER new to mySQL. Having issues connecting to my database with PHP. Hoping someone can point me in the right direction.
I can login to our Cpanel using my username/password. Using the web gui I was able to create a database.
Now when I try to connect to the database (or even just the server for that matter) using PHP I get an error:
Warning: mysqli::__construct(): (HY000/1045): Access denied for user 'username'#'servername' (using password: YES) in /home/ropepart/public_html/techportal/sandbox/mysqltest.php on line 8
Connection failed: Access denied for user 'username'#'servername' (using password: YES)
To me, it seems like this is a username/password error. But I an using the same username/password that I use to login to the web gui. Why can I successfully login there, but can't login with PHP?
Here's my code (taken pretty much directly from W3Schools):
<?php
$servername = "servername";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
(Hopefully it's obvious that I've changed my servername/username/password for the purposes of this post)
Check the details correctly, By deafult
host = localhost
username = root
password = (No password leave it as empty)
database = (your database)
<?php
$connection = new mysqli('host','username','password','your_database');
if($connection->connect_error || $connection->error){
echo "error";
}else{
echo "done";
}
?>
you should add database name.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "demo"
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
//if you are using xampp you shoul locate this file you get information from this
passwords.txt
MySQL database username/password is not necessarily same as cPanel username & password.
Here is what you should do:
Login to your cPanel
From dashboard click "MySQL® Databases"
Add a new user from there (https://prnt.sc/kpiby9). Just fill username
and password (note down the password).
Add that user with your database by selecting both from the dropdown
(https://prnt.sc/kpidqx)
Now, use this username & password to connect with the database.
mysqli_connect(serverhostname,username,password,dbname);

Is it possible to obtain a cpanel mysql database prefix?

$db_connection = $_SERVER['DOCUMENT_ROOT'] . '/includes/install/database_connection.php';
if (!file_exists($db_connection)) {
require("install/xmlapi.php");
if (isset($_POST['cpname'])) {
$opts['user'] = $_POST['cpname'];
$opts['pass'] = $_POST['cppass'];
$opts['temp'] = substr(str_shuffle(md5(time())),0,'12');
$xmlapi = new xmlapi($_SERVER['HTTP_HOST']);
$xmlapi->set_port( 2083 );
$xmlapi->password_auth($opts['user'],$opts['pass']);
$xmlapi->set_debug(0);
$cpaneluser=$opts['user'];
$databasename="OSMP_DAT";
$databaseuser="OSMP_admin";
$databasepass=$opts['temp'];
$db = $databasename;
$user = $databaseuser;
$pass = $databasepass;
$loc = 'localhost';
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array("".$cpaneluser."_".$databasename."", "".$cpaneluser."_".$databaseuser."", 'all'));
include ('install/installer.php');
exit;
}
if (!isset($_POST['dbhost'])) { include ('install/db_installer.php'); }
if (isset($_POST['dbhost'])) {
// save connection details to $db_connection
}
}
The above code works flawlessly as one would expect.
First it checks for the existence of database_connection.php. If it exists, it includes the file which contains database details.
If not - we are assuming its a first time install. So we are asking a user for cpanel login details, and our script creates the database and saves details to database_connection.php.
The only problem ... is database prefixes. When the database is created, if the WHM has database prefixes set for the user account, then a database prefix is prefixed to the database name.
I want to know how to determine if there is a prefix, and if so how to find out what it is so the script can prefix it on the database name as well.
Note I am not seeking a table prefix, but rather the database prefix as added by cpanel/whm
So apparently cpanel by default if prefixing is enabled used the first 8 characters of ones username followed by an underscore. This is used for both database and database names.
So I simply modified the above code as follows:
$db_connection = $_SERVER['DOCUMENT_ROOT'] . '/includes/install/database_connection.php';
if (!file_exists($db_connection)) {
require("install/xmlapi.php");
if (isset($_POST['cpname'])) {
$opts['user'] = $_POST['cpname'];
$prefix = substr($opts['user'],0,8).'_';
if ($prefix === FALSE) {$prefix = $opts['user'];}
$opts['pass'] = $_POST['cppass'];
$opts['temp'] = substr(str_shuffle(md5(time())),0,'12');
$xmlapi = new xmlapi(localhost);
$xmlapi->set_port( 2083 );
$xmlapi->password_auth($opts['user'],$opts['pass']);
$xmlapi->set_debug(1);
$cpaneluser=$opts['user'];
$databasename="OSMP_DAT";
$databaseuser="osmp";
$databasepass=$opts['temp'];
$pass = $databasepass;
$loc = 'localhost';
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array($databasename, $databaseuser, 'all'));
$db = $prefix.$databasename;
$user = $prefix.$databaseuser;
include ('install/installer.php');
exit;
}
if (!isset($_POST['dbhost'])) { include ('install/db_installer.php'); }
if (isset($_POST['dbhost'])) {
// save connection details to $db_connection
}
}
So now a check is done to determine the length of the username and if longer than 8 characters, its truncated to 8. Then the understore is added and output as variables to pass along to the next part of the script.
The only flaw left as I can see is if the host has disabled the prefixing in whm, so I am well on my way.
For anyone attempting to use this code in the future - make note you
need to secure the included files or you are going to have whopping
security problems. As this code stands someone could manually call
install/db_installer.php or install/installer.php and bypass the
(!file_exists($db_connection)) check and the if (isset($_POST)) and
the (!isset($_POST['dbhost'])).
DO NOT USE THIS CODE IF YOU DON'T KNOW HOW TO SECURE IT!

Can't create database from coding but can from cpanel

The database test_new_1 is able to create for the user testcom directly from the cpanel, But not able to create through php. Another server it is working properly, the only difference username and database prefix is same in that server.
Error Shows:
Error creating database: Access denied for user 'testcom'#'localhost' to database 'test_new_1'
PHP
// Create connection
$conn = mysqli_connect('localhost', 'testcom', '123456');
// Check connection
if (!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS test_new_1";
if (mysqli_query($conn, $sql))
{
echo "Database created successfully";
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
cPanel does not allow you to create databases directly from with MySQL function. You need to use the API provided to you by cPanel:
Download xmlapi.php from https://github.com/CpanelInc/xmlapi-php/blob/master/xmlapi.php then use it:
<?php
include("xmlapi.php");
$db_host = 'yourdomain.com';
$cpaneluser = 'your cpanel username';
$cpanelpass = 'your cpanel password';
$databasename = 'testdb';
$databaseuser = 'test'; // Warning: in most of cases this can't be longer than 8 characters
$databasepass = 'dbpass'; // Warning: be sure the password is strong enough, else the CPanel will reject it
$xmlapi = new xmlapi($db_host);
$xmlapi->password_auth("".$cpaneluser."","".$cpanelpass."");
$xmlapi->set_port(2082);
$xmlapi->set_debug(1);//output actions in the error log 1 for true and 0 false
$xmlapi->set_output('array');//set this for browser output
//create database
$createdb = $xmlapi->api1_query($cpaneluser, "Mysql", "adddb", array($databasename));
//create user
$usr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduser", array($databaseuser, $databasepass));
//add user
$addusr = $xmlapi->api1_query($cpaneluser, "Mysql", "adduserdb", array("".$cpaneluser."_".$databasename."", "".$cpaneluser."_".$databaseuser."", 'all'));
?>

error when trying to connect with sftp

I am trying to establish connection using sftp class
my code:
$host = 'some ip address';
$username = 'username';
$pass = 'password';
$sftp = new SFTPConnection($host, 22);
$sftp->login($username, $pass);
When i run this script i get message Could not authenticate with username and password
When i use same user and pass in fileZilla with sftp, then is ok, I can establish connection, but with script i cant
Anyone know what is the problem?
Ok, here what was the problem...
My IP address wasnt been allowed on FTP server?! Now when they put my IP on whitelist, everything working just fine.
Thank you guys for your effort.
Try to add this code in your sftp.php in login(){} function. Then tell what error does it give:
if (!extension_loaded('ssh2'))
{
throw new Exception("Extension ssh2 has to be loaded to use this class. Please enable in php.ini.");
}
if (! #ssh2_auth_password($this->connection, $username, $password))
throw new Exception("Could not authenticate with username $username " . "and password $password.");
$this->sftp = #ssh2_sftp($this->connection);
if (! $this->sftp)
throw new Exception("Could not initialize SFTP subsystem.");
Edit your code to do the following[ as some people say that we should authenticate both via username_password and as well as hostKeyAuthentication ]
-------------------------------
The above description shows that:
The issue lies in the php extension assuming that you’re going to authenticate either with a password or with a public key. Because of that assumption, authenticating with a password will give you a failure and could throw you off into the wrong direction (brief description is in the link: Must Read).
$connection = ssh2_connect($host, $port);
ssh2_auth_password($connection, $username, $password);
if (ssh2_auth_pubkey_file($connection, $username, $pubkey, $privatekey)) {
echo "Public Key Authentication Successful";
}
else {
echo 'Public Key Authentication Failed' ;
return false;
}

Mongodb PHP driver: how to create database and add user to it?

so using the mongodb shell, I was able to create a database and add a username and password to it. How can I do the same in php? I have everything installed and able to connect to mongodb server.
However, I can't find any information in the doc.
I do not believe addUser() is implemented in the PHP driver.
However, there is an execute that should allow you to do an addUser() the same way you would from the mongo shell:
EDIT: After testing, I couldn't get execute to do what you wanted, but I did find that the following works:
<?php
// open connection
$mongo = new Mongo("mongodb://" . MONGO_USER . ":" . MONGO_PASS . "#" . MONGO_HOST, array("persist" => "abcd1234"));
$db = $mongo->selectDB("admin");
// user info to add
$username = "testUser";
$password = "testPassword";
// insert the user - note that the password gets hashed as 'username:mongo:password'
// set readOnly to true if user should not have insert/delete privs
$collection = $db->selectCollection("system.users");
$collection->insert(array('user' => $username, 'pwd' => md5($username . ":mongo:" . $password), 'readOnly' => false));
?>
That adds a new user to the admin db on my server - checked via mongo shell after executing PHP script.
That said - why do you want to add a Mongo user from a PHP script?
A way to create a new mongodb user from PHP is via MongoDB::command:
//info to add
$db_name = 'db_name';
$db_user = 'new_user';
$db_pass = 'new_pass';
//autenticate with a user who can create other users
$mongo = new MongoClient("mongodb://root:root#localhost/admin");
$db = $mongo->selectDB( $db_name );
//command to create a new user
$command = array
(
"createUser" => $db_user,
"pwd" => $db_pass,
"roles" => array
(
array("role" => "readWrite", "db" => $db_name)
)
);
//call MongoDB::command to create user in 'db_name' database
$db->command( $command );
Tested with mongo 3.0 and PHP mongo driver 1.6

Categories