Basic AES-128-CBC/AES-256-CBC Encryption/Decryption with PHP

For AES-128-CBC Encryption/Decryption | PHP

To use CBC encryption, you also need to sort the $iv offset, as follows: AES-128-CBC encryption and decryption.

Here i used simple keys for the example, But Keys need to be generated using a cryptographically secure random number generator if you are using this in a production.

$iv = '1234567890123456'; // 16 byte
$key = '1234567890123456'; // 16 byte
function decode($str,$key,$iv)
{
    return openssl_decrypt(base64_decode($str),"AES-128-CBC",$key,OPENSSL_RAW_DATA, $iv);
}

function encode($str,$key,$iv)
{
     return base64_encode(openssl_encrypt($str,"AES-128-CBC",$key,OPENSSL_RAW_DATA, $iv));
}

echo "String: Hellow World !";
echo "<br/>Encrypted String: ";
echo encode("Hellow World !",$key,$iv);
echo "<br/>Decryped String: ";
echo decode("l3mMP/irpStRPTIfYsdZmg==",$key,$iv); 

OUT PUT

String: Hellow World !
Encrypted String: l3mMP/irpStRPTIfYsdZmg==
Decryped String: Hellow World !

 

 

For AES-256-CBC Encryption/Decryption | PHP

function encrypt_decrypt($action, $string) 
    {
        $output = false;
        $encrypt_method = "AES-256-CBC";
        $secret_key = '12345678901234561234567890123456'; // 32 byte
        $secret_iv = '1234567890123456'; // 16 byte $key = hash('sha256', $secret_key); $iv = substr(hash('sha256', $secret_iv), 0, 16); if ( $action == 'encrypt' ) { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = base64_encode($output); } else if( $action == 'decrypt' ) { $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv); } return $output; } echo "String: Hellow World !"; echo "<br/>Encrypted String: "; echo encrypt_decrypt('encrypt', "Hellow World !"); echo "<br/>Decryped String: "; echo encrypt_decrypt('decrypt', "QkNZWjlab2pSTUtqVnMyMHlYeTV4dz09");

 

OUT PUT

String: Hellow World !
Encrypted String: QkNZWjlab2pSTUtqVnMyMHlYeTV4dz09
Decryped String: Hellow World !

Basic AES-128-ECB Encryption/Decryption with PHP

Note: ECB is useful for random data, but structured data should use a stronger mode like MCRYPT_MODE_CBC, Because ECB is an insecure method for sensitive data.

Lets see an example of its usage in PHP.

The Key must be 16bit long.

    $key = '1234567890123456';
   
    function encrypt($data,$key) {
        return base64_encode(openssl_encrypt($data, "aes-128-ecb", $key, OPENSSL_RAW_DATA));
    }

    function decrypt($data,$key) {
        return openssl_decrypt(base64_decode($data), "aes-128-ecb", $key, OPENSSL_RAW_DATA);
    }

 

To Encrypt, Simply call

$data = "This is to be encrypted";
echo $encrypted_text = encrypt($data,$key);

 

To Decrypt the above encrypted text

$data = "This is to be encrypted";
$encrypted_text = encrypt($data,$key);

$data = $encrypted_text;
echo $decrypted_text = decrypt($data,$key);

But there are other problems in this code which make it insecure, in particular the use of ECB (which is not an encryption mode, only a building block on top of which encryption modes can be defined).

Why ECB is insecure ?

You have a cipher, that with a key will encrypt 16 bytes of data. And you have some data, that is more than 16 bytes. Its a problem. ECB is the wrong solution to that problem: you just encrypt each 16-bytes block separately.

Why is it wrong? Because this way blocks that were equal before encryption will remain equal also after! And this will lead to all kinds of unwanted consequences.

 

Simple REST API php/mysql

REST meaning of “REpresentational State Transfer”. It is a concept or an architecture for transfer information over the internet with unique and standard structure specially designed for it. REST concepts/architectures are referred as resources. A representation of a resource must be stateless and it is usually represented in JSON format.

API meaning of “Application Programming Interface”. It is a set of rules/methods that allows one piece of software application to talk to another with specially defined rules/methods with its own structure. Those “rules/methods” can include for create, read, update and delete operations.

Here i have explained, How to make a REST API for a CRUD (CREATE, READ, UPDATE, DELETE) application. For example, i am going to explain here;

I am going to use a test_database with the users table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL,
  `username` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `status` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `users` ADD PRIMARY KEY (`id`);
ALTER TABLE `users` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;

Here are some test data to the table, for the testing purpose.

INSERT INTO `users` (`id`, `first_name`, `last_name`, `email`, `username`, `password`, `status`) VALUES
(1, 'John', 'Doe', 'jd@gmail.com', 'john', '2829fc16ad8ca5a79da932f910afad1c', 1),
(2, 'Peter', 'Alex', 'peter@gmail.com', 'peter', '827ccb0eea8a706c4c34a16891f84e7b', 1);

Let’s start to make a simple REST API step by step using PHP/MySQL according to the following;

How to create an user in the database ?
How to read user’s information from the database ?
How to update user’s information in the database ?
How to delete an user from the database ?

Additionally,

How to get all users list from the database ?
How to search users from the database ?

For the database connection i am using my database class discussed in a previous article. https://blogs.webservice.lk/2020/02/28/phpmysql-database-class/

How to create an user in the database ?

To create a user, we need to pass data to the create_user.php file. Here we only allow POST method to transfer data between the API and the application. API will return response in JSON format.

In this JSON response i have used;

response  – to get the status success/unsuccess
message – to describe the status
count – to get the row count in the data result (When fetching rows)
data – to get the fetched data. (Sometimes, insert id for insert operations)

create_user.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require('class.database.php');

$arr = [];
if($_SERVER['REQUEST_METHOD']=="POST"){
    if(isset($_POST['first_name'])) $first_name = $database->escape($_POST['first_name']);
    if(isset($_POST['last_name'])) $last_name = $database->escape($_POST['last_name']);
    if(isset($_POST['username'])) $username = $database->escape($_POST['username']);
    if(isset($_POST['password'])) $password = $database->escape($_POST['password']);
    if(isset($_POST['email'])) $email = $database->escape($_POST['email']);

    if(isset($first_name) && !empty($first_name)){
        if(isset($last_name) && !empty($last_name)){
            if(isset($username) && !empty($username)){
                if(isset($password) && !empty($password)){
                    if(isset($email) && filter_var($email,FILTER_VALIDATE_EMAIL)){
                        $sql = "INSERT INTO `users` 
                        (
                            `first_name`,`last_name`,`username`,`password`,`email`
                        ) 
                        VALUES (
                            '$first_name','$last_name','$username','".md5($password)."','$email'
                        )";

                        $insert_id = $database->insert($sql);

                        if($insert_id>0){
                            $arr = ["response"=>"success","message"=>"User successfuly created.","id"=>$insert_id];
                        }
                        else $arr = ["response"=>"unsuccess","message"=>"Create user failed. ".$database->error()];
                    }
                    else $arr = ["response"=>"unsuccess","message"=>"Valid email required !"];
                }
                else $arr = ["response"=>"unsuccess","message"=>"Password required !"];
            }
            else $arr = ["response"=>"unsuccess","message"=>"Username required !"];
        }
        else $arr = ["response"=>"unsuccess","message"=>"Last name required !"];
    }
    else $arr = ["response"=>"unsuccess","message"=>"First name equired !"];
}
else  $arr = ["response"=>"unsuccess","message"=>"Bad request !"];

echo json_encode($arr);
?>

We can test this create_user.php using POSTMAN or any REST API testing tool like RESTer extension installed in Firefox web browser. According to this example, we need to pass First Name, Last Name, Username, Password and the Email to create a new user as below.

 

How to read user’s information from the database ?

To read information for an user, we need to pass user’s id to get_user.php file and get the result related to the sent user id. Data can be sent only via POST method.

get_user.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require('class.database.php');

$arr = [];
if($_SERVER['REQUEST_METHOD']=="POST"){
    if(isset($_POST['id'])) $id = $database->escape($_POST['id']);

    if(isset($id) && !is_null($id) && $id>0){
        $sql = "SELECT * FROM `users` WHERE `id`='$id'";
        $results = $database->select($sql);
        $count = $database->num_rows($sql);

        if($count>0){
            $arr = ["response"=>"success","data"=>$results[0]];
        }
        else $arr = ["response"=>"unsuccess","message"=>"User not found !".$database->error()];                   
    }
    else $arr = ["response"=>"unsuccess","message"=>"Id required !"];
}
else  $arr = ["response"=>"unsuccess","message"=>"Bad request !"];

echo json_encode($arr);
?>

API will return response in JSON format. Here is the test result for sent id as 1. This will show the result for user id 1.

How to update user’s information in the database ?

To update an user, we need to send the id of the user we need to update and the required data to update in the database.

update_user.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require('class.database.php');

$arr = [];
if($_SERVER['REQUEST_METHOD']=="POST"){
    if(isset($_POST['id'])) $id = $database->escape($_POST['id']);
    if(isset($_POST['first_name'])) $first_name = $database->escape($_POST['first_name']);
    if(isset($_POST['last_name'])) $last_name = $database->escape($_POST['last_name']);
    if(isset($_POST['username'])) $username = $database->escape($_POST['username']);
    if(isset($_POST['password'])) $password = $database->escape($_POST['password']);
    if(isset($_POST['email'])) $email = $database->escape($_POST['email']);

    if(isset($id) && !is_null($id) && $id>0){
        if(isset($first_name) && !empty($first_name)){
            if(isset($last_name) && !empty($last_name)){
                if(isset($username) && !empty($username)){
                    if(isset($password) && !empty($password)){
                        if(isset($email) && filter_var($email,FILTER_VALIDATE_EMAIL)){
                            $sql = "UPDATE `users`SET 
                            `first_name`='$first_name',`last_name`='$last_name',`username`='$username',
                            `password`='".md5($password)."',`email`='$email'
                            WHERE id='$id'";

                            if($database->query($sql)===true){
                                $arr = ["response"=>"success","message"=>"User successfuly updated."];
                            }
                            else $arr = ["response"=>"unsuccess","message"=>"Update user failed. ".$database->error()];
                        }
                        else $arr = ["response"=>"unsuccess","message"=>"Valid email required !"];
                    }
                    else $arr = ["response"=>"unsuccess","message"=>"Password required !"];
                }
                else $arr = ["response"=>"unsuccess","message"=>"Username required !"];
            }
            else $arr = ["response"=>"unsuccess","message"=>"Last name required !"];
        }
        else $arr = ["response"=>"unsuccess","message"=>"First name equired !"];
    }
    else $arr = ["response"=>"unsuccess","message"=>"Id required !"];
}
else  $arr = ["response"=>"unsuccess","message"=>"Bad request !"];

echo json_encode($arr);
?>


How to delete an user from the database ?

To delete an user from the database, we need to pass the id of the user in the database to the delete_user.php file. Here i am not going to delete the user information from the database and used a status field to update the user’s status to the value zero. So status=0 rows are deleted users. [We should not delete important data permanently in our real applications, because these records will very important in one day to audit some database operations.]

delete_user.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require('class.database.php');

$arr = [];
if($_SERVER['REQUEST_METHOD']=="POST"){
    if(isset($_POST['id'])) $id = $database->escape($_POST['id']);

    if(isset($id) && !is_null($id) && $id>0){
        $sql = "UPDATE `users` SET `status`=0 WHERE `id`='$id'";

        if($database->query($sql)===true){
            $arr = ["response"=>"success","message"=>"User successfuly deleted."];
        }
        else $arr = ["response"=>"unsuccess","message"=>"Delete user failed. ".$database->error()];                   
    }
    else $arr = ["response"=>"unsuccess","message"=>"Id required !"];
}
else  $arr = ["response"=>"unsuccess","message"=>"Bad request !"];

echo json_encode($arr);
?>

How to get all users list from the database ?

To get all users we can sent request using POST method without any parameters since we don’t want to add any filter to the fetching result. Here i have only returned the rows with status=1. Because status=0 are the deleted rows and we don’t need to show them when fetching users from the database.

get_users.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require('class.database.php');

$arr = [];
if($_SERVER['REQUEST_METHOD']=="POST"){
        $sql = "SELECT * FROM `users` WHERE `status`=1 ";
        $results = $database->select($sql);
        $count = $database->num_rows($sql);

        if($count>0){
            $arr = ["response"=>"success","count"=>$count,"data"=>$results];
        }
        else $arr = ["response"=>"unsuccess","message"=>"No users found. ".$database->error()];
}
else  $arr = ["response"=>"unsuccess","message"=>"Bad request !"];

echo json_encode($arr);
?>

Here is the test result using RESTer extension installed in the Firefox web browser.

How to search users from the database ?

To search users from the database, we can send search parameters to the serach_user.php file. According to this example, we can search users using their First Name, Last Name, Username and Email.

search_user.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
require('class.database.php');

$arr = [];
if($_SERVER['REQUEST_METHOD']=="POST"){
    if(isset($_POST['first_name'])) $first_name = $database->escape($_POST['first_name']);
    if(isset($_POST['last_name'])) $last_name = $database->escape($_POST['last_name']);
    if(isset($_POST['username'])) $username = $database->escape($_POST['username']);
    if(isset($_POST['email'])) $email = $database->escape($_POST['email']);

        $sql = "SELECT * FROM `users` WHERE `status`=1 ";

        if(isset($first_name) && !empty($first_name)){
            $sql .= " AND `first_name` LIKE '%".$first_name."%' ";
        }
        if(isset($last_name) && !empty($last_name)){
            $sql .= " AND `last_name` LIKE '%".$first_name."%' ";
        }
        if(isset($username) && !empty($username)){
            $sql .= " AND `username` LIKE '%".$first_name."%' ";
        }    
        if(isset($email) && !empty($email)){
            $sql .= " AND `email` LIKE '%".$first_name."%' ";
        }
        
        $results = $database->select($sql);
        $count = $database->num_rows($sql);

        if($count>0){
            $arr = ["response"=>"success","count"=>$count,"data"=>$results];
        }
        else $arr = ["response"=>"unsuccess","message"=>"No users found for the search. ".$database->error()];
}
else  $arr = ["response"=>"unsuccess","message"=>"Bad request !"];

echo json_encode($arr);
?>

Matched search response will returned the status, row count and the result in JSON format.

Likewise, we can create a simple REST API using PHP/MySQL for our cross-platform applications to communicate between the database and the application. This is just an example only. To use this in a production application, we need to think about it’s security and many more things.

You can download this source files from my Github: https://github.com/lahirutm/REST-API-php-mysql

Bootstrap 4 Login Page – PHP/MySQL

Here i have created a login page where user can enter their email address and password. When user submit the form, inputs will be verified against the credentials stored in the database, if the email and password match, the user is authorized and granted. Otherwise it will display error message.

You would need database connection to connect to MySQL database.

I have already posted a post about creating a database class for PHP/MySQL. I would suggest you to go through the previous post PHP/MySQL Database Class before following this.

login.php

Let’s create a file named “login.php” and place the following code. This file contains php scripts and HTML code for the login page. Here i have fetched the user from the database according to the entered username and compared the password hash in the database with the entered password’s hash (I have used md5 password hashing method). If both hashes are exactly same, register user id in the session and redirect to the index.php page.

<?php
require('class.database.php');

if(isset($_POST['submit'])){
	if(isset($_POST['username'])){
		if(isset($_POST['password'])){
			$username = $database->escape($_POST['username']);
			$password = $database->escape($_POST['password']);

			$sql = "SELECT * FROM users WHERE username='$username'";
			$results = $database->select($sql);
			if(is_array($results) && count($results)>0){
				$password_hash = $results[0]['password'];
				if($password_hash==md5($password)){
					// Username & password correct
					session_start();
					$_SESSION['user_id'] = $results[0]['id'];
					header('location:index.php');
				}
				else $ermsg = "Password incorrect !";
			}
			else $ermsg = "User not found !";
		}
		else $ermsg = "Password required !";
	}
	else $ermsg = "Username required !";
}
?>
<!DOCTYPE html> 
<html lang="en"> 
<head> <!-- Required meta tags --> 
  <meta charset="utf-8"> 
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> 
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <!--Fontawesome CDN-->
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
  <title>Login</title> 
</head> 
<body> 


<div class="container">
		<?php 
		if(isset($ermsg) && !empty($ermsg)) {
			echo '<div class="alert alert-danger" role="alert">'.$ermsg.'</div>';
		}
		?>
	<div class="d-flex justify-content-center h-100">
		<div class="card">
			<div class="card-header">
				<h3>Login</h3>
			</div>
			<div class="card-body">
				<form method="post">
					<div class="input-group form-group">
						<div class="input-group-prepend">
							<span class="input-group-text"><i class="fas fa-user"></i></span>
						</div>
						<input type="text" name="username" class="form-control" placeholder="username">
						
					</div>
					<div class="input-group form-group">
						<div class="input-group-prepend">
							<span class="input-group-text"><i class="fas fa-key"></i></span>
						</div>
						<input type="password" name="password" class="form-control" placeholder="password">
					</div>
					<div class="form-group">
						<input type="submit" name="submit" value="Login" class="btn float-right login_btn">
					</div>
				</form>
			</div>
		</div>
	</div>
</div>


  <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> 
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> 
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> 
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> 
</body> 
</html>

 

After successful login, it will display a simple index.php page with the logout button for logout when needed.

index.php

<?php 
session_start();
// if the user is not logged in, then redirect to the login page
if(!isset($_SESSION["user_id"])){
    header("location:login.php");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <title>Simple Bootstrap4  - Login PHP/MySQL</title>
  </head>
  <body>
    <h1>Login Successful !</h1>
    <h2>
    <a href="logout.php">
    <button class="btn btn-warning">Logout</button>
    </a>
    </h2>
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  </body>
</html>

 

logout.php

This uses for clear the login session we created and destroy all other sesions by destroying the session and redirect back to the login page.

<?php 
session_start();
// Unset all session variables
$_SESSION = array();
// Destroy the session.
session_destroy();
// Redirect to the login page
header("location:login.php");
exit();
?>

Download the complete source code sample database from my Github: https://github.com/lahirutm/Bootstrap-4-Login-Page—PHP-MySQL

PHP/MySQL Database Class

This is a simple and easy database class to use in a PHP/MySQL application. I have used Object Oriented Programing (OOP) methods to made this very useful in OOP applications.

class.database.php

<?php
// database class
class database {
    protected static $connection;
    
    var $hostname="localhost";
    var $username="root";
    var $password="";
    var $database="test_database";

    public function __construct() {
        
    }

    public function connect() {    
        if(!isset(self::$connection)) {               
            self::$connection = new mysqli($this->hostname,$this->username,$this->password,$this->database);
        }

        // If connection was not successful, handle the error
        if(self::$connection === false) {
            // Handle error - notify administrator, log to a file, show an error screen, etc.
            return false;
        }

        self::$connection -> query("SET NAMES 'utf8'");

        return self::$connection;
    }


    public function query($query) {
        // Connect to the database
        $connection = $this -> connect();
        // Query the database
        $result = $connection -> query($query);

        return $result;
    }

    public function multi_query($query){
        // Connect to the database
        $connection = $this -> connect();

        // Query the database
        $result = $connection -> multi_query($query);

        return $result;
    }

    public function insert($query) {
        // Connect to the database
        $connection = $this -> connect();

        // Query the database
        $connection -> query($query);
        // Get inserted id
        $insertid = $connection -> insert_id;

        return $insertid;
    }

    public function select($query) {
        $rows = array();
        $result = $this -> query($query);
        if($result === false) {
            return false;
        }
        while ($row = $result -> fetch_assoc()) {
            $rows[] = $row;
        }
        return $rows;
    }

    public function num_rows($query) {
        $result = $this -> query($query);
    
        if($result === false) {
            $count = 0;
        }
        else $count = $result->num_rows;
        
        return $count;
    }

    /**
     * Fetch the last error from the database
     * 
     * @return string Database error message
     */
    public function error() {
        return self::$connection -> error;
    }

    /**
     * Quote and escape value for use in a database query
     *
     * @param string $value The value to be quoted and escaped
     * @return string The quoted and escaped string
     */
    public function escape($value) {
        $connection = $this -> connect();
        return $connection -> real_escape_string(trim($value));
    }
}

$database = new database();
?>

How to use this in a PHP application ?

You must include this in your php page where you need to get data from mysql database or write data to mysql database.

Let’s assume, we have system_users table in our test database. Now we want to get users from this table. So, here is my get_users.php file.

<?php
require('class.database.php'); 

$sql = "SELECT `user_name`, `user_email`, `user_password` FROM `system_users` WHERE 1";
$users = $database->select($sql);

echo json_encode($users);
?>

Download source code from my Github: https://github.com/lahirutm/PHP-MySQL-Database-Class

Install PHP 7.3 on Ubuntu 18.04 with Apache

Linux is a very popular environment for [PHP + Apache] server configuration. Ubuntu is a one of popular operating system in Linux family. In this post, i am going to describe the steps for installing PHP 7.3 with Apache2.

Before we start, ensure that your system packages are upto-date. Run the  below to commands to perform system package update and upgrade.

sudo apt update
sudo apt upgrade

This will update the package index and update the installed packages to the latest version.

PHP 7.3 is a not available on Ubuntu 18.04 default repositories. Add the ondrej/php which has PHP 7.3 package and other required PHP extensions.

sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update

If you encounter the error, sudo: add-apt-repository: command not found, install the following package to fix it.

sudo apt install software-properties-common

Now, re-synchronize your system packages to the latest versions.

sudo apt update

Install PHP 7.3 for Apache

Execute the following command to install PHP 7.3

sudo apt install php7.3

After the installation has completed, confirm that PHP 7.3 has installed correctly.

php -v

Now, install some commonly used php-extensions with the following command.

sudo apt install php7.3-common php7.3-mysql php7.3-xml php7.3-xmlrpc php7.3-curl php7.3-gd php7.3-imagick php7.3-cli php7.3-dev php7.3-imap php7.3-mbstring php7.3-opcache php7.3-soap php7.3-zip php7.3-intl -y

Now you have successfuly installed PHP 7.3 on Ubuntu.

Install PHP 7.3 on Windows 7/8/10 with IIS

Internet Information Services (IIS) for Windows is a flexible, secure and manageable Web server for hosting anything on the Web. It is commonly made for windows server operating systems. But we can still use it in any versions of windows operating systems by enabling the feature.

To install IIS on Windows 8

  1. On the Start page, type Control Panel, and then click the Control Panel icon in the search results.
  2. In Control Panel, click Programs, and then click Turn Windows features on or off.
  3. In the Windows Features dialog box, click Internet Information Services.
  4. Pre-selected features that are installed by default, and then select CGI. This selection also installs FastCGI, which is recommended for PHP applications.
  5. Click OK.

To verify that IIS installed successfully, Type the following into a web browser: http://localhost
You will see the default IIS Welcome page.

 

Install PHP by using Web Platform Installer.

The preferred method to install PHP on Windows computer is to use Web Platform Installer (Web PI).

Open a browser to the following website: Microsoft Web Platform Installer.
Click Download It Now, and then click Run.

At the top of the Web Platform Installer window, click Products.

Click Frameworks, and then select the current latest version of PHP. (At this writing, the current latest version is PHP 7.3)

Click Install.

The Web Platform Installation page displays the version of PHP and its dependencies that will be installed.

Click I Accept. Web PI installs the PHP packages.

Click Finish.

Test the PHP installation

Open a text editor, for example Notepad, as Administrator.
In a new file, type the following text:

<?php phpinfo(); ?>

Save the file as C:\inetpub\wwwroot\phpinfo.php
Open a browser and enter the following URL: http://localhost/phpinfo.php

A nicely formatted webpage is displayed showing the current PHP settings.