Loading...

Follow Bootsity | PHP, Laravel, Angular and Web Develo.. on Feedspot

Continue with Google
Continue with Facebook
or

Valid

1. Introduction

In this article, we learn about SQL injection security vulnerability in web application. We see an example of SQL Injection, learn in in-depth how it works, and see how we can fix this vulnerability. We use PHP and MySQL for the examples. The SQL injection is the top exploit used by hackers and is one of the top attacks enlisted by the OWASP community.

2. What is SQL Injection

SQL Injection is a attack mostly performed on web applications. In SQL Injection, attacker injects portion of malicious SQL through some input interfaces like web forms. These injected statements goes to the database server behind a web application and may do unwanted actions like providing access to unauthorised person or deleting or reading sensitive information.
The SQL Injection vulnerability may affect any application powered by database supporting SQL like Oracle, MySQL and others.
SQL Injection attacks are one of the widest used, oldest, and very dangerous application vulnerabilities. The OWASP organization (Open Web Application Security Project) lists SQL Injections in their OWASP Top 10 document as the top threat to web application security.

3. Example of SQL Injection

Let’s create a form in HTML:

<!DOCTYPE html>
<html>
   <body>
      <h2>SQL injection in web applications</h2>
      <form action="/form-handler.php">
         Username:<br>
         <input type="text" name="username" value="">
         <br>
         Password:<br>
         <input type="password" name="password" value="">
         <br><br>
         <input type="submit" value="Submit">
      </form>
   </body>
</html>

When we click on submit, the form above submits to below PHP script:

<?php

mysql_connect('localhost', 'root', 'root');
mysql_select_db('bootsity');

$username = $_POST["username"];
$password = $_POST["password"];
$query    = "SELECT * FROM Users WHERE username = " . $username . " AND password =" . $password;

$re = mysql_query($query);

if (mysql_num_rows($re) == 0) {
    echo 'Not Logged In';
} else {
    echo 'Logged In';
}
?>
4. How SQL Injection works

In the above example, assume that the user fills up the form as below:

Username: ' or '1'='1
Password: ' or '1'='1

Now our $query becomes:

SELECT * FROM Users WHERE username='' or '1'='1' AND password='' or '1'='1';

This query always returns some rows and results in printing Logged In on the browser. So, here the attacker doesn’t know any username or password that are register in the database, but the attacker is still able to log in.

5. Fixing SQL Injection

Now we understand how SQL injection works in PHP. Generally, the best solution is to use prepared statements and parameterized queries. When we use prepared statements and parameterized queries, the SQL statements are parsed separately by the database engine. Let us see these approaches below:

5.1 Using PDO

We can change our form-handler.php to use PDO:

<?php

$dsn    = "mysql:host=localhost;dbname=bootsity";
$user   = "root";
$passwd = "root";

$pdo = new PDO($dsn, $user, $passwd);

$username = $_POST["username"];
$password = $_POST["password"];

$stmt = $pdo->prepare('SELECT * FROM Users WHERE username = :username AND password = :password');

$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);

$stmt->execute();

if (count($stmt) == 0) {
    echo 'Not Logged In';
} else {
    echo 'Logged In';
}

$stmt->close();
$pdo->close();
?>
5.2 Using MySQLi (Only for MySQL)

We can also use MySQLi in our form-handler.php to fix the SQL Injection issue:

<?php
$servername = "localhost";
$username   = "root";
$password   = "root";
$dbname     = "bootsity";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$username = $_POST["username"];
$password = $_POST["password"];

// prepare and bind
$stmt = $conn->prepare('SELECT * FROM Users WHERE username = ? AND password = ?');
$stmt->bind_param($username, $password);

$stmt->execute();

if (count($stmt) == 0) {
    echo 'Not Logged In';
} else {
    echo 'Logged In';
}

$stmt->close();
$conn->close();
?>
6. More notes on SQL Injection

We saw one way of SQL injection. There can be other ways, as well. It mostly depends on the creativity of the attacker. One other method that may lead to more severe implications is:

Assume the example code:

$username = getRequestString("UserId");
$query = "SELECT * FROM Users WHERE username = " + $username;

If the end user passes the value 1; DROP TABLE profiles;

Then $query becomes SELECT * FROM Users WHERE username = 1; DROP TABLE profiles;

That is why, in our applications, we should use connections having required permissions.

7. Conclusion

In this article, we learned what SQL Injection is and how we can avoid loopholes in our web applications that may result in SQL injections attacks. In the upcoming articles, we will learn more about other security vulnerabilities in web applications. The complete code example that we used is available on Github for your practice. If you have any queries, or you want to share more things related to SQL Injection, you may share in the comments below. Cheers to you.

The post What is SQL Injection and how to fix it appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

1. Introduction

Setting up and managing our own servers can take a considerable amount of time especially if we are not a day to day linux user. That is why we see things like serverless and containers catching on. There’s another option out there though too and it’s called unikernels.

What are unikernels though? Unikernels are simple single application operating systems. Instead of deploying our software on top of linux unikernels create an operating system out of our application and run only that app – nothing else. There’s no concept of usernames/passwords or sshin’g into the application as it is only running one application. Traditionally unikernels have been hard to work with as they used to require expert level of systems knowledge. Now there are newer tools like OPS that fix that.

2. Setup

