Security and .ini file - php

Is it safe to store data required to connect to a database in a .ini file ?
I build something like this
<?php
include_once($_SERVER['DOCUMENT_ROOT']."proto/class/Database.php");
function connect()
{
$config = parse_ini_file($_SERVER['DOCUMENT_ROOT']."proto/admin/config.ini");
$host = $config['host'];
$username = $config['username'];
$password = $config['password'];
$database = $config['dbname'];
$db = new Database($host,$username,$password,$database);
return $db;
}
?>
I wonder if using important variables within a function is a good way to proceed.

If you save your infos in an ini file or in a php file is a personal thing I guess. What makes it secure is that your file should not be saved in your public web path.
So ensure that the file you read/include is outside of your document root.

I would ask why? Why not make it a PHP file?
<?php
return array(
"host" => "...",
"username" = "...",
//...
);
Then when you need it, just call $config = require "config.php";
This is better than an ini file, since it's parsed (you'll get syntax errors for mistakes rather than ignoring the mistake) and since the parsing is cachable (opcode cache).
Additionally, it's protected from direct web access even if it's in the webroot (or a server misconfiguration allows direct access to the file).

Related

How to use database password?

I am very new to php. Currently I am working on a project, where data from a database server should be fetched and then returned to a client. I have got this little code snippet:
<?php
$host_name = 'host';
$database = 'db';
$user_name = 'user';
$password = 'passwd';
$link = new mysqli($host_name, $user_name, $password, $database);
if ($link->connect_error) {
die('<p>Connection failed</p>');
} else {
echo '<p>Connection success.</p>';
}
?>
The ugly part is, that the password is written in the source code. When using gitlab or something similar, the password is always uploaded - in each software version. This is (of course) a huge security risk. How can I make this more safe? Store the password in a file and read the file with php to get the database password - would that be a good solution?
To do that, you could use a framework like Laravel, but It would be a major change in your development.
What Laravel does is generate a .env file. This file contains all the app credentials (database, mail, etc.). You could do the same : make a file that won't be in your git (add it to your .gitignore) (a JSON file for example).
When you clone the repository, you will just have to create this file.
For example, a JSON file named credentials.json :
{
"database": {
"login": "your-login",
"password": "your-secret-password"
}
}
You can easily read a JSON file with PHP.
Clearly, you have to manage your .htaccess to make this file unreadable from the outside.
Note : you can add to your git repository a blank file to keep the JSON file structure, without the credentials in a credentials-example.json :
{
"database": {
"login": "",
"password": ""
}
}
After cloning, you will just have to rename the file and add the credentials.

Application Instantiation Error displaying when trying to install joomla on a localhost

I created a mySQL database called "testsite" using phpMyAdmin and downloaded all of my joomla files from my live site to the folder wamp/www/testsite. (I already have a live site that I would like to have on a localhost).
When I want to look at the site I get the following error: "Error displaying the error page: Application Instantiation Error"
I undestand this is because the configuration.php file is not set up properly, here is the relevant part of it, I don't know where my mistake is...
public $dbtype = 'mysql';
public $host = 'localhost';
public $user = 'root';
public $password = '';
public $db = 'testsite';
public $dbprefix = '';
I know this does or should not cause the error, but here is the other part that I need to change and am not sure as to what exactly to change, this is what I have tried:
public $log_path = '/C:/wamp/www/testsite/logs';
public $tmp_path = '/C:/wamp/www/testsite/tmp';
Simple answer, the database credentials you have entered in the configuration.php file aren't correct.
This line must be correct as you already mentioned you have created a database called testsite
public $db = 'testsite';
After this, you're supposed to create a user and assign this user to the database. You are currently using the user root which I believe is a default user, however have you assigned it to the database you created? Either way, I would not do this, I would create a completely new user with a password of your choice and assign this one to the database.
Update
You have strict errors appearing on your site. This happens a lot with Joomla and PHP 5.4+
Turn turn them off, firstly, open the php.ini file for wampserver (check the last comment on my answer to another question here)
Then set error reporting to :
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT
Update 2
Here is another approach that worked for me:
In the configuration.php look for public $error_reporting = 'default'; and change it to public $error_reporting = '30711';
I had this problem, but it may have been my fault. I had amended the my.cnf file in the mysql directory.
Set it back to the original settings and all worked ok.
Just for reference the file I edited was:
/etc/mysql/my.cnf

Connecting to database via php code

