How to secure DB configurations in php - php

I have a php api endpoint as below.
I need to make changes something like:
need to include all the configurations in the seperate file
validate API request using a server token to ensure to accept only genuine requests
Capture all the error logs in a seperate file, instead of showing in the browser
This is my code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$data = json_decode(file_get_contents('php://input'), true);
if(!empty($data)):
header('Content-Type:text/plain');
/*MYSQL CREDENTIALS*/
$hostname = 'localhost';
$username = 'root';
$password = '';
$dbname = 'mydb';
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$arraykey=array_keys($data);
$array=$data[$arraykey[0]];
try
{
foreach($data as $array)
{
//MYSQL execute
$count = $dbh->exec("INSERT INTO gmr(version,visitorId,dwellTime,poiId,srId,zoneId,poiProximityConfidence,zoneProximityConfidence,poiPresenceConfidence,zonePresenceConfidence,normalizedTime) VALUES ('" . implode("', '", $array) . "')" ) or die(print_r($dbh->errorInfo(), true));
echo count($data);
echo 'Data Successfully inserted!!<br />';
}
//echo $data;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
endif;
?>
For point 1) I have put all the configs in a seperate file like:
<?php
define (DB_USER, "root");
define (DB_PASSWORD, "");
define (DB_DATABASE, "mydb");
define (DB_HOST, "localhost");
?>
Need clarity on the better way to include this config file in my main file.
Since im sharing the API endpoint to client, the main file should be able to read my db config files.
So which is suggested to use:
require ("configuration.php");
OR
$config = parse_ini_file('../config.ini');
Suggestion required for other 2 points

Here are suggestion for another two points:
validate API request using a server token to ensure to accept only
genuine requests
For this you can use CSRF Token to check for valid request. you can find here important use of this.
List item Capture all the error logs in a separate file, instead of showing in the browser
By default PHP log everything in server side. in Ubuntu you can find /var/log/apache/error.log
Just you need to check your apache configuration is properly set for error logs
Read here for more info : Where does PHP store the error log? (php5, apache, fastcgi, cpanel)
if you don't want to show your error in browser then you can set error_reporting(0);
Hope this is what you need !!

Related

Open DB Connection within PHP Function

I wrote an addon module for our WHMCS billing system a long time ago that we recently realized was causing some issues. Essentially each module's PHP file is loaded regardless if it is actually used or not, where this is how their "hook" system is setup.
When I wrote the module, I included my "db_config.php" file at the top in the global space, which I now realize is causing this database to load every page and is apparently being written to when it shouldn't be. As this is the case, I would like to open the Database connection at the top of the function and close it at the end of the function.
I've never seen this done before nor can I find much information on it. The contents of my db_config.php appear as follows and I am wondering if I can just include_once() inside of the function?
<?php
// Connection's Parameters
$hostname = "xxx.xxx.xxx.xxx";
$database = "database";
$username = "username";
$password = "password";
// Connection
$tca_conn = mysql_connect($hostname, $username, $password);
if(!$tca_conn)
{
die('Cannot Establish Connection to Database : ' . mysql_error());
}
$tca_db = mysql_select_db($database, $tca_conn);
if (!$tca_db)
{
die ('Cannot Select Database : ' . mysql_error());
}
?>
Try this one.It might work for you.
$tca_db = mysql_select_db($database);
instead of
$tca_db = mysql_select_db($database, $tca_conn);

Development and Production php/MySQL queries management with Mercurial