In the next few minutes we are going to build, run, then deploy a php unikernel. First things first let’s download OPS from https://ops.city:

curl https://ops.city/get.sh -sSfL | sh

We can also download and build it from github. can always go to https://github.com/nanovms/ops and build it from source – it’s written in Go.

3. Build and Run our First PHP Unikernel

Now that we have that let’s create a temporary working directory:

mkdir p && cd p

For this simple example we’ll just use the built-in php webserver just to keep things simple. Put this into a config.json file:

{
 "Args":["-S", "0.0.0.0:3030"],
 "Files": ["index.php"]
}

What this does is tell the built in php webserver to listen on port 3030 and place the index.php file onto the otherwise barren filesystem. We’ll put this into a index.php:

<?php

echo 'hello from php!';

?>

Now let’s run it via:

ops load php_7.2.13 -c config.json -p 3030

Here we tell OPS that we wish to use PHP7. When we are running this it will first download a php package then it looks at the config file and finally opens up a local port on 3030.

We should see this:

[php -S 0.0.0.0:3030]
booting /Users/eyberg/.ops/images/php.img ...
assigned: 10.0.2.15

Assuming that boots we should now be able to hit it with curl:

➜  ~ curl -XGET http://127.0.0.1:3030/
hello from php!% 
➜ ~ curl -XGET http://127.0.0.1:3030/
hello from php!%
4. Deploy to Google Cloud

Great! We just ran our first php unikernel! Now let’s deploy it. Assume have a google cloud account we’ll need a project id, a service worker key, and a cloud storage bucket to place our built images in. We definitely don’t have to use google but we are using it for this example.

We are going to slightly modify our config.json file and put this inside:

{

 "Args":["-S", "0.0.0.0:80"],
 "Files": ["index.php"],
 "CloudConfig" :{
   "ProjectID" :"my-project-id",
   "BucketName":"my-bucket"
 },
 "RunConfig" : {"Memory": "2G"}
}

What this does is tell OPS to place our built image in the bucket ‘my-bucket’ and use ‘my-project-id’. We also changed the port to 80 which is the default HTTP port.

If we got a service worker key we can put that somewhere to source like so:

export GOOGLE_APPLICATION_CREDENTIALS=~/gcloud.json

Then let’s build the image. What this does is create a virtual machine on Google Cloud that contains only our application with the php interpreter. It’s important to note that there is no underlying linux system here. When the virtual machine boots it boots straight into our application just like it did locally. This make it run much faster and safer than linux.

➜  p ops image create -c config.json -p php_7.2.13
[php -S 0.0.0.0:80]
bucket found: nanos-deploy
Image creation started. Monitoring operation operation-1556904873950-587ff29f5fcc5-76e6bf08-ff926925.
..............
Operation operation-1556904873950-587ff29f5fcc5-76e6bf08-ff926925 completed successfullly.
Image creation succeeded nanos-php-image.
gcp image 'nanos-php-image' created...

We should see something like this when it’s done building:

➜  p ops image list
+--------------------+--------+-------------------------------+
|        NAME   | STATUS |          CREATED |
+--------------------+--------+-------------------------------+
| nanos-main-image   | READY | 2019-03-21T15:06:17.567-07:00 |
+--------------------+--------+-------------------------------+
| nanos-node-image   | READY | 2019-04-16T23:16:03.145-07:00 |
+--------------------+--------+-------------------------------+
| nanos-php-image    | READY | 2019-05-03T10:34:34.966-07:00 |
+--------------------+--------+-------------------------------+

Now let’s create an instance. Keep in mind an instance is the server. The image is the actual disk image of the server.

➜  p ops instance create -p prod-1033 -z us-west2-a -i nanos-php-image
Instance creation started using image projects/prod-1033/global/images/nanos-php-image. Monitoring operation operation-1556905041207-587ff33ee1f25-fc8382ab-ec299733.
.....
Operation operation-1556905041207-587ff33ee1f25-fc8382ab-ec299733 completed successfullly.
Instance creation succeeded nanos-php-image-1556905040.

If we look at the instance list we can see it running:

➜  p ops instance list -z us-west2-a -p prod-1033
+----------------------------+---------+-------------------------------+-------------+--------------+
|            NAME   | STATUS |       CREATED | PRIVATE IPS |  PUBLIC IPS |
+----------------------------+---------+-------------------------------+-------------+--------------+
| nanos-php-image-1556905040 | RUNNING | 2019-05-03T10:37:22.465-07:00 | 10.240.0.48 | 35.236.11.13 |
+----------------------------+---------+-------------------------------+-------------+--------------+

Now if we hit that ip up with curl we can see our php unikernel running in Google Cloud!

➜  ~ curl -XGET http://35.236.11.13
hello from php!% 
➜ ~ curl -XGET http://35.236.11.13
hello from php!%

We can also see the logs from the unikernel:

➜  p ops instance logs nanos-php-image-1556905040 -p prod-1033 -z us-west2-a
SeaBIOS (version 1.8.2-20190322_093631-google)
Total RAM Size = 0x0000000080000000 = 2048 MiB
CPUs found: 1     Max CPUs supported: 1
found virtio-scsi at 0:3
virtio-scsi vendor='Google' product='PersistentDisk' rev='1' type=0 removable=0
virtio-scsi blksize=512 sectors=2097152 = 1024 MiB
drive 0x000f2a30: PCHS=0/0/0 translation=lba LCHS=1024/32/63 s=2097152
Booting from Hard Disk 0...
assigned: 10.240.0.48
[Fri May  3 17:39:36 2019] 1.2.3.4:57595 [200]: /
[Fri May  3 17:39:37 2019] 1.2.3.4:57596 [200]: /
[Fri May  3 17:39:59 2019] 92.112.48.216:35338 [200]: /
5. Conclusion

