Here's a small addition to your switching script that sets the command line alternative. This gets both the server and the command line in sync using the same version of PHP:

sudo a2dismod php5 php5.6 php7.0 php7.1;
sudo a2enmod php7.1;
sudo service apache2 restart;
sudo update-alternatives --set php /usr/bin/php7.1;

Run "sudo update-alternatives --config php" to see a list of possible values to set.