I have a web project I'm versioning with Mercurial and I don't know how to manage access to two different databases; one is for Development purposes and the other one is for Production.
For now my project is still in development, so I access the dev database and make queries on some of its tables with a php script as for example :
<?php
$dbuser = 'something';
$dbpassword = 'something';
$dbname = 'devDBName';
//~ //connect
$link = mysql_connect('servName', $dbuser, $dbpassword);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
metricsName();
function metricsName()
{
$sql = "SELECT id_metric, name_metric FROM metric";
$result = mysql_query($sql); // result set
while($rec = mysql_fetch_array($result, MYSQL_ASSOC)){
$arr[] = $rec;
};
$data = json_encode($arr); //encode the data in json format
echo '({"success": "true", "message" : "OK","data":' . $data . '})';
}
?>
But I don't know how to access a different database for the Production environment, should I make a copy of these PHP scripts and put explicitly the name of the production database? Or is there a way to "parameterize" this?
Any help would be appreciated.
Separate out your code so that the configuration (i.e. database connections, any other environment specific config / code) is kept in one place.
It makes it easier to maintain (as it's kept centrally), and your build / deployment process can deal with which configuration details need to be used.
Clearly your project is at a very early stage, but this approach will help as it grows.
This example is for mysqli, but the idea should apply to the library you are using. in a config.php file do something like:
//define('DB_HOST_NAME', 'prodserver.com');
define('DB_HOST_NAME', "devserver");
define('DB_NAME', "databasename");
define('DB_USER', "username");
define('DB_PW', "password");
you could put some code around the define statements that will check which server the code is running on and determine which database to connect to. If the dev server for the php is different from the prod server for the php.
Then in your database.php do something like
$include_path = $_SERVER['DOCUMENT_ROOT'] . "/someincludedir";
.....
require $include_path . '/config.php';
......
class myDatabase
{
var $db_host_name = DB_HOST_NAME;
var $db_name = DB_NAME;
var $db_user = DB_USER;
var $db_pw = DB_PW;
var $mysqli;
function connect()
{
$this->mysqli = new mysqli
(
$this->db_host_name,
$this->db_user,
$this->db_pw,
$this->db_name
) or die ("mysqli interface failed");
if( mysqli_connect_errno() )
{
printf("COULD NOT CONNECT TO DATABASE -- mysqli connection failed: %s\n", mysqli_connect_error());
}
}
}
Note that the above class assumes it will be a singleton and if you wanted to have multiple connections to the same or different databases you would then parameterize the database, username, etc for the connect function and you could connect to different databases with different objects.

PHP mysql connect to any remove server the post variables

if (!empty($_POST)) {
$host = $_POST['host'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$db = $_POST['db'];
echo '<pre>';
print_r($_POST);
$con = #mysqli_connect($host . ":3360", $user, $pass, $db);
// $con=#mysqli_connect('192.168.100.42','root','vertrigo','skates');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo 'connected';
}
#mysqli_close($con);
}
I'm using this script to access remote db server in local(basically i want to access local db server through live webiste), howewer, I'm getting an error:
Failed to connect to MySQL: Unknown MySQL server host
'192.168.100.42:3360' (11004)
Please help to get out from this.
192.168.100.42 looks like a local IP. You'd need to try to connect to your static public IP and then forward port 3306 in your router to the 192.168.100.42 machine.
That's not your only problem;
Just because $_POST is not empty, don't assume it has those array keys set and not empty. Syntax like
if(isset($_POST['user'] && !empty($_POST['user'])))
Is much better.
Also, never use $_POST on any database interaction without sanitisation, and never connect to a database with the root user.
I don't know your exact application, but it's impossibly insecure.

ssh2_auth_none returns true

I have a scenario where when i call ssh2_auth_none, it returns true. According to the documentation, it would seem to indicate that this means the switch is configured to allow login without authentication.
However, this is not the case. We are using passwords...
Here's what my code looks like:
<?php
$connection = ssh2_connect('10.124.123.45', 22);
$auth_methods = ssh2_auth_none($connection, 'username');
var_dump($auth_methods);
if (in_array('password', $auth_methods)) {
echo "Server supports password based authentication\n";
}
?>
Just wondering if you have any ideas or comments on what I can test or check to resolve this issue. Ultimately, I'd like to be able to call ssh2_connect and ssh2_auth_password() to login to this switch.
Thanks.
We had to change the way we connect to these types of switches - the root cause of the problem was that this switch has a very limited implementation of ssh and so popular libraries like phpseclib don't work.
here's our code that works - in case it helps anyone else out there who's trying to connect to CISCO's small business class switches.
<?php
$uname = 'myusername';
$pswd = 'mypassword';
$connection = ssh2_connect('123.123.123.123', 22);
//$authentication_methods = ssh2_auth_none($connection, 'user');
$stdio_stream = ssh2_shell($connection);
fwrite($stdio_stream,$uname."\n");
sleep(1);
fwrite($stdio_stream,$pswd."\n");
sleep(1);
echo "Results: " . stream_get_contents($stdio_stream);
echo 'sending show bonjour command:<br>';
fwrite($stdio_stream, "show bonjour".PHP_EOL);
sleep(1);
echo "<br>Results: " . stream_get_contents($stdio_stream);
?>

PHP ignoring mysql_connect requests

I'm new to PHP and have installed on Linux to boot (also a newbie).
Anyway, PHP is working...
<?
$myVar = "test";
echo($myVar);
?>
... works just fine.
But...
<?
$dbhost = "localhost";
$dbuser = "myuser";
$dbpass = "mypass";
$dbname = "mydb";
echo($dbhost . "-" . $dbuser . "-" . $dbpass . "-" . $dbname);
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to MySQL");
print $conn;
mysql_close($conn);
phpInfo();
?>
... does nothing. Nor errors, nothing. Its as if the code isn't even there.
Any help?
Try to do the following:
First make sure display_errors is turned on in your php configuration file. Also set the level of error_reporting to show all errors, including strict (error_reporting = E_ALL|E_STRICT). After you make changes, restart your webserver.
Run phpinfo(), and check that the mysql extension is installed and working. If it isn't make sure that you uncommented it in the php configuration file (again, remember to restart apache after each change to the configuration file).
At this point MySQL should be loaded and working, and you should be able to tell from the error (if it persists) what's the problem.
Try also dumping the contents of the connection result ($conn) to see what it contains.
In general, I'd recommend using long php tags (<?php and not <?) since it is more portable (short tags are off by default in PHP 5 installations).
Try adding this to the top of your code:
error_reporting(E_ALL);
If it does nothing, doesn't that mean that it connected fine? What output do you expect out of that statement?
You could try
error_reporting(E_ALL);
$conn = mysql_connect("localhost", "myusername", "mypassword");
if(!$conn) {
echo 'Unable to connect';
} else {
echo 'Connected to database';
}
var_dump($conn);
edit: Addressing the comment saying that you have a mysql query setup, if you are not seeing "success" it means something is wrong with your query. Add to the above
$sth = mysql_query("SELECT * FROM tablename");
if(!$sth) {
echo 'unable to query: ' . mysql_error();
} else {
echo 'success';
}
Is there more code than you're showing us? The block you have just sets up a connection. You won't see anything at all if it succeeds, you have to use $conn to do something.
To confirm, try changing your password to a deliberately wrong value, and then see if you get an error. If you do, the code works just fine.
Connecting to a database with
$conn = mysql_connect("localhost", "myusername", "mypassword") or die("Unable to connect");
will have no (visible( results if the connection was made succesfully. However, once you run this statement, you can use the other mysql functions to make make queries to the database.
Connecting to a database tells your program "hey, I want to talk to this database".
This code is supposed to create a db connection, nothing else. What do you expect to see?
Try this
<?php
$conn = mysql_connect("localhost", "myusername", "mypassword")
or die("Unable to connect");
print("code sample");
print $conn;
?>
It should print you something like "resource #1"...
And then you may use that connection to communicate with db server

Categories