Congratulations! We’ve built, ran and deployed our first php unikernel on google cloud – now we can go show our friends that we don’t need servers to deploy our applications anymore! Unikernels give us the convenience of containers and serverless with the protection and speed of traditional virtual machines.

The post Running PHP Unikernels on Google Cloud appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

1. Introduction

Two-factor Authentication, also known as 2FA is a type, or subset, of Multi-factor Authentication. Multi-factor authentication is a method of confirming identity using by combination of two or more claimed identities. 2FA is a method of confirming users’ claimed identities by using a combination any two different factors from below:

  • something they know
  • something they have
  • something they are

Essentially, this approach allows us to create a restriction for certain areas in our application. It ensures that only the right people have access to the resources in those areas. In this article we are going to take a look at how we can implement 2FA in our Laravel application in really simple steps. Also, we will be using email as our means of verification of user’s identity. Let us dive right in.

2. Setup for Two Factor Authentication

We need the following to get started:

3. The Process or Workflow

When an user tries to access a route protected by 2FA, he gets a mail notification containing an OTP code and is redirected to a form where they can input the OTP.

When this OTP is entered and is verified to be correct, they are able to access the resource, if the code is incorrect, they are not granted access.

The user session will last for the same time as Laravel’s set session lifetime. The duration for this can be found and modified in /config/sessions.php

4. Adding Two-factor Form

We are going to add a form which allows users to enter the OTP that was received in their email addresses and submit it for processing by the application’s backend. The markup for the form can be found here. The excerpt from from code is:

<form action="" method="post">
     @csrf
     <div >
         <label for="token">Token</label>
         <input type="text" name="token" placeholder="Enter OTP" token') ? ' is-invalid' : '' }}" id="token"> 
           @if($errors->has('token'))
              <span  role="alert">
                  <strong>{{ $errors->first('token') }}</strong>
              </span> 
           @endif
        </div>
    <button >Verify</button>
</form>
5. Writing Database Migration

We have to ensure that our users’ migration contains an email field. As we are using email as of of the factor in 2FA in this article. Users migration are generally present in file  /database/migrations/<datetime>_create_users_migration.php

We need two extra fields in the users migration: two_factor_token and two_factor_expiry. We can do this by generating a new migration with this command:

php artisan make:migration add_2fa_fields_to_users_table --table=users

The command above will generate the migration and set the table as users, so we can add the following within the migration’s schema closure:

// this goes in the up() method
$table->string('two_factor_token')->nullable();
$table->datetime('two_factor_expiry')->nullable();

// this goes in the down() method
$table->dropColumn('two_factor_expiry');
$table->dropColumn('two_factor_token');

After saving this file, we will run the command: php artisan migrate to append the fields to the users table.

6. Generating Middleware and Mailables

We are adding a middleware which will serve as a filter for requests coming into the route we protect with 2FA.

To generate the middleware, run:

php artisan make:middleware TwoFactorVerification

In the handle method of this middleware, we are going to check if the current time is greater than the time in the two_factor_expiry field of the users’ migration.

The request will pass if the condition specified evaluates to true, otherwise, a OTP is generated and sent to their mail, they are redirected to the form to input the token they got via email.

Our middleware looks like:

$user = auth()->user();

if ($user->two_factor_expiry > \Carbon\Carbon::now()) {
    return $next($request);
}

$user->two_factor_token = str_random(10);
$user->save();

\Mail::to($user)->send(new TwoFactorAuthMail($user->two_factor_token));

return redirect('/2fa');

Now, we need to generate a mailable (TwoFactorAuthMail) to configure the mail to be sent to the user.

Also, do not forget to import the necessary namespaces and classes.

We can quickly generate the mailable with this command: php artisan make:mail TwoFactorAuthMail

Pass in a $token argument (or variable) to the mailable’s constructor such that in the end, the mailable looks like this:

public $token;

public function __construct($token)
{
    $this->token = $token;
}

public function build()
{
    return $this->view('email.2fa')->subject('Your Authentication Token');
}

After this, add the middleware to the route middleware array in App/Http/Kernel.php:

protected $routeMiddleware = [
    // other middlewares
    'two_factor_auth' => \App\Http\Middleware\TwoFactorVerification::class,
];

Doing this will register the middleware on the app and you can use the middleware on any route/controller you want. For example:

// in routes
Route::middleware('two_factor_auth')->group(function () {
    // routes go here
});

// in controller constructors
public function __construct()
{
    $this->middleware('two_factor_auth');
}
7. Setting up routes

The next thing we are going to do is to set up our routes – a get request to /2fa and a post request to /2fa:

