How to install php 7 to run beside php 5 on ubuntu with nginx

Firstly, you need to install php5-fpm and php7.0-fpm from Ondřej Surý's PPA for co-installable php5 and php7.0.:

sudo apt-get install python-software-properties
sudo LC_ALL=en_US.UTF-8 add-apt-repository ppa:ondrej/php

We then, with nginx, suggest using the FPM packages. So, install the packages accordingly:

sudo apt-get update

# We need to ***remove*** php5 packages, so we can use php5.6 packages
# from the PPA instead
sudo apt-get remove php5-common
sudo apt-get autoremove

# Now we install php5.6 packages.
sudo apt-get install php5.6-fpm

# Now, install php7.0-fpm.  You may need to install separate PHP plugins
# for databases, extensions, etc. later.
sudo apt-get install php7.0-fpm

Source: An answer on the "How to install php 7?" question, and custom comments and modifications from myself.


Secondly, nginx. nginx is only able to be as good as your configurations. You very likely have a PHP handling block on your nginx server block(s) similar to this (from the 'default' example config):

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000

location ~ \.php$ {
    include snippets/fastcgi-php.conf;

    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}

This configuration will only pass to php5-fpm. In effect, this will apply for your entire server block. The easiest way to go about this is to have a second server block (for, say, test.domain.tld), and provide instead the PHP 7.0 fastcgi_pass destination. In php7.0 on Xenial, this is going to end up something like this (extracted from a fix recently uploaded to the Xenial nginx package), however I do not know the layout of Ondrej's package so I cannot give exact specifics there (check /etc/php7.0/fpm/pool.d/www.conf or similar to determine where it's listening):

location ~ \.php$ {
    include snippets/fastcgi-php.conf;

    # With php7.0-fpm:
    fastcgi_pass unix:/var/run/php7.0-fpm.sock;
}

You will have to do something similar for your php5 block, to validate that php5.6 sockets are used instead of the built-in php5 socket (which we just removed).

Then, use the second test domain to run the php7.0 testing. Make sure, though, to make a copy of your site if you want to do this - it will likely be necessary to have a separate testing copy so that once you've finished getting it working with php7.0, you can just 'switch over' without issue.

There is, unfortunately, no easy way to make php5 and php7.0 work within the same server block, not without altering your paths for your site, applications, etc. to have one for php5 and one for php7.0; such reworking of sites can get nasty, hence the suggestion to run two separate copies of the site code, one for php7.0 migration and one for php5 in production.