Tuesday, November 20, 2018


PHP and Nginx

PHP (or PHP Hypertext Preprocessor) is a server-side scripting language that is used to create
dynamic web pages that can interact with databases.

Benefits of developing website with PHP.

  • PHP is open source scripting language.
  • It’s easy to develop and manage.
  • It gives low development and maintenance cost with very high performance and reliability.
  • PHP gives us database flexibility as well.
  • From PHP 7, programming with object oriented is also easy and advanced.
  • The main benefit of PHP is its platform independent.

As PHP is open source and light weight, web service API development is more beneficial and faster
using PHP language.

To execute php files, we need some web server and php executable files. Apache is a web server
used to run PHP files. Apache was the backbone of the first generation of the World Wide Web,
becoming the industry standard for web serving almost as soon as it debuted in 1995. It was created
at a time when the World Wide Web was still a novelty. Traffic levels were low, web pages were
simple, bandwidth was constrained and expensive, and CPU was relatively cheap. There was a
huge thirst in the early community to innovate with new technologies, and Apache was the platform
of choice.

Apache’s architectural model:

The simplicity of Apache’s architectural model was key to its early success. Apache adopted  prefork
model in which pool of worker processes was created in advance. When a prefork Apache web
server received an HTTP connection, one of the httpd worker processes grabbed and handled it.
Each process handled one connection at a time, and if all of the processes were busy, Apache
created more worker processes to be ready for a further spike in traffic.


Problem Or Challenges in Apache Model:
Over the past 20 years, there has been explosive growth in the volume of traffic and the number of
users on the World Wide Web.

At the same time, the weight of web pages (the size and number of components the web browser
has to fetch to render a page) has grown steadily, and users have become less and less patient
about waiting for web pages to load.

The Apache web server always spawns a child process each time a new request comes in, this
means that if you are website or web service is getting lots and lots of request, then you will start
having problems with RAM because each process takes at chunk of the RAM for dealing with a
request.

So now Nginx comes in picture.

What is Nginx:
Nginx is most popular open source web server like APACHE. Nginx is also well known for High
performance load balancer. Nginx is developed by Igor Sysoev. The purpose  is to accelerating a
large Apache‑based service.

Nginx and PHP-FPM is a better option given. Nginx is event driven and takes under 10MB of your
RAM when handling large number of request. PHP-FPM has come a long way and lately has
improved in terms of speed. It’s a lot better than mod_php because its an independent process on its
and does not require that it be loaded by the web server. Nginx communicates with it via TCP so
generally both Nginx and PHP-FPM have a low memory footage


php-fpm stands for php fastcgi process manager. It is a fastcgi implementation of php with some
additional features. Have a look here http://php-fpm.org/

How to Set Up Nginx in your web server:
For Ubuntu - Linux :
Step 1:  Run following command and install nginx in your web server.
Sudo apt-get update
Sudo apt install nginx

Step 2: After installation of nginx, stop apache server if its running by default and start nginx service
with following commands:
sudo service stop apache2
sudo service start nginx
sudo enable nginx

Step 3: Check status of nginx service:
Sudo service nginx status.

Step 4: Now install php-fpm module along with additional dependant modules by using  following command:
sudo apt-get install php-fpm php-mcrypt php-cli php-mysql php-gd php-imagick php-recode php-tidy
php-xmlrpc

Step 5: Now configure Nginx with php:

Now as Nginx and PHP are installed, you may want to configure Nginx to use PHP properly.
The default Nginx PHP configuration file is located at /etc/php/7.x/fpm/php.ini
The X in the location will be 0 or 1 depending on the php version installed.
Open PHP Nginx configuration file by running the commands below:

sudo nano /etc/php/7.1/fpm/php.ini

Next edit the file to suit your environments. Some important lines to consider:

file_uploads = On
allow_url_fopen = On
memory_limit = 256M
upload_max_filesize = 64M

Next, open the Nginx site configuration file and wrote below code in that file… by default it’s stored
at /etc/nginx/sites-available/default

sudo nano /etc/nginx/sites-available/default

server {
listen 80;
listen [::]:80;
root /var/www/html;
index  index.php index.html index.htm;
server_name  example.com www.example.com;

location / {
    try_files $uri $uri/ =404;  
}

# pass PHP scripts to FastCGI server
    #
    location ~ \.php$ {
           include snippets/fastcgi-php.conf;
    #
    #    # With php-fpm (or other unix sockets):
          fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    #    # With php-cgi (or other tcp sockets):
    #    fastcgi_pass 127.0.0.1:9000;
 
}
Restart Nginx and PHP-FPM services

Step 6: Test your configuration:
http://localhost/phpinfo.php

Bingo!!! Nginx is now installed and you can start your development.

For Windows, we can use WEMP instead of WAMP.
Here is the link to download and install WEMP in windows platform.


Benefits with PHP frameworks (Symfony):

As php is growing fast and large scale projects are now developed in project, some frameworks also
developed. These frameworks helps to manage code and make it more flexible. Symfony is one of
most popular framework used in PHP for large scale projects.

The minimum configuration to get your application running under Nginx is:

server {
server_name domain.tld www.domain.tld;
root /var/www/project/public;

location / {
    # try to serve file directly, fallback to index.php
    try_files $uri /index.php$is_args$args;
}

location ~ ^/index\.php(/|$) {
    fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
    fastcgi_split_path_info ^(.+\.php)(/.*)$;
    include fastcgi_params;

    # optionally set the value of the environment variables used in the application
    # fastcgi_param APP_ENV prod;
    # fastcgi_param APP_SECRET <app-secret-id>;
    # fastcgi_param DATABASE_URL "mysql://db_user:db_pass@host:3306/db_name";

    # When you are using symlinks to link the document root to the
    # current version of your application, you should pass the real
    # application path instead of the path to the symlink to PHP FPM.
    # Otherwise, PHP's OPcache may not properly detect changes to
    # your PHP files (see https://github.com/zendtech/ZendOptimizerPlus/issues/126
    # for more information).
    fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT $realpath_root;
    # Prevents URIs that include the front controller. This will 404:
    # http://domain.tld/index.php/some-path
    # Remove the internal directive to allow URIs like this
    internal;
}

# return 404 for all other php files not matching the front controller
# this prevents access to other php files you don't want to be accessible.
location ~ \.php$ {
    return 404;
}

error_log /var/log/nginx/project_error.log;
access_log /var/log/nginx/project_access.log;
}

Top 5 points to consider for selecting nginx with symfony
  1. Nginx support reverse proxy, using this feature, we can decrease the number of calls to our applications by enabling load balancing.

  1. Along with load balancing, NGINX Plus offers more sophisticated session persistence, often highly relevant for symfony.
  2. Compared to Apache2, nginx performs better at serving static files and when under high traffic. Applications built with HTTP frameworks (e.g. Symfony) benefit from the HTTP cache specification.Since nginx sits between clients (e.g. browsers) and the application, it can act as the cache.

  1. This results in a drastic reduction of response time from the point of view of the client.
  2. Micro cashing technique of Nginx fasten performance.