Route::get('/2fa', function () {
    return view('2fa');
}

Route::post('/2fa', function (Request $request) {
    $request->validate([
        'token' => 'required',
    ]);

    if($request->input('token') == Auth::user()->two_factor_token){            
        $user = Auth::user();
        $user->two_factor_expiry = \Carbon\Carbon::now()->addMinutes(config('session.lifetime'));
        $user->save();

        return redirect()->intended('home');
    } else {
        return redirect('/2fa')->with('message', 'Incorrect code.');
    }
});
8. TwoFactorController

We can extract the closures of both the GET and POST requests above to a separate controller. Let us call the controller TwoFactorController and we shall generate it using the command php artisan make:controller TwoFactorController on the terminal.

When the controller is generated, we can have methods to display the form and another method to handle the post request as seen in this snippet:

// show the two factor auth form
public function show2faForm()
{
    return view('2fa');
}

// post token to the backend for check
public function verifyToken(Request $request)
{
    $this->validate(['token' => 'required']);

    $user = auth()->user();

    if ($request->token == $user->two_factor_token) {
        $user->two_factor_expiry = \Carbon\Carbon::now()->addMinutes(config(session.lifetime));
        $user->save();
        return redirect()->intended('/home');
    }

    return redirect('/2fa')->with('message', 'Incorrect token.');
}

As you can see in the POST request method, we first validate that the token was indeed entered in the form otherwise the users get a response that the token is required to proceed.

The routes will look like this after the extraction has been done:

Route::get('/2fa', 'TwoFactorController@show2faForm');
Route::post('/2fa', 'TwoFactorController@verifyToken');

Do keep in mind that the user is already authenticated or logged in on the app, he only doesn’t have access to that particular resource because of the middleware that we have set up earlier.

If the validation passes, we fetched the currently authenticated user, then checked that token entered on the form is the same as the one that was sent to the user then we set the expiry of the token to the session lifetime that was set in config/sessions.php, saved the new data to the user then redirect to our intended route or get bounced back to /home route.

9. Conclusion

In this article, we have learned how to implement two-factor authentication in Laravel applications in very simple steps. The code for this article is available on github. You may, check it out here.

If you do have questions or comments, feel free to discuss in comments.

The post Implementing Two-Factor Authentication in Laravel Applications appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction

Software engineering is a combination of art and science. In this article, we will understand the most basic and essential software design principle: SOLID, which is an acronym for five different principles given by Robert C. Martin. He is famously known as Uncle Bob. Software designed using these principles is easily extensible, maintainable, reusable and better suited to the adaptive or agile style of business needs. Following these principles also help to avoid code smells and leaves the code to be easily refactor-able. Followings are the five principles:

S – Single-responsibility principle
O – Open-closed principle
L – Liskov substitution principle
I – Interface segregation principle
D – Dependency Inversion Principle

Let’s dive deep into these principles one by one.

2. Single-responsibility Principle

This principle states:

A class should have one and only one reason to change, meaning that a class should have only one responsibility.

In other words, it implies that a class should be responsible for only one job and whenever there is a change in that job, it should be the only reason to change that class.

For example, say we have some planets, and we want to compute the surface area of planets. The surface area depends on the radius. So, let’s assume the following classes:

interface Planet{
}
class Earth implements Planet {
    public $radius;

    public function construct($radius) {
        $this->radius = $radius;
    }
}
class Mercury implements Planet{
    public $length;

    public function construct($radius) {
        $this->radius = $radius;
    }
}

First, we create our classes and have the constructors to set up the required parameters. Next, we are creating a class which calculates the surface area.

class SurfaceAreaCalculator {

    protected $planet;

    public function __construct($planet) {
        $this->planet = $planet;
    }

    public function getSurfaceArea() {
        $radius = $this->planet->radius;
        return 4*(22/7)*$radius*$radius;
    }

    public function output() {
        return '<p>'. 'the surface area of planet is '. $this->getSurfaceArea() . "</p>"
    }
}

To compute the surface area of any planet, we can instantiate the class SurfaceAreaCalculator and pass an object of type planet.

$planet = new Earth(6371);
$calc = new SurfaceAreaCalculator($planet);
$calc->output();

Now, the SurfaceAreaCalculator is responsible for two things – first calculating the surface area and second outputting that. What if tomorrow we want to use JSON or XML output from output method? Then we need to change the class.

So, to fix this, we can create an AreaOutputFormatter class and use this class to print the output in the format we want.

class AreaOutputFormatter{
    private $area;

    public function construct($area) {
        $this->area = $area;
    }

    public function HTML(){
        return '<p>'. 'the surface area of planet is '. $this->area. '<p>';
    }

    public function Blade(){
        return '<p>'. 'the surface area of planet is '. $this->area;
    }

}

The AreaOutputFormatter class would work like this:

$planet = new Earth(6371);
$calc = new SurfaceAreaCalculator($planet);
$surfaceArea = $calc->getSurfaceArea();
$output = new AreaOutputFormatter($surfaceArea);
echo $output->HTML();
echo $output->Blade();
3. Open-closed Principle

The second principle states:

Objects or entities should be open for extension but closed for modification.

It implies that a class should be easily extendable without modifying the class itself. Let’s have a look on AreaOutputFormatter; it supports HTML and Blade output but what if we want to have output in JSON? Now, we need to modify our existing class, which is terrible.

To make AreaOutputFormatter open for extension and closed for modification, we should refactor our code as below:

interface IAreaOutputFormatter{
    public function getOutput();
}

Now, we should create implementing classes of this interface like:

class HTMLAreaOutputFormatter implements IAreaOutputFormatter {
    private $area;

    public function construct($area) {
        $this->area = $area;
    }

    public function getOutput(){
        return '<p>'. 'the surface area of planet is '. $this->area. '<p>';
    }

}

The above class implements output in HTML format. Similarly, we can create one more class which outputs the area in JSON:

class JSONAreaOutputFormatter implements IAreaOutputFormatter {
    private $area;

    public function construct($area) {
        $this->area = $area;
    }

    public function getOutput(){
        return json_encode (["area" => $this->area]);
    }

}

In this way, we can extend our output format class to many output types.

4. Liskov substitution principle

The Liskov substitution principle states:

Every subclass/derived class should be substitutable for their base/parent class.

Assume a new class LiveablePlanet, which extends class Earth:

class LiveablePlanet extends Earth{
    public function color(){
    }
}

Now according to the Liskov substitution principle, we should be able to use LivablePlanet class wherever we are using Earth.

Like in the above example, this should work:

$planet = new LivablePlanet (6371); // here earlier we used Earth class
$calc = new SurfaceAreaCalculator($planet);
$surfaceArea = $calc->getSurfaceArea();
$output = new AreaOutputFormatter($surfaceArea);
echo $output->HTML();
echo $output->Blade();
5. Interface segregation principle

This principle states:

A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.

Using our Planet interface above, assume that we add a method named getHighestMountainRange():

interface Planet{
    public function getHighestMountainRange();
}

However, the problem with this approach is interface Planet forces Earth and Mercury class to implement the method getHighestMountainRange().

A better and cleaner approach would be to create a new interface like MountainyPlanet, which extend the Planet interface and then Earth should implement MountainyPlanet because Earth has mountains and Mercury should implement Planet (assuming Mercury have no mountains).

Our code outlines would look like:

interface Planet{
}
interface MountainyPlanet extend Planet{
    public function getHighestMountainRange();
}
class Mercury implements Planet{
}
class Earth implements MountainyPlanet{
    public function getHighestMountainRange(){
        return "Himalayas";
    }
}
6. Dependency Inversion principle

The last, Dependency Inversion principle states :

Different entities must depend on abstractions, not on concretions.
It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.

In simple words: This principle allows for decoupling, an example that seems like the best way to explain this principle:

class PasswordReminder {
    private $dbConnection;

    public function __construct(MySQLConnection $dbConnection) {
        $this->dbConnection = $dbConnection;
    }

}

MySQLConnection is the low-level module and PasswordReminder is high level and PasswordReminder is being forced to depend on MySQLConnection.

If in future, we want to switch to Oracle in place of MySQL, we have to edit PasswordReminder class which violets Open-close principle.

The PasswordReminder class should not be dependent on the database system that we are using in our application. As high level and low-level modules should connect through an interface, let’s create an interface:

interface DBConnectionInterface {
    public function connect();
}

This interface has a connect method and classes implementing this interface should provide an implementation for connect() method.
Now, we can modify MySQLConnection class to implement DBConnectionInterface, and in the constructor of PasswordReminder we accept an object of type DBConnectionInterface, our code looks like:

class MySQLConnection implements DBConnectionInterface {
    public function connect() {
        return "Database connection";
    }
}
class PasswordReminder {
    private $dbConnection;

    public function __construct(DBConnectionInterface $dbConnection) {
        $this->dbConnection = $dbConnection;
    }

}

Now, if in future if we want to use Oracle, we can quickly create class MySQLConnection which implements DBConnectionInterface. The flexibility of database independence become possible by creating a common interface DBConnectionInterface which connects the high-level modules and low-level modules.

7. Conclusion

Bingo! We learned about SOLID design patterns in this article, and with continuous usage and application in daily life, it becomes the part of our code which results in beautiful code which can be easily be modified, extended, tested, and refactored without any problems.

The post Understanding the SOLID principles of software engineering appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction
In software engineering and development, things change very quickly. We need to move forward and keep ourselves and our code up to date. Software development mostly revolves around code re-use because there is no point in writing login-signup again and again. There are ways to share our code with others and to use the code shared by others. In the PHP ecosystem, the composer is the most widely used dependency manager. Assuming that we know how the composer works, we want to explore how we can share our code or libraries that can be used by others in their projects. Let us get started.
2. Write the code
For creating a composer package, we need to follow a directory structure like below:
|-src/
|-composer.json
The src directory contains all the code and composer.json have all the information for discovery of the package.
Let us write a Calculator class which looks like:
<?php

namespace Bootsity\Calculator;

class Calculator
{

    public function add($a, $b)
    {
        return $a + $b;
    }

    public function multiply($a, $b)
    {
        return $a * $b;
    }

}

This is a really simple class having two methods: one for adding two numbers and other for returning product of two numbers.

In our code, let us add a composer.json

{
    "name": "bootsity/calculator",
    "description": "Package for mathematics calculations",
    "type": "package",
    "require": {
        "php": ">=5.4.0"
    },
    "license": "mit",
    "authors": [
        {
            "name": "Pradeep Kumar",
            "email": "pradeep@bootsity.com",
            "homepage": "https://bootsity.com"
        }
    ],
    "minimum-stability": "dev",
    "autoload": {
        "psr-4": {
            "Bootsity\\Calculator\\": "src/"
        }
    }
}

This composer.json specifies information about package name, description, and authors. One important key to note here is autoload. This key directs the composer to use PSR-4 standard for autoloading.

3. Host package on GitHub
Now, we have completed the writing of our code, we need to put it on some public repository from where packagist will read our code and supply it to the developer when they require it in their composer.json. GitHub, Bitbucket and Gitlab are some examples. We will use Github. Create a repo on GitHub and push your code in the same repo.
For our example here is the repository GitHubhub that we can refer – https://github.com/Bootsity/calculator
4. Register with packagist
Now, our code is available publically and anyone can download a copy of it and re-use. But what if we released a new version of our Calculator class having one more method to find the difference between two numbers? The developers who are using my Calculator class by downloading it will not get the updates. To make the updates easy, we need to register our package with packagist so that it is discoverable and people get easy updates.
To register with packagist, go to packagist,

After submission, our package will be crawled and will be available to use through composer.

5. Use package in other projects
Now, our package is available on packagist, it can be used by anyone in their projects. Let us try to use our package in a sample project. Let’s create a blank composer project:
composer init
This command will open up an interactive prompt, which will look like:
Pradeeps-MacBook-Pro:composer-repo-user prady$ composer init

                                            
  Welcome to the Composer config generator  
                                            


This command will guide you through creating your composer.json config.

Package name (<vendor>/<name>) [prady/composer-repo-user]: 
Description []: 
Author [, n to skip]: n
Minimum Stability []: 
Package Type (e.g. library, project, metapackage, composer-plugin) []: 
License []: 

Define your dependencies.

Would you like to define your dependencies (require) interactively [yes]? n
Would you like to define your dev dependencies (require-dev) interactively [yes]? n

{
    "name": "prady/composer-repo-user",
    "require": {}
}

Do you confirm generation [yes]? y

It will create a composer.json. In the same directory, execute:

composer require bootsity/calculator
this will add the dependency in composer.json and update all the dependencies.
Let’s create an index.php having the following code:
<?php
require_once __DIR__ . '/vendor/autoload.php';

use Bootsity\Calculator\Calculator;

$instance = new Calculator();

echo $instance->add(2,6);

When we execute the above code, it prints 8 on output.

6. Summary
In this article, we learned how we can create packages and distribute them for reuse using composer. We just need to put the code on a public git repository and register it with packagist to make it discoverable – that’s all we need to create a composer package. Our package is available on packagist here – https://packagist.org/packages/bootsity/calculator What you are planning to roll out as the a composer package?

The post Create a composer package and list on packagist appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction

In this article, we are starting to learn about Laravel. Laravel is one of the most famous PHP Framework as well as the most-starred PHP framework on GitHub. This article follows the Laravel 5.5 LTS version. Taylor Otwell develops Laravel with beautiful code and developer happiness in mind. It has a minimal learning curve when compared to other PHP frameworks. At this point of time, we assume that we know the basics of PHP if not, you might want to go through our free course – Learn PHP in 10 Days  first. So let’s get started.

2. About composer

The composer is an application-level package manager for the PHP programming language that provides a standard format for managing dependencies of PHP software and required libraries. It uses a JSON file named package.json to control the application level dependencies.
Laravel uses composer as dependency manager. To install Composer, download it from https://getcomposer.org/

3. Installing PHP and git for local environment

We use the XAMPP package for a local development environment. You can download the latest version of XAMPP from the official website https://www.apachefriends.org/

We also need to install the git source control on our system. You can download and install the git from here – https://git-scm.com/

4. Getting Laravel and starting a local server

Once you have your local environment ready, open up a command prompt and execute the following command

composer create-project --prefer-dist laravel/laravel blog "5.5.*"

This command will copy Laravel from github.com to your current folder and will install all the related dependencies.

To start the local development server.

php artisan serve

The command above will start a local PHP development server on http://localhost:8000

5. Hello World! in Laravel

Using an editor, open the file routes/web.php

In this file, you will find this code.

Route::get('/', function () {
    return view('welcome');
});

This welcome view produces the Laravel “welcome” page, which we can see in a browser on http://localhost:8000.

We can change this code to something like

Route::get('/', function() {
    return 'Hello, World!';
});

Now, when we browse http://localhost:8000, we see the string Hello, World!

6. Summary

In this article, we started with the introduction of Laravel, had an overview of the composer and prepared our local environment for development. Then, we created a hello world project in Laravel. In the next articles, we will learn more about Laravel. Stay happy and updated by subscribing to our newsletter.

The post Hello world in Laravel appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction
In this article in this series will learn how we can handle errors and exceptions that occur when our PHP code is executed.
We will learn about different types of errors and exceptions in PHP, how we can use built-in functions related to exception handling and how we can write custom error handler functions.
2. Types of Errors in PHP
Fundamentally, there are two types of errors in any software system:
Internal or Logical Errors: These types of errors are the errors which are in our programs. These are the logical errors in our code and can be avoided by careful programming.
External Errors or Runtime Exceptions: These type of errors occur at run-time. Some examples are the exception in connecting to a database or error in reading a file from the filesystem. As these are runtime errors and are mostly not known at the time of writing programs but we can always catch these exceptions using try-catch programming paradigm.
3. Error Reporting Settings in php.ini
Generally, in php.ini we set the default configuration of Error Reporting.
It can be done like:
error_reporting=E_ALL
We can also override this default value set in php.ini in our code using error_reporting()   function. Like:
// Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
4. Creating Global Custom Error Handlers
We can configure and override the types of errors that we want with PHP. However, we can also set the global error handler. The global error handler is a function which catches all the errors occurred during the execution of PHP program.
We can set any function to be global custom error handler using the function  set_error_handler(). Here is an example:
// error handler function
function errorHandler($errno, $errstr) {
  echo "Error: [$errno] $errstr";
}

// set error handler
set_error_handler("errorHandler");

// trigger an error
echo($foo); // undefined variable!
5. Exceptions Handling
In exception handling, there are specific keywords we need to know :
try: The try block has the code that may or may not throw an exception during execution. The code inside try is executed line by line until an exception is thrown.
throw: The throw keyword is used to create a new exception.  After an exception is thrown, the runtime try to catch the exception in any of catch statement.
catch: The catch block is executed only when an exception is, and the catch block is trying to catch the Exception or more specific exception.
finally: The finally block contains the code that needs to be always executed irrespective of any exception was encountered on not. There are specific tasks or code that should always be executed like the closing of DB connection, such tasks or code should go inside finally block. Example:
try {
    print "this is our try block n";
    throw new Exception();
} catch (Exception $e) {
    print "something went wrong, caught yah! n";
} finally {
    print "this part is always executed n";
}
6.Pre-defined classes for Exception Handling
PHP also has some predefined classes and interfaces that we can use and extend. The necessary hierarchy of pre-defined exception classes looks like :
Throwable
 — Error
   — Arithmetic Error
   — Parse Error
 — Exception
   — Logic Exception
   — Runtime Exception
7. Conclusion
In this article, we had a quick look at different types of errors and how we can handle them in PHP. We also had a look at try-catch-finally constructs, and we can use it to catch exceptions. In our application, we can also define a global custom error handler, and we also learned about few predefined classed in PHP related to Exception hierarchy.

The post Handling PHP Errors and Exceptions appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction

In this article, we are learning about databases and how we can connect to databases using PHP programs.
Databases are used as information storage components in software systems. We can connect to databases using different technologies and programming language.
Let’s first understand the concept of databases thoroughly and then we will connect to it using PHP programming language.

2. RDBMS Concepts

RDBMS stands for Relational Database Management Systems. To interact with RDBMS, we use SQL. SQL stands for Structural Query Language. SQL is used with all modern database systems like MySQL, MS SQL Server, IBM DB2, Oracle, and others.

In RDBMS, we store data in objects and we call them tables. This table is a collection of related data entries, and it consists of numerous columns and rows. These tables are logically related to each other using some connector known as Foreign keys

3. Using SQL for performing actions on DB

To interact with databases, we use SQL and in SQL there are two types of queries – data definition queries and data manipulation queries. We use data definition queries to define the database schema, table structures etc and to insert, update or delete we use data manipulation queries. To keep this article simple and focused, we will just connect to MySQL using PHP and create a new table in the DB.

4. Program to connect to MySQL

To connect to MySQL using PHP, we use PDO. PDO stands for PHP Data Objects. Here is the code:

$servername = "localhost";
$username = "username";
$password = "password";

try {
    $db= new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 
}catch(PDOException $e){
    echo "Connection failed: " . $e->getMessage();
}
5. Creating a table

As we have successfully connected to DB, let’s try creating a table in DB. Below is the complete code to create table –

$servername = "localhost";
$username = "username";
$password = "password";

try {

    $db = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Error Handling

    $sql ="CREATE table USERS(
              ID INT( 11 ) AUTO_INCREMENT PRIMARY KEY,
              Name VARCHAR( 250 ) NOT NULL
           );" ;

    $db->exec($sql);
    print("Created Table.\n");

} catch(PDOException $e) {
    echo $e->getMessage();
}
6. Conclusion