I am programming a game in PHP and have the following code to connect to a database
//$sqldb=mysql_connect('godaddy.hostedresource.com', 'godaddyUserName', 'godaddyPassword') OR die ('Unable to connect to database! Please try again later.');
$sqldb=mysql_connect('localhost', 'root', 'mypassword') OR die ('Unable to connect to database! Please try again later.');
The trick here is that if I am on the production server I comment out the godaddy database; when I upload the code to the server I then comment out the localhost code instead.
Unfortunately the ineveitable has happened and I uploaded the code with the wrong connection commented out; this led to 24 hours of locked out customers! :(
Is there a way to have the code to tell if it is on the localhost server, and if it isn't it then looks for the godaddy connection?
you can try this to identify if its on live or localhost
if($_SERVER["SERVER_NAME"] == "localhost"
&&
$_SERVER["SERVER_ADDR"] == "127.0.0.1"){
// in localhost
$hostname = "localhost";
$username = "localuser";
$password = "localpassword";
}else{
// not in localhost
$hostname = "livehost";
$username = "liveuser";
$password = "livepassword";
}
and fail if couldn't connect to database but save the error into a file.
if(!mysql_connect($hostname,$username,$password)){
file_put_contents("mysql_connect.error",mysql_error(),FILE_APPEND);
die("Couldn't connect to database");
}
a suggestion, try not to use mysql_* anymore, switch to PDO or mysqli ..
if ($_SERVER['SERVER_NAME'] == 'the.name.of.your.devel.server') {
$host = 'localhost';
} else {
$host = 'name.of.godaddy.server';
}
$sqldb = mysql_connect($host, ....);
i normally use a method of obtaining the URL / domain of the site? This can work in certain situations and setups. Otherwise if your operating with a fixed IP than you can also use this method
Have a look over the methods using $_SERVER
PHP $_SERVER
One way would be for you to check your external IP address and see where you are. A solution should present itself by looking at the properties inside the $_SERVER global variable.
I have a good suggestion : You coding a game , game is a big program, you don't use mysql* function directly in big program , because yourself should handling them, such as error handling.i suggest you use a DB-Handler. please google for : DB-Handler PHP
As has been mentioned by other people, you can obtain the current site your script is running on using the $_SERVER variable. However, I would like to provide an alternative solution.
You could make a folder in your website (both local and production), something like config, then store a configuration file in it, for example config.php, with the following:
<?php
// Local
$db_host = 'localhost';
$db_username = 'root';
$db_password = 'mypassword';
?>
And for production:
<?php
// Production
$db_host = 'godaddy.hostedresource.com';
$db_username = 'godaddyUserName';
$db_password = 'godaddyPassword';
?>
and disallow access to the directory with a .htaccess file in the directory, something like:
deny from all
Then, in your PHP code, do the following:
<?php
require_once($_SERVER["DOCUMENT_ROOT"] . "/config/config.php");
$sqldb=mysql_connect($db_host, $db_username, $db_password) OR die ('Unable to connect to database! Please try again later.');
?>
Now, simply leave the different configuration files where they're at and upload everything else, so your code will access different configuration files whenever it runs.
Also, the .htaccess file should prevent anyone from accessing the file via HTTP, and having the file contents in PHP tags, as well as a .php extension should prevent anyone from seeing any contents if they were able to access the file (PHP would parse the file before it is rendered, and would output nothing).

PHP - Using a function outside the file it has been created in

I have 3 php files. The first (connexion.php) one contains a function I use to create a new PDO connexion:
<?php
header('Content-Type: text/html; charset=utf-8');
date_default_timezone_set('Europe/Paris');
function connexion($host, $user, $pass, $db){
$db_host = $host;
$db_user = $user;
$db_password = $pass;
$db_database = $db;
return $connexion = new PDO("mysql:host=$db_host;dbname=$db_database;charset=utf8", $db_user, $db_password);
}
?>
The second file (my_function.php) contains a function that contains only one function that connects to a db and then is echoing some information.
<?php
include(connexion.php);
function my_first_function(){
try{
$connexion = connexion('localhost', 'user', 'user', 'mydb');
$connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//some code that echoes information
}
catch(...){...}
}
?>
My problem is when I try to include that last file into my third php script in order to be abble to use the function. The script is not even launching. I just have 'internal error'. If I remove the include(my_function.php) my file is loaded properly. I don't get it. Hope someone can help me understand. Thanks in advance. Cheers. Marc. Here below the third file:
<?php
include('connexion.php');
include('my_function.php');
//some code
my_first_function();
?>
You should not use include('connexion.php'); in the third file as it will also be included already automatically when you do include('my_function.php');
As it contains a function declaration, that will lead to an error because that function has already been declared.
"Internal error" is not a PHP thing, you may want to check your .htaccess or other apache settings.
If you are trying to include the file more than once, you will get errors because PHP won't allow you to redeclare a function with the same name. To get around that, use:
include_once("my_include_file.php");
You are either not providing the relative path to the include file or your include file has an error inside it. To test this, try the following code..
if( file_exists('the_file_where_the_function_is.php') )
{
echo "Found the file";
} else {
echo "File not found";
}
If it finds the file, then you most likely have a syntax error in the included file. Also I am guessing you are using IE and getting an "Internal Server Error" ??? If so go into your preferences for IE and turn off friendly error messages to see the actual PHP error.

Edit PHP config file from HTML form

Here's my config file:
<?php
#config variables
$host = ''; #your database host
$user = ''; #your database username
$password = ''; #your database password
$database = ''; #your database title
$page_title = ''; #this appears at the top of the webpage and in the browser tab/window.
$tbl_prefix = ''; #the prefix on your database tables.
$installed = false; #if false, you'll be redirected to an installation page.
if($installed == false) {
header('Location: install/index.php');
}
else {
#connect to db
$consult_err = ' Consult lib/sqlerrors.html';
$connect = #mysql_connect($host, $user, $password)
or die('Errno(1) - Invalid connection details.' . $consult_err);
#mysql_select_db($database, $connect)
or die('Errno(2) - Couldn\'t connect to database.' . $consult_err); #select database
}
?>
I have an installation script that gets all the variables above from a user, checks to make sure there's a mySQL connection/database present, and creates some tables. However, I haven't found a good way to edit the above file with the user's input.
I'm rather stuck on where to go from here, but I need the end result to be taking input from a form, and having the variables in the configuration file reflect that input.
Any suggestions?
I think that doing this will only lead you down a very difficult, twisty path. May I recommend using PEAR's Config package? It can generate, manipulate, and read configuration files in INI, PHP array or constant, XML, or generic formats.
Another option would be to only store the values that change very rarely (e.g. database connection info) in the configuration file and then store the rest of the configuration options in the database. This is how most larger PHP applications do it, I believe (I'm thinking of WordPress specifically). Users will have to edit the file manually if they want to change those settings, but since the more frequently-changed settings are in the database (and that's easy to hook up to your configuration form), they'll only very rarely have to edit the file.
You can use the PHP filesystem functions to open the file and write out a modified version.

Categories