Skip to content

Instantly share code, notes, and snippets.

@halkyon
Last active September 2, 2017 00:02
Show Gist options
  • Save halkyon/15bcf89ccf4e25548b2ac3f334e0cd0d to your computer and use it in GitHub Desktop.
Save halkyon/15bcf89ccf4e25548b2ac3f334e0cd0d to your computer and use it in GitHub Desktop.
Install and switch between PHP versions (5.6, 7.0, and 7.1) using deb.sury.org packages
#!/bin/bash
# todo: support fpm as well as apache
# use bash "strict mode" http://redsymbol.net/articles/unofficial-bash-strict-mode/
set -euo pipefail
IFS=$'\n\t'
if [ $EUID -ne 0 ]; then
echo "This script must be run as root"
exit 1
fi
if [ $# -eq 0 ]; then
echo "Usage: switch_php <selected_version>"
echo "where <selected_version> is either 5.6, 7.0, or 7.1"
exit 1
fi
selected_version=$1
versions=(
"5.6"
"7.0"
"7.1"
)
extensions=(
"bcmath"
"cli"
"common"
"curl"
"dev"
"gd"
"intl"
"json"
"ldap"
"mbstring"
"mcrypt"
"mysql"
"opcache"
"readline"
"sqlite3"
"tidy"
"xml"
"zip"
)
# install deb.sury.org package source as needed
if [ "$(apt-cache search php5.6 | wc -l)" -eq 0 ]; then
apt-get -y install wget apt-transport-https lsb-release ca-certificates
wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list
apt-get update
fi
# purge any existing php5 packages from built-in packages
apt-get -y purge php5 php5-* libapache2-mod-php5
apt-get -y autoremove
# install deb.sury.org packages
for version in ${versions[@]}; do
apt-get -y install "php$version" "libapache2-mod-php$version" "${extensions[@]/#/php$version-}"
done
# set selected version
update-alternatives --set php "/usr/bin/php$selected_version"
update-alternatives --set php-config "/usr/bin/php-config$selected_version"
update-alternatives --set phpize "/usr/bin/phpize$selected_version"
# disable all libapache2 php mods
for version in ${versions[@]}; do
a2dismod "php$version"
done
# enable the selected version and restart apache
a2enmod "php$selected_version"
service apache2 restart
@fer-ri
Copy link

fer-ri commented Sep 1, 2017

Thanks for this 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment