Securing access data is one of the basic skills used in back-end programming. In many cases, unauthorized access to the database can be dangerous to the operation of our website. Although .php files are not available at a glance, more experienced users can easily browse the server content.
1. Data globalization
The basic and easy way to secure database access data is to extract them from a file .php to file .ini. An additional advantage of this solution is no need to enter the same data in each file .php and the ability to update / change this data quickly across the entire site.
Many platforms today use similar data globalization. For example, in WordPress we have a file wp-config.php, which stores the most important configuration data and database access. It is from him that data is downloaded at connection and it is in this file that we can change access for the entire site.
The first step in this process will be to create a sample file db.ini and supplementing it with data. When entering information into a file .ini remember the order. Going from the left side - name of the variable, space, equal sign, space, variable value. This should be the structure of this file in the most basic version (of course, any order):
servername = example.server.pl
dbname = example_db
username = user1
password = qwerty
2. Reading information
After creating the file .ini (in the example db.ini) should read the data. In PHP, one line of code is enough to read all values from a file .ini:
$config = parse_ini_file ('* path_to_file *');
From now on, all our values from the file .ini have been assigned to the table $config []. If you want to use them, just enter the name of the required variable in square brackets. Example:
$config ['servername']
The example given will give us the value przykladowy.serwer.pl
3. .htaccess security
Before starting this point, make sure our server supports files .htaccess. This file allows you to change settings for directories on the Apache server. The examples provided will not work on Nginx or IIS servers.
On the server, in the location of our file .ini we're creating a file called .htaccess and paste in its content:
# Deny access to .htaccess
Order allow, deny
Deny from all
# Disable directory browsing
Options -Indexes# Hide the contents of directories
IndexIgnore *IndexIgnore * .ini * .php
# Deny access to filenames starting with dot (.)
Order allow, deny
Deny from all
# Deny access to files with extensions .ini, .psd, .log, .sh
Order allow, deny
Deny from all
Order allow, deny
Deny from all
These few lines of code will disable the ability to browse directories and block the opening and displaying of the contents of our data file.
We now have a secured file with our database access data or any data. You can use it in any way and save the variables that we need for global use and easy editing.