How To Set Up A Laravel Application on Ubuntu 16.04 VPS

How To Set Up A Laravel Application on Ubuntu 16.04 VPS

Let us presume that you have already set up an Ubuntu 16.04 VPS server with Apache and that you have installed a bare bones Laravel app. In this tutorial we shall install and create a MySQL database and connect the app to it. The final step is to fully configure the application via the .env file and artisan.

;

What we are going to cover

  • Creation of MySQL database for the app,
  • Connecting Laravel app to the database
  • Creating the .env file for Laravel environment variables
  • Using artisan to generate the app key
  • Additional configuration for timezone and locale

PRE-REQUISITES

We shall install and deploy Laravel 5 on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access
  • You have already installed Laravel on your VPS and it is running properly

Step 1: Install MySQL Database

First use SSH to access the VPS server. To install MySQL database, run the following command from Ubuntu command line:

sudo apt install mysql-server -y

This will install the MariaDB database server (an enhanced fork of MySQL). You will be asked to enter password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Depending on the level of security you wish to achieve, you will have the option to adjust the minimum password complexity. Press 2 to select the highest level. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then ener another password to secure the installation. Store that second password as you will need it in Step 9 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 2 Creating a Database

Launch MySQL shell:

sudo mysql -u root -p

When asked, enter the second password from Step 1 of this tutorial.

Once in MySQL prompt, copy and paste the following code as a whole, then press Enter on the keyboard:

CREATE DATABASE blogdb;
USE blogdb;
CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);
    INSERT INTO posts (title, body, created)
    VALUES ('Sample title', 'This is the article body.', NOW());
    GRANT ALL PRIVILEGES ON blogdb.* TO 'post_user'@'localhost' IDENTIFIED BY 'password9I%';
    FLUSH PRIVILEGES;
    EXIT;

That will execute everything at once. Here is what it will look like in the terninal:

The first line will create a database blogdb and from the second line on, will start using it. Then we create table called posts with two visible fields, title and body. Column idis necessary but will be used by only internally.

Then we populate table posts by inserting one sample value.

Command GRANT ALL PRIVILEGES creates a new user called postuser_ and grants it all privileges on database blogdb. Currently there is only one table in this database, posts.

Command IDENTIFIED BY defines the password. It must contain lower and uppercase letters, as well as digits and special characters. Be sure to always change and invent new passwords for database users.

Command FLUSH PRIVILEGES; reloads the database with the changes made. The last command is EXIT, to leave the MySQL prompt and go back to the command line in Ubuntu itself.

Step 3 The .env File

Navigate to the app folder and execute the ls -a command:

cd /var/www/html/blog/
ls -a

The following image shows the contents of the blog folder. Note that there are files starting with dot, such as .end, which is not visible with the usual ls command. Using ls -a will, however, show the dot files as well.

The fact that the dot files are “invisible” will not stop us from reading these files into an editor and changing them to finish the installation. The .env file contains debugging options, parameters to connect to the database and so on. So let us open it for editing:

sudo nano /var/www/html/blog/.env

Step 4 Connect the App To the Database

Put the following into the .env file to enable access to the database you have created in previous steps:

DB_DATABASE=blogdb
DB_USERNAME=post_user
DB_PASSWORD=assword9I%

Save and close the file.

The .env File May Be Missing

In some installations and scenarios, the .env file may be missing. You can download it from here, then create the missing .env file by opening it in an editor such as nano and copying the contents there.

With every installation there will be a file called .env.example so the other way to recreate the .env file is to use .env.example as a template, and create the .env files by copying:

cd /var/www/html/blog
cp .env.example .env

Step 5 Creating the Key for the Application

With each change of the the .env file, there will be several artisan commands to execute. As a minimum, you will need to run php artisan key:generate. If you don’t, you will get a warning screen like this:

So execute the following commands in a row:

php artisan key:generate
php artisan config:cache
composer dump-autoload

If you are changing the database, run the migration commands as well:

php artisan migrate