In this article, we are learning about what is an RDBMS, and it is used to store data in software applications. SQL is used to interact with RDBMS DB to access and manipulate the data stored in RDBMS DB. We also connected to MySQL RDBMS using PHP technology using PDO technology. In the upcoming article of this series, let’s learn about errors and exceptions in PHP.

The post Databases and working with MySQL appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction
The majority of our web works on a client-server model which is governed by the HTTP protocol. In this article, we are having an introductory look on HTTP protocol and different capabilities of PHP related to HTTP. Also, we are exploring some of the most useful and essential functions in PHP to create a web application which runs over the web using the HTTP protocol. So, let us start.
2. HTTP Protocol
HTTP stands for HyperText Transfer Protocol. HTTP is the protocol used by the internet or WWW. HTTP defines how messages are formatted and transmitted between two different systems connected on the internet and what actions servers and client software like browsers should take in response to various commands. The client (most of the times a browser) sends a request to server and server reads the request and sends back the expected response to the client.
3. $_REQUEST, $_GET and $_POST
We have learned about the superglobals in earlier articles. $_REQUEST contains all the information about the request that a client sends to the server. $_GET contains only the information about the GET request and similarly $_POST contains information only about POST request. So, we can say that all the information that is present in $_GET and $_POST is also available in $_REQUEST. To understand these variables deeply, let’s assume that there is an HTML form:
<form method="POST" action="handle.php">
    <input name="name" />
    <button type="submit">Submit</button>
