Select Page
C Programming Tutorial Part 2 – Preprocessors

C Programming Tutorial Part 2 – Preprocessors

In the first part of our ongoing C programming tutorial series, we briefly touched on the preprocessing stage. In this tutorial, we will discuss it in a little more detail so that you have a basic idea about it before learning other C programming aspects.

Preprocessing is usually the first stage of program compilation, where-in anything beginning with a ‘#’ gets processed. Let’s take a basic example code.

#include 

int main (void)
{
    printf("n Hello World n");
    return 0;
}

Yes, this is the same piece of code we used in the first part of this article series. Here, it’s the first line that begins with a hash ‘#’. In layman’s terms, the line ‘#include ‘ makes sure the content of header file ‘stdio.h’ are included in this program during compilation.

So what happens in the preprocessing stage is, this line gets replaced with the actual content of the header file. Here’s how the code looks after the preprocessing stage:

C Code File

So you can see, everything above the few lines of code we wrote (look at the bottom of the screenshot) is the contents of stdio.h. Now, I won’t go in details of how I managed to see the code after preprocessing, but this was to give you a clear idea on what happens during preprocessing.

Moving on, lines that include a header file aren’t the only ones that begin with a hash (#). There’s also something called Macros that also begin with #. So it’s important to discuss them here (at least their basics).

A Macro is nothing but a name (usually in capital letters) that refers to a piece of code. Macros are defined using the ‘#define’ directive. Here’s an example:

#include 
#define PRINT_HELLO_WORLD printf("n Hello World n");
int main (void)
{
    PRINT_HELLO_WORLD
PRINT_HELLO_WORLD
    return 0;
}

So we defined a macro PRINT_HELLO_WORLD with value printf(“n Hello World n”); . Now, wherever we’ll use this macro name in the code, it will get replaced with its value during the preprocessing stage. Here’s the code after pre-processing:

C Program Macro

So you see that both occurrences of the macro were replaced by its value at the pre-processing stage. Of course, there are several other details related to macros that you should know about in order to successfully use them. We will discuss those details in a Macro dedicated part of this tutorial series.

Moving on, the third type of lines beginning with # are #ifdef and #endif. These are used for conditional compilation. To give you a quick idea, there are times when you’d not want a part of code to get compiled based on a certain condition, it’s in cases like these, these directives are used.

Here’s an example:

#include 
#define PRINT_HELLO_WORLD printf("n Hello World n");

int main (void)
{
#ifdef CONDITION
    PRINT_HELLO_WORLD
#endif
    PRINT_HELLO_WORLD
    return 0;
}

In the code above, since ‘CONDITION’ isn’t defined anywhere, so the first occurrence of ‘PRINT_HELLO_WORLD’ will be omitted from code at the preprocessing stage only. Here’s the proof:

Code condition

So you can see only one printf statement after the preprocessing stage.

Conclusion

In this tutorial, we discussed preprocessing to give C programming beginners a basic idea of what happens during this stage. Now, move on to part 3 to learn further about C programming basics.

How to Install InvoicePlane with Nginx on CentOS 7

How to Install InvoicePlane with Nginx on CentOS 7

InvoicePlane is a free and open source invoicing application. Its source code can be found on this Github. This tutorial will show you how to install InvoicePlane on a fresh CentOS 7 system.

Requirements

  • WebServer (Apache, NGINX). This tutorial will use Nginx.
  • MySQL version 5.5 or greater or the equivalent version of MariaDB.
  • PHP version 7.0 or greater with the following PHP extensions installed and activated:
  • php-gd
  • php-hash
  • php-json
  • php-mbstring
  • php-mcrypt
  • php-mysqli
  • php-openssl
  • php-recode
  • php-xmlrpc
  • php-zlib
  • A server running CentOS 7.
  • A non-root user with sudo privileges.

Initial steps

Check your CentOS system version:

cat /etc/centos-release
# CentOS Linux release 7.6.1810 (Core)

Set up the timezone:

timedatectl list-timezones
sudo timedatectl set-timezone 'Region/City'

Update your operating system’s packages:

sudo yum update -y

Install required packages:

sudo yum install -y vim wget curl git bash-completion unzip

Step 1 – Install PHP and required PHP extensions

InovicePlane web application requires PHP version 7.0.0 or greater. Default CentOS repositories contain older version of PHP, and thus we will need to set up a third-party repository to install a newer PHP version. We will use Webtatic repository.

Setup the Webtatic YUM repo:

sudo rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

Install PHP, as well as the necessary PHP extensions:

sudo yum install -y php72w php72w-cli php72w-fpm php72w-common php72w-gd php72w-json php72w-mbstring php72w-mcrypt php72w-mysql php72w-xmlrpc php72w-recode

Check the PHP version:

php --version

# PHP 7.2.12 (cli) (built: Nov 11 2018 14:54:16) ( NTS )
# Copyright (c) 1997-2018 The PHP Group
# Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

Start and enable PHP-FPM service:

sudo systemctl start php-fpm.service
sudo systemctl enable php-fpm.service

Step 2 – Install MariaDB

Install MariaDB database server:

sudo yum install -y mariadb-server

Check the MariaDB version:

mysql --version
# mysql Ver 15.1 Distrib 5.5.60-MariaDB, for Linux (x86_64) using readline 5.1

Start and enable MariaDB service:

sudo systemctl start mariadb.service
sudo systemctl enable mariadb.service

Run mysql_secure installation script to improve MariaDB security and set the password for MariaDB root user:

sudo mysql_secure_installation

Answer all the questions as shown below:

Enter current password for root (enter for none):
Set root password? [Y/n]: Y
Remove anonymous users? [Y/n]: Y
Disallow root login remotely? [Y/n]: Y
Remove test database and access to it? [Y/n]: Y
Reload privilege tables now? [Y/n]: Y

Log into MariaDB shell as the user root:

mysql -u root -p
# Enter password

Create a MariaDB database and user that you will use for your installation of InvoicePlane, and remember the credentials:

CREATE DATABASE dbname;
GRANT ALL ON dbname.* TO 'username' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

Exit from MariaDB shell:

quit

Step 3 – Install NGINX

Install Nginx web server:

sudo yum install -y nginx

Check the NGINX version:

nginx -v
# nginx version: nginx/1.12.2

Start and enable Nginx service:

sudo systemctl start nginx.service
sudo systemctl enable nginx.service

Configure NGINX for InvoicePlane. Run sudo vim /etc/nginx/conf.d/invoiceplane.conf and populate the file with the following configuration:

server {
    listen 80;
    listen [::]:80;

    server_name example.com;

    root /var/www/invoiceplane;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ .php$ {
        fastcgi_index index.php;
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass 127.0.0.1:9000;
    }
}

Test the NGINX configuration:

sudo nginx -t

Reload NGINX:

sudo systemctl reload nginx.service

Step 4 – Install InvoicePlane

Download the latest stable version of InvoicePlane and extract the archive:

sudo mkdir -p /var/www
cd /var/www
sudo curl -O -J -L https://invoiceplane.com/download/v1.5.9
sudo unzip v1.5.9.zip
sudo rm v1.5.9.zip
sudo mv ip invoiceplane

Navigate to /var/www/invoiceplane folder:

cd /var/www/invoiceplane

Make a copy of the ipconfig.php.example file and rename the copy to ipconfig.php:

sudo cp ipconfig.php.example ipconfig.php

Open the ipconfig.php file and add your URL in it:

sudo vim ipconfig.php
# Something like this
IP_URL=http://example.com

Change ownership of the /var/www/invoiceplane directory to nginx:

sudo chown -R nginx:nginx /var/www/invoiceplane

Run sudo vim /etc/php-fpm.d/www.conf and set the user and group to nginx. Initially, they will be set to apache:

sudo vim /etc/php-fpm.d/www.conf
# user = nginx
# group = nginx

Run sudo vim /etc/php.ini and set date.timezone:

date.timezone = Region/City

Restart the PHP-FPM service:

sudo systemctl restart php-fpm.service

Run the InvoicePlane installer from your web browser and follow the instructions:

http://example.com/index.php/setup

Once the installation has finished, you may log into InvoicePlane using the email address and password you have chosen during the installation.

If you want to secure your installation, you may disable the setup. To do so, replace the line DISABLE_SETUP=false with DISABLE_SETUP=true in your ipconfig.php file.

Step 5 – Complete the InvoicePlane setup

InvoicePlane is now installed and configured, it’s time to access their web installation wizard.

Open your web browser and type the URL http://example.com. You will be redirected to the following page:

InvoicePlane web installer

Now, click on the Setup button. You should see the following page:

Choose language

Next, choose the language and click on the Continue button. You should see the following page:

Prerequisite check successful

Next, click on the Continue button. You should see the following page:

Database setup

Here, provide your database details and click on the Try Again button. You should see the following page:

Database has been set up.

Now, click on the Continue button. You should see the following page:

Create user

Now, click on the Continue button. You should see the following page:

Installation complete

Now, provide all the required details, then click on the Continue button. Once the installation is completed, you should see the following page:

Log into InvoicePlane

Now, click on the Login button to access InvoicePlane administration.

How to Install PageKit CMS on Ubuntu 18.04 LTS

How to Install PageKit CMS on Ubuntu 18.04 LTS

PageKit is a free, open source and lightweight CMS that can be used to create beautiful websites. Pagekit comes with a clean and intuitive interface that allows you to focus on what matters most, managing your content. It provides a configurable dashboard that shows all the statistics related to your site at one place. You can easily manage the pages, menus, and widgets using Pagekits’ drag and drop control panel. Pagekit does not require any special hardware requirements. It can be installed on servers with a small amount of RAM.

In this tutorial, we will learn how to install PageKit CMS with Apache web server on Ubuntu 18.04 LTS.

Requirements

  • A server running Ubuntu 18.04.
  • A non-root user with sudo privileges.

Getting Started

Before starting, you will need to update your system with the latest version. You can do this by running the following command:

sudo apt-get update -y
sudo apt-get upgrade -y

Once your system is updated, restart the system to apply the changes.

Install Apache, MariaDB and PHP

PageKit runs on the web server, written in PHP language and use MariaDB to store their data. So, you will need to install Apache web server, MariaDB server, PHP and other PHP libraries to your server. You can install all of them by just running the following command:

sudo apt-get install apache2 mariadb-server php7.2 libapache2-mod-php7.2 php7.2-common php7.2-sqlite php7.2-curl php7.2-intl php7.2-mbstring php7.2-xmlrpc php7.2-mysql php7.2-gd php7.2-xml php7.2-cli php7.2-zip wget unzip -y

After installing all the required packages, you will need to edit php.ini file and make some changes:

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

Make the following changes:

memory_limit = 300M
allow_url_fopen = On
upload_max_filesize = 200M
max_execution_time = 400
date.timezone = Asia/Kolkata

Save and close the file. Then, restart Apache and MariaDB service and enable them to start on boot time by running the following command:

sudo systemctl restart apache2
sudo systemctl restart mariadb
sudo systemctl enable apache2
sudo systemctl enable mariadb

Configure MariaDB for PageKit

By default, MariaDB is not hardened. So you will need to secure it first. You can secure it by running the following command:

sudo mysql_secure_installation

This command will set a root password, remove the anonymous user, disallow remote root login, and remove the test database as shown below:

    Enter current password for root (enter for none):
    Set root password? [Y/n]: N
    Remove anonymous users? [Y/n]: Y
    Disallow root login remotely? [Y/n]: Y
    Remove test database and access to it? [Y/n]:  Y
    Reload privilege tables now? [Y/n]:  Y

Once the MariaDB is secured, log in to MariaDB shell:

mysql -u root -p

Enter your root password when prompt. Then, create a database and user for PageKit with the following command:

MariaDB [(none)]> CREATE DATABASE pagekitdb;
MariaDB [(none)]> CREATE USER pagekit;

Next, grant privileges to the PageKit database with the following command:

MariaDB [(none)]> GRANT ALL PRIVILEGES ON pagekitdb.* TO 'pagekit'@'localhost' IDENTIFIED BY 'password';

Next, flush the privileges with the following command:

MariaDB [(none)]> FLUSH PRIVILEGES;

Next, exit from the MariaDB console with the following command:

MariaDB [(none)]> exit

Download PageKit

First, you will need to download the latest version of PageKit CMS from their official website. You can download it with the following command:

wget https://pagekit.com/api/download/latest -O pagekit.zip

Once the download is completed, unzip the downloaded file to the Apache web root directory with the following command:

sudo unzip pagekit.zip -d /var/www/html/pagekit

Next, give proper permissions to the pagekit directory with the following command:

sudo chown -R www-data:www-data /var/www/html/pagekit/
sudo chmod -R 777 /var/www/html/pagekit/

Next, you can proceed to configure Apache for PageKit.

Configure Apache for PageKit

Next, you will need to create an Apache virtual host file for PageKit CMS. You can do this by creating pagekit.conf file as shown below:

sudo nano /etc/apache2/sites-available/pagekit.conf

Add the following lines:


     ServerAdmin [email protected]
     DocumentRoot /var/www/html/pagekit
     ServerName example.com

     
          Options FollowSymlinks
          AllowOverride All
          Require all granted
     

     ErrorLog ${APACHE_LOG_DIR}/pagekit_error.log
     CustomLog ${APACHE_LOG_DIR}/pagekit_access.log combined

Save and close the file. Then, enable PageKit virtual host file with the following command:

sudo a2ensite pagekit

Next, enable Apache rewrite module and restart Apache web server to apply all the changes:

sudo a2enmod rewrite
sudo systemctl restart apache2

Access PageKit CMS

PageKit CMS is now installed and configured. It’s time to access PageKit web installer wizard.

Open your web browser and type the URL http://example.com. You will be redirected to the following page:

PageKit Installer

Now, click on the Arrow button. You should see the following page:

Choose Language

Here, select your language and click on the NEXT button. You should see the following page:

Connect Database

Here, provide your database name, database username and password. Then, click on the NEXT button. You should see the following page:

Setup site in PageKit

Here, provide your site title, admin username and password. Then, click on the INSTALL button. You should see the following page:

Log in

Now, provide your admin login details and click on the LOGIN button. You should see the PageKit CMS default dashboard in the following page:

PageKit Dashboard

Congratulations! you have successfully installed PageKit CMS on Ubuntu 18.04 server. I hope you can now easily edit the website to create a modern looking website for your business. Feel free to ask me if you have any questions.

Linux type Command Tutorial for Beginners (with Examples)

Linux type Command Tutorial for Beginners (with Examples)

On the Linux command line, you’ll come across several types of utilities. Some are an alias, while others are built-in tools and even functions. So, how do you check these types? Well, there exists a command ‘type‘ that offers you this information. In this tutorial, we will discuss the ‘type’ command using some easy to understand examples.

But before we do that, it’s worth mentioning that all examples here have been tested on an Ubuntu 18.04 LTS machine.

Linux type command

As already mentioned in the introduction above, the type command in Linux displays information about command type. Following is its syntax:

type [-afptP] name [name ...]

And here are some Q&A-styled examples that should give you a better idea on how the type command works.

Q1. How to use type command?

It’s simple, just execute ‘type’ with the command line tool name as input and -t as the command line option. For example,

type -t cp

This command produced the following output:

file

Similarly, if the tool name is an alias, then the type command clearly tells that. For example, the following command:

type -t ls

produced this output:

alias

Here’s how the tool’s man page explains the -t option:

-t	output a single word which is one of `alias', `keyword',
    	`function', `builtin', `file' or `', if NAME is an alias, shell
    	reserved word, shell function, shell builtin, disk file, or not
    	found, respectively

For this, execute the type command sans any option. Here’s an example:

How to make type print location of tools

Use the -a command line option for this. Here’s an example:

type -a ls

This command produced the following output on my system:

ls is aliased to `ls --color=auto'
ls is /bin/ls

Q4. How to make type search even if input is an alias?

By default, if you input an alias (like ‘ls’ on some systems), the type command doesn’t produce location in output. For example:

type ls

Here’s the output:

ls is aliased to `ls --color=auto'

However, if you want, you can force ‘type’ to search for location even if the input is an alias. This can be done using the -P command line option.

-P      force a PATH search for each NAME, even if it is an alias,
       	builtin, or function, and returns the name of the disk file
    	that would be executed

How to make type search even if input is an alias

Conclusion

The type command doesn’t have a steep learning curve. Many of the options it provides we’ve discussed in this tutorial. Once you’re done testing these, head to the ‘type’ command man page to learn more about it.

How to Install Anchor CMS on CentOS 7

How to Install Anchor CMS on CentOS 7

Anchor is a lightweight open source blog CMS written in PHP. Anchor’s source code is hosted on GitHub. This tutorial will show you how to install Anchor CMS on a CentOS 7 system.

Requirements

Make sure your server meets the following requirements.

  • MySQL 5.6 or greater (MySQL 5.7 recommended)
  • PHP 5.6 or greater with the following PHP extensions: (curlmcrypt, gd, mbstring, pdo_mysql or pdo_sqlite)
  • Apache or Nginx. In this tutorial we will use Nginx.
  • CentOS 7 operating system.
  • A non-root user with sudo privileges.

Initial steps

Check your CentOS system version:

cat /etc/centos-release
# CentOS Linux release 7.5.1804 (Core)

Set up the timezone:

timedatectl list-timezones
sudo timedatectl set-timezone 'Region/City'

Update your operating system’s packages:

sudo yum update -y

Install some useful packages if they are not already installed:

sudo yum install -y vim wget curl git unzip bash-completion

Step 1 – Install PHP and necessary PHP extensions

Anchor CMS requires PHP version 5.6 or greater. Default CentOS repositories contain an older version of PHP, and thus we will need to set up a third-party repository to install a newer PHP version. We will use Webtatic repository.

Setup the Webtatic YUM repo:

sudo rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm

Install PHP, as well as the necessary PHP extensions:

sudo yum install -y php72w php72w-cli php72w-fpm php72w-common php72w-mbstring php72w-curl php72w-mysql php72w-sqlite3 php72w-gd php72w-mcrypt php72w-dom

Check the PHP version:

php --version

# PHP 7.2.12 (cli) (built: Nov 11 2018 14:54:16) ( NTS )
# Copyright (c) 1997-2018 The PHP Group
# Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

Start and enable PHP-FPM service:

sudo systemctl start php-fpm.service
sudo systemctl enable php-fpm.service

Step 2 – Install MariaDB and create a database for Anchor CMS

Anchor supports MySQL/MariaDB and SQLite databases. Default CentOS repository contains an unsupported version of MariaDB. Because of that, we will use the official MariaDB repository that contains a newer version of MariaDB.

Create MariaDB YUM repository for CentOS:

sudo vim /etc/yum.repos.d/MariaDB.repo

Copy and paste the following text into it:

# MariaDB 10.2 CentOS repository list - created 2017-12-11 23:19 UTC
# http://downloads.mariadb.org/mariadb/repositories/
[mariadb]
name=MariaDB
baseurl=https://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1

After the file is in place, install MariaDB by running:

sudo yum install -y MariaDB-server MariaDB-client

Check the MariaDB version:

mysql --version
# mysql  Ver 15.1 Distrib 10.2.19-MariaDB, for Linux (x86_64) using readline 5.1

Start and enable MariaDB service:

sudo systemctl start mariadb.service
sudo systemctl enable mariadb.service

Run mysql_secure installation script to improve MariaDB security and set the password for MariaDB root user:

sudo mysql_secure_installation

Answer all the questions as shown below:

Enter current password for root (enter for none):
Set root password? [Y/n]: Y
Remove anonymous users? [Y/n]: Y
Disallow root login remotely? [Y/n]: Y
Remove test database and access to it? [Y/n]: Y
Reload privilege tables now? [Y/n]: Y

Log into MariaDB shell as the user root:

mysql -u root -p
# Enter password

Create a MariaDB database and user that you will use for your installation of Anchor CMS, and remember the credentials:

CREATE DATABASE dbname;
GRANT ALL ON dbname.* TO 'username' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;

Exit from MariaDB shell:

quit

Step 3 – Install and configure Nginx

Install Nginx web server:

sudo yum install -y nginx

Check the Nginx version:

nginx -v
# nginx version: nginx/1.12.2

Start and enable Nginx service:

sudo systemctl start nginx.service
sudo systemctl enable nginx.service

Run sudo vim /etc/nginx/conf.d/anchor.conf and populate the file with the following configuration:

server {
    listen 80;

    server_name example.com;
    root /var/www/anchor;

    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php;
    }
    
    location ~ .php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

}

Test Nginx configuration:

sudo nginx -t

Reload Nginx:

sudo systemctl reload nginx.service

Step 4 – Download and install Composer

To successfully install Anchor, we will need to install Composer, the dependency manager for PHP applications:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

php -r "if (hash_file('SHA384', 'composer-setup.php') === '93b54496392c062774670ac18b134c3b3a95e5a5e5c8f1a9f115f203b75bf9a129d5daa8ba6a13e2cc8a1da0806388a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"

php composer-setup.php

php -r "unlink('composer-setup.php');"

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

Check the Composer version.

composer --version
# Composer version 1.8.0 2018-12-03 10:31:16

Step 5 – Download and install Anchor CMS

Create a document root directory:

sudo mkdir -p /var/www/anchor

Change ownership of the /var/www/limesurvey directory to [jour_user]:

sudo chown -R [your_user]:[your_user] /var/www/anchor

Navigate to document root:

cd /var/www/anchor

Download the latest release of Anchor CMS by using Composer:

composer create-project anchorcms/anchor-cms .

Change ownership of the /var/www/anchor directory to nginx:

sudo chown -R nginx:nginx /var/www/anchor

Create the directory/var/lib/php/session and set ownership to nginx.

sudo mkdir -p /var/lib/php/session && sudo chown -R nginx:nginx /var/lib/php

Run sudo vim /etc/php-fpm.d/www.conf and set the user and group to nginx. Initially, they will be set to apache:

sudo vim /etc/php-fpm.d/www.conf
# user = nginx
# group = nginx

Restart the PHP-FPM service:

sudo systemctl restart php-fpm.service

Step 6 – Complete the Anchor CMS setup

Open your web browser and type the URL “http://example.com”. You will be redirected to the following page:

Anchor CMS web installer

Click on the “Run the installer” button, to initiate Anchor CMS web installer. After, language and timezone page should appear:

Select Language and Time zone

Select the settings that you want and click on the “Next Step” button to proceed to the database configuration page:

Database settings

Enter your database details, and click on the “Next Step” button to proceed to site metadata configuration page:

Site Metadata

You can set site name or site description here, or leave the defaults and change it later via Anchor backend interface. Click on the “Next Step” button for the next step which is setting your first account:

Create admin account

After setting up your first account, click on the “Complete” button to finish the installation process.

Once you have completed the install, make sure to delete install folder for security purposes.

sudo rm -rf /var/www/anchor/install

Links