Step 6 Additional Configuration

In file config/app.php you can set up timezone and locale parameters. They look like this:

The command to access the file is:

sudo nano /var/www/html/blog/config/app.php

What To Do Next

Now you have a rudimentary Laravel app on your server, running smoothly.Once you develop your app and test it, you may aim for a production level of system. See article “How To Set Up Laravel For Production: Ubuntu 16.04” to improve your site before going to production phase.

Dusko Savic is a technical writer and Flutter programmer.
duskosavic.com

The post How To Set Up A Laravel Application on Ubuntu 16.04 VPS appeared first on Low End Box.

How To Install CakePHP On Ubuntu 16.04 VPS

How To Install CakePHP On a Ubuntu 16.04 VPS

With this tutorial, you will be able to create a CakePHP environment from scratch, define a database, and automatically generate a working web app.

You will start with an empty black screen and within an hour have a small web site on a VPS.

What are we going to cover

  • installation of LAMP stack (Linux, Apache, MySQL, PHP),
  • creation of user which will have access to the app,
  • installation of CakePHP itself,
  • creation of the database for the app,
  • creation of the app itself, through the process known as baking.

PRE-REQUISITES

We shall install and deploy CakePHP on Ubuntu 16.04:

  • Starting with a clean VPS with
  • At least 512Mb of RAM and
  • 15Gb of free disk space.
  • You will need root user access

Step 1: Creating a Non Root User

Once you are logged in as root, you can create a new user account that you’ll use from now on. Root is useful for performing system administration tasks, but using it for ordinary tasks is error prone and risky.

We’ll call the new user cakeuser. To create it, run:

adduser cakeuser

Then, add it to the sudo group, so that you can run commands as sudo:

usermod -aG sudo cakeuser

Step 2: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Next, enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://SERVER_IP/. If that does not work, try adding :80 in the end, like this:

http://SERVER_IP:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 3: Install MySQL Database

To install MySQL database, run the following command:

sudo apt install mysql-server -y

This will install the MariaDB database server (an enhanced fork of MySQL). You will be asked to enter a password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Depending on the level of security you wish to achieve, you’ll have the option to adjust the minimum password complexity. Press 2 to select the highest level. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then ener another password to secure the installation. Store that second password as you will need it in Step 9 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 4: Install PHP

Finally, install PHP by running:

sudo apt install php -y

This will install PHP 7.0, which will here serve just fine.

You’ll then need to install common PHP extensions that CakePHP requires:

sudo apt install php-{bcmath,bz2,intl,gd,mbstring,mcrypt,mysql,zip,intl,xml} libapache2-mod-php unzip -y

Linux uses tar to decompress files while some of the files for PHP come in zip format, so the above line will install zip and unzip programs as well.

Step 5: Install Composer

Composer is a flexible PHP package manager, which CakePHP uses to manage all of its dependencies.

Install curl to download the install script for Composer:

sudo apt install curl -y

Then, download the installer:

cd ~
sudo curl -s https://getcomposer.org/installer | php

To make it available globally, move it to /usr/bin:

sudo mv composer.phar /usr/local/bin/composer

You are installing Composer as root user and it will show a warning about it. Once we have the app installed, we shall give access to its folder to user cakeuser.

Step 6: Create an Example CakePHP App

Apache stores the data it serves under /var/www/html. To create a new app, run:

composer create-project --prefer-dist cakephp/app /var/www/html/cakeapp

Here “cakeapp” will be the name of the app. You may install several CakePHP apps in this way on the same server, just change “cakeapp” for the new name.

When Composer asks if you want it to set up folder permissions, answer with y.

If for some reason you later get a warning that these folders are not accessible, you may run these two commands:

sudo chmod -R a+rw /var/www/html/cakeapp/logs
sudo chmod -R a+rw /var/www/html/cakeapp/tmp

In Step 11 of this tutorial we shall use bake command in CakePHP to create a ready made app. For now, let us create a permission to access it:

cd /var/www/html/cakeapp
chmod +x bin/cake

We can now give user cakeuser access to the app folder:

sudo chown -R cakeuser /var/www/html/cakeapp

Have your passwords always easily accessible as Ubuntu will ask you for them whenever you change or access something in the system.

Step 8: Configuring Apache

Edit Apache configuration file so that it will serve CakePHP app by default. It is called 000-default.conf and is stored in directory /etc/apache/sites-enabled. Open it for editing:

sudo nano /etc/apache2/sites-enabled/000-default.conf

Find line which starts with DocumentRoot and replace it with this:

DocumentRoot /var/www/html/cakeapp/webroot

Save and close the file.

CakePHP requires Apache module_rewrite to also be enabled; do so by running:

sudo a2enmod rewrite

Finally, instruct Apache to use .htaccess files, with which CakePHP configures Apache on the fly. Open Apache global configuration file for editing:

sudo nano /etc/apache2/apache2.conf

Under the block, you’ll find the following line:

AllowOverride None

Change it to

AllowOverride All

When you are done, save the file.

Again restart Apache so that it takes new configuration into account:

sudo systemctl restart apache2

You can now navigate to your domain in your browser. You should see the following:

CakePHP is now installed properly, save for the fact that there is no database to connect to. We shall first create the database and then connect it to CakePHP in the next step.

Step 9 – Creating a Database

Launch MySQL shell:

sudo mysql -u root -p

When asked, enter the second password from Step 3 of this tutorial.

Once in MySQL prompt, copy and paste the following code as a whole, then press Enter on the keyboard:

CREATE DATABASE blogdb;
USE blogdb;
CREATE TABLE posts (
    id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(50),
    body TEXT,
    created DATETIME DEFAULT NULL,
    modified DATETIME DEFAULT NULL
);
    INSERT INTO posts (title, body, created)
    VALUES ('Sample title', 'This is the article body.', NOW());
    GRANT ALL PRIVILEGES ON blogdb.* TO 'post_user'@'localhost' IDENTIFIED BY 'password9I%';
    FLUSH PRIVILEGES;
    EXIT;

That will execute everything at once. Here is what it will look like in the terninal:

The first line will create a database blogdb and from the second line on, will start using it. Then we create table called posts with two visible fields, title and body. Columns id, created, and modified are necessary but will be used by CakePHP only internally.

Then we populate table posts by inserting one sample value.

The next line, starting with GRANT ALL PRIVILEGES is crucial. It creates a new user called _postuser and grants it all privileges on database blogdb. Currently there is only one table in this database, posts.

The third part, starting with IDENTIFIED BY, defines the password. It must contain lower and uppercase letters, as well as digits and special characters. Be sure to always change and invent new passwords for database users.

Command FLUSH PRIVILEGES; reloads the database with the changes made. The last command is EXIT, to leave the MySQL prompt and go back to the command line in Ubuntu itself.

Step 10: Connecting App to the Database

Navigate to the app folder:

cd /var/www/html/cakeapp/

CakePHP stores database credentials in a file named app.php, stored under the config folder. Open it for editing:

sudo nano /var/www/html/cakeapp/config/app.php