</form>

When a user submits it, it sends a POST request to the script handle.php. Now, assume that the code of handle.php is:

<?php
    print_r($_POST);
?>

the handle.php produces the result as below on the output:

array(
    name => bootsity
)
4. Cookies
The HTTP protocol is a stateless protocol. To identify any subsequent requests from the same client, we share cookies with a client and client attaches those cookies in subsequent requests. Cookies are tiny files that are generated by the server and send back in response, and the client sends those cookies in all subsequent requests. In PHP, we can use setcookie function to create a cookie:
setcookie(name, value, expire, path, domain, secure, httponly);
5. Session
When we work with an application, we open it, do some changes, and then we close it. This is much like a Session. The system knows who we are. It also knows when we start the application and when you end. However, on the internet, as HTTP is a stateless protocol, there is a problem: the web server does not know who we are or what we do, because the HTTP address doesn’t maintain state. To solve this difficulty, we make use of sessions. The session is a storage area on the server shared between the different request from a particular client. In PHP, we can start using the session using a function:
session_start();
6. Conclusion
In this article, we learned about how HTTP works in client-server model followed by www. We also learned about the different capabilities of PHP related to the HTTP protocol and how these functionalities can be used in creating a web application in PHP. In the next article in this series, we will learn about databases and how we can use them as data storage systems and access them using PHP programming language.

The post PHP, HTTP, and the web appeared first on Bootsity.

Read Full Article
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 
1. Introduction
In this article in the series, we are learning about different types of loops. Loops are programming constructs that can be used to repeat a particular task, or in other words, we can say loops are used to execute the same block of code again and again by some pre-defined conditions. The primary use of loop is to automate repetitive tasks and save time and efforts.
In PHP, we have the following types of loops:
  • while: loops through a block of code until the condition evaluates to true.
  • do…while: The block of code executes once, and then condition gets computed. If the condition results in a true, the statement is repeated as long as the specific condition is true.
  • for: loops through a block of code until the counter reaches a specified number.
  • foreach: loops through a block of code for each element in an array.
Let us go through them to understand each loop deeply.
2. PHP while loop
The while loop executes the code block until the condition results in true. The syntax of while loop is:
while(condition){
    // Code to be executed
}
The code below demonstrates the use of while loop which starts $i = 1  with  and keeps executing until the condition $i <= 5 results in true.
$i = 1;
while($i <= 5){
    $i++;
    echo "Value of $i is " . $i . "<br>";
}
Output:
Value of $i is 1
Value of $i is 2
Value of $i is 3
Value of $i is 4
Value of $i is 5
3. PHP do-while loop
The do-while loop is a modified version of while loop. The while loop evaluates the condition at the starting of iteration, but the do while evaluates the condition at the end of every iteration, after execting it once.
The do-while loop always executes the loop once and keeps iterating until the condition results in true. The syntax of do-while is:
do{
    // Code to be executed
}while(condition);