Find the Datasources block:

    'Datasources' => [
        'default' => [
            'className' => 'CakeDatabaseConnection',
            'driver' => 'CakeDatabaseDriverMysql',
            'persistent' => false,
            'host' => 'localhost',
            ...
            //'port' => 'non_standard_port_number',
            'username' => 'post_user',
            'password' => 'password9I%',
            'database' => 'blogdb',

In your terminal it may look like this:

For ‘username’ put your database user’s user name (post_user), for ‘password’ put your database user’s password (password9I%), and for database name it is obvious what to put (blogdb).

Save and close the file.

Refresh app in your browser and observe the success message under the Database section.

Step 11: Creating Your First CakePHP App

Under normal circumstances, you would have to now learn programming in PHP, then learn CakePHP, and within a couple of days, weeks or months, you would have your first “Hello World” app on the server.

There is a much faster way – using the bake command. Execute this:

./bin/cake bake all posts

It will create CakePHP code in various folders and produce an app that can read, save, update and delete entries in table posts of database blogdb.

Part of the bake output is shown here:

Visit the address in the browser:

http://SERVER_IP/posts

That’s it, we now have a CakePHP app installed, connected to the database and running for real.

What To Do Next

Now you have a rudimentary CakePHP app on your server. The rest depends on your original intentions. For example, if you are a developer selling sites to the clients, at this point you can upload your CakePHP app and be sure that it will run properly.

Once you finish your app, see article “How To Set Up CakePHP For Production: Ubuntu 16.04” how to improve your site before going to production phase.

Dusko Savic is a technical writer and Flutter programmer.
duskosavic.com

The post How To Install CakePHP On Ubuntu 16.04 VPS appeared first on Low End Box.

Install and Secure phpMyAdmin on Ubuntu 16.04 VPS

With this tutorial, you will be able to install and secure phpMyAdmin, the most popular program for accessing MySQL and MariaDB databases on Internet servers.

What We Are Going To Cover

  • Installing the LAMP stack (Linux, Apache, MySQL, PHP)
  • Adding PHP extensions to run phpMyAdmin
  • How to install phpMyAdmin itself

To secure phpMyAdmin, we are going to:

  • Install Let’s Encrypt
  • Edit php.ini to eliminate showing of PHP errors
  • Restrict access to folders templates and libraries
  • Prevent robots from accessing phpMyAdmin
  • Hide phpMyAdmin behind an authentication proxy
  • Change the URL of phpMyAdmin

Prerequisites

We will install and deploy phpMyAdmin on :

  • a clean installation of Ubuntu 16.04,
  • with at least 512Mb of RAM available on the server and
  • at least 15Gb free disk space.
  • You will need root user access.

To install Let’s Encrypt certificates

  • You must have DNS records for your your domain already set up to point to your VPS.

Step 1: Install Apache

First, update your package manager’s cache:

sudo apt update -y

Install the Apache web server:

sudo apt install apache2 -y

Enable its service to make it run on every system boot:

sudo systemctl enable apache2

Finally, start it:

sudo systemctl start apache2

To verify that Apache was installed successfully, access it from your local browser by navigating to http://YOUR_DOMAIN/. If that does not work, try adding :80 in the end, like this:

http://YOUR_DOMAIN:80

You should see a welcome page for Apache, which means that you now have Apache running.

Step 2: Install PHP 7.3

At the time of this writing, phpMyAdmin requires a version of PHP 7.1.0 or newer to be installed. We shall install PHP 7.3. First, install the prerequisite packages:

sudo apt install software-properties-common python-software-properties

Then, add the ondrej PPA:

sudo add-apt-repository -y ppa:ondrej/php

and update your sources by running:

sudo apt update

Install PHP 7.3 using the following command:

sudo apt install php7.3 php7.3-cli php7.3-common

Step 3: Install Required PHP Extensions

The PHP extensions that phpMyAdmin requires are:

  • session support, the Standard PHP Library (SPL) extension, hash, ctype, and JSON support
  • mbstring, zip, gd. openssl, libxml, curl

Install them:

sudo apt install php7.3-curl php7.3-gd php7.3-json  php7.3-mbstring php7.3-intl php7.3-mysql php7.3-xml php7.3-zip

Restart Apache to activate:

sudo systemctl restart apache2

Step 4: Install MariaDB

Install MariaDB database with the following command:

sudo apt install mysql-server -y

This will install MariaDB database server (an enhanced fork of MySQL). You will be asked to enter password for the MySQL root user. (Use Tab key from the keyboard to switch to the OK button and press Enter on the keyboard.)

Then, secure MySQL installation by running:

sudo /usr/bin/mysql_secure_installation

Press 2 to select the highest level of password complexity. Answer y to every prompt you get afterwards.

So you enter one password first, to enable access to MySQL, then enter another password to secure the installation. Store that second password as you will need it in Step 5 of this article.

To make it run on every system boot, enable it via systemctl:

sudo systemctl enable mysql

Step 5: Install phpMyAdmin From Ubuntu Repository

It is possible to install phpMyAdmin via Composer and Git, but the easiest way is to pull it from the Ubuntu repository:

sudo apt install phpmyadmin php-mbstring php-gettext

You will see this window:

Press space on the keyboard, otherwise the Apache option will NOT be checked. Then, press Tab and Enter to finish data entry in this window.

Press Enter in the next window to let the installer configure a suitable database for phpMyAdmin for you.

In the next screen, enter a password with which phpMyAdmin will connected to the database. That will be the second password from Step 4:

The installation process created files phpmyadmin.conf in directory /etc/apache2/conf-enabled/. Apache will automatically read in all files in that directory.

Execute the following command to see the new file:

ls /etc/apache2/conf-enabled/

Finally, restart Apache so that all these changes take effect:

sudo systemctl restart apache2

Step 6: Securing You Site To Serve Only HTTPS

If you have a domain name and DNS records properly set up to point to your VPS, you can use certbot to generate Let’s Encrypt certificates. This means that you will always access phpMyAdmin (and the rest of your YOUR_DOMAIN) via HTTPS.

We will folow the original documentation to install Let’s Encrypt. Choose Apache for software and Ubuntu 16.04 (xenial) for System – it should look like this:

The site will then generate the following commands for you to enter into the command prompt of your VPS:

sudo apt-get update
sudo apt-get install software-properties-common
sudo add-apt-repository universe
sudo add-apt-repository ppa:certbot/certbot
sudo apt-get update
sudo apt-get install certbot python-certbot-apache 
sudo certbot --apache

You will be asked for the DNS name of your site and whether you want to route all traffic from HTTP to HTPPS. Choose this option as that is the sole reason of installing Let’s Encrypt in the first place.

Now that the access to site is secure behind HTTPS, we can access phpMyAdmin for the first time, without fear that someone could sniff our database user name and password.

Go to this address in your browser:

http://YOUR_DOMAIN/phpmyadmin

Note that this address started with HTTP, but it will end up as HTTPS.

You should see the familiar interface of phpMyAdmin:

Step 7: Securing the Instance of phpMyAdmin

There are several ways to secure the instance of phpMyAdmin. We will show only those that do not require access to phpMyAdmin source code.

Edit php.ini To Eliminate Showing of PHP Errors

Open the config file for PHP and eliminate showing of the errors for all PHP apps:

sudo nano /etc/php/7.3/apache2/php.ini

With Ctrl-W search for “Error handling and logging”. You’ll see something like this:

You will want to change the so-called production values in that document.

We want to turn off any errors tht PHP might return. Find row that starts with errorreporting_ and set it to off or to this:

error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

(Optional) Restrict Access to Folders templates and libraries

Folders templates and libraries in your phpMyAdmin installation must not be accessed by non-authorized visitors. This kind of protection should be installed right from the start, but if that is not the case, here is how we can allow only, say, the root user to access these folders:

sudo chown -R root:root /usr/share/phpmyadmin/templates
sudo chmod 0750 /usr/share/phpmyadmin/templates
sudo chown -R root:root /usr/share/phpmyadmin/libraries
sudo chmod 0750 /usr/share/phpmyadmin/libraries

Prevent Robots From Accessing phpMyAdmin

To prevent robots from accessing your phpMyAdmin installation, create a .htaccess file:

sudo nano /usr/share/phpmyadmin/.htaccess

then enter the following text into it:

RewriteEngine on

RewriteCond %{REQUEST_METHOD} !^(GET|POST)$ [NC,OR]

RewriteCond %{HTTP_USER_AGENT} ^(java|curl|wget).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(libwww-perl|curl|wget|python|nikto|wkito|pikto|scan|acunetix).* [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^.*(winhttp|HTTrack|clshttp|archiver|loader|email|harvest|extract|grab|miner).* [NC,OR]

intext:"Cookies must be enabled"
RewriteCond %{HTTP_USER_AGENT} ^.*(AdsBot-Google|ia_archiver|Scooter|Ask.Jeeves|Baiduspider|Exabot|FAST.Enterprise.Crawler|FAST-WebCrawler|www.neomo.de|Gigabot|Mediapartners-Google|Google.Desktop|Feedfetcher-Google|Googlebot|heise-IT-Markt-Crawler|heritrix|ibm.comcs/crawler|ICCrawler|ichiro|MJ12bot|MetagerBot|msnbot-NewsBlogs|msnbot|msnbot-media|NG-Search|lucene.apache.org|NutchCVS|OmniExplorer_Bot|online.link.validator|psbot0|Seekbot|Sensis.Web.Crawler|SEO.search.Crawler|Seoma.[SEO.Crawler]|SEOsearch|Snappy|www.urltrends.com|www.tkl.iis.u-tokyo.ac.jp/~crawler|SynooBot|crawleradmin.t-info@telekom.de|TurnitinBot|voyager|W3.SiteSearch.Crawler|W3C-checklink|W3C_Validator|www.WISEnutbot.com|yacybot|Yahoo-MMCrawler|Yahoo!.DE.Slurp|Yahoo!.Slurp|YahooSeeker).* [NC]
RewriteRule .* - [F]

This may be just a beginning in your battle against the robots, but the code above is a good start.

Hiding phpMyAdmin Behind an Authentication Proxy

You can force your users to enter login details before accessing phpMyAdmin. To that end, configure your web server to request HTTP authentication. Open the phpmyadmin.conf file for editing:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf

Find the following line in nano editor: “Directory /usr/share/phpmyadmin”. Add the line “AllowOverride All”, then save and close the file.

This is what it will look like in the editor:

Restart Apache for these changes to take effect:

sudo systemctl restart apache2

Now Apache can read .htaccess file for phpmyadmin folder, but we haven’t created that file as yet. Create it by running:

sudo nano /usr/share/phpmyadmin/.htaccess

Enter the following text:

AuthType Basic
AuthName "Restricted Files"
AuthUserFile /etc/phpmyadmin/.htpasswd
Require valid-user

Save and close the file.

Here is what the commands in this file do:

  • AuthType defines what kind of authentification will be used. “Basic” means it will ask for a password.
  • AuthName is the name of the rule applied for authentication. In our case, that is a string that will appear in the dialogue when asking user for login details.
  • AuthUserFile – where will the password file reside? We are going to create this file outside of the usual paths for files.
  • Require – Who will have access to the main site? In this case, only valid users will have it, while none of the others will be let in.

Now, create a password file with the following command:

sudo htpasswd -c /etc/phpmyadmin/.htpasswd username

Executing it will define a user called username in the password file, and will ask for a password. Store that password in a secure place as you will need it as soon as you visit the address

http://YOUR_DOMAIN/phpmyadmin

You will see a form prompting you to enter a username and password:

Once you enter it successfully, you will be redirected to another form asking for login details.

Into that second form, enter login credentials for the database. You can log in as root using the password you set up previously, in Step 4.

Changing the URL of phpMyAdmin

Instead of using a very obvious name of /phpmyadmin, you can use something else. Access the configuration file like this:

sudo nano /etc/apache2/conf-available/phpmyadmin.conf

Put phpmyadmin234 instead of phpmyadmin. Here is how the relevant part in the editor may look like:

Use this address in your browser to access phpmyadmin:

http://YOUR_DOMAIN/phpmyadmin234

Restart Apache to activate:

sudo systemctl restart apache2

This is a “security through obscurity” approach at work. Most bots won’t try other paths except the default one anyways.

Dusko Savic is a technical writer and Flutter programmer.

duskosavic.com

The post Install and Secure phpMyAdmin on Ubuntu 16.04 VPS appeared first on Low End Box.