The code below demonstrates the use of do-while loop which starts with $i = 1 and keeps executing until the condition $i <= 5  results in true.

$i = 1;
do{
    $i++;
    echo "Value of $i is " . $i . "<br>";
}while($i <= 5);

Output:

Value of $i is 1
Value of $i is 2
Value of $i is 3
Value of $i is 4
Value of $i is 5
4. PHP for loop
The for loop is the most frequently used loop. It repeats a block of code until a certain condition is true. The syntax of for loop is:
for(initialization; condition; increment){
    // Code to be executed
}

Let’s discuss the three parameters of for loop:

  • initialization — used to initialize the counter variables and evaluated once unconditionally before the first execution of the body of the loop.
  • condition — at the beginning of each iteration, the condition gets computed. If the condition results in true, the loop continues, and the statements in the block are executed, else the execution of the loop ends.
  • increment — increment updates the loop counter. It is evaluated at the end of each loop iteration.
Consider:
for($i=1; $i<=5; $i++){
    echo "Value of $i is " . $i . "<br>";
}
The output of the above code would be:
Value of $i is 1
Value of $i is 2
Value of $i is 3
Value of $i is 4
Value of $i is 5
5. PHP foreach loop
The foreach loop is mostly used to iterate over arrays. The syntax is:
foreach($array as $value){
    // Code to be executed
}
The following example demonstrates the use of foreach loop that will print the values of the given array:
$planets = array("Earth", "Mars", "Venus");

// Loop through $plants array
foreach($planet as $planet){
    echo $planet . "<br>";
}
The output would be:
Earth
Mars
Venus
There is one more syntax of the foreach loop, which is an extension of the above syntax.
foreach($array as $key => $value){
    // Code to be executed
}
The $key contains the key of the array. So, the above example becomes –
$planets = array("Earth", "Mars", "Venus");

// Loop through $plants array
foreach($planet as $key => $planet){
    echo $planet . " is at position ". $key ."<br>";
}
The output would be:
Earth is at position 0
Mars is at position 1
Venus is at position 2
6. Conclusion
In this article, we had an in-depth look at different types of looping constructs and how and where we can use them. In the next article of this series, we will learn about different HTTP related capabilities of PHP programming language. Till then, try printing table of 2 using for loop.

The post Looping around in PHP appeared first on Bootsity.

Read Full Article

Read for later

Articles marked as Favorite are saved for later viewing.
close
  • Show original
  • .
  • Share
  • .
  • Favorite
  • .
  • Email
  • .
  • Add Tags 

Separate tags by commas
To access this feature, please upgrade your account.
Start your free month
Free Preview