Here’s a shell script that you can use to easily switch between PHP 7.4 and PHP 8.1 on macOS when using Homebrew. The script will handle unlinking the current PHP version, linking the desired one, and restarting Apache to apply the change.
Script: switch_php.sh
#!/bin/bash
# Function to switch PHP versions
switch_php() {
local version=$1
if [ "$version" == "7.4" ]; then
echo "Switching to PHP 7.4..."
brew unlink php@8.1
brew link php@7.4 --force --overwrite
sudo sed -i '' 's|php@8.1|php@7.4|' /opt/homebrew/etc/httpd/httpd.conf
elif [ "$version" == "8.1" ]; then
echo "Switching to PHP 8.1..."
brew unlink php@7.4
brew link php@8.1 --force --overwrite
sudo sed -i '' 's|php@7.4|php@8.1|' /opt/homebrew/etc/httpd/httpd.conf
else
echo "Invalid PHP version specified. Please choose 7.4 or 8.1."
exit 1
fi
# Restart Apache to reflect the change
echo "Restarting Apache..."
sudo brew services restart httpd
# Verify the PHP version
echo "Current PHP version:"
php -v
}
# Check if a version argument was provided
if [ -z "$1" ]; then
echo "Usage: $0 [7.4|8.1]"
exit 1
fi
# Call the switch_php function with the desired version
switch_php "$1"
Steps to Use the Script:
- Create the Script File: Save the script as
switch_php.shin your desired location, such as your home directory:bashCopy codenano ~/switch_php.shPaste the script content, then save and exit. - Make the Script Executable: Make the script executable by running:bashCopy code
chmod +x ~/switch_php.sh - Switch PHP Versions:
- To switch to PHP 7.4:
~/switch_php.sh 7.4 - To switch to PHP 8.1:
~/switch_php.sh 8.1
- To switch to PHP 7.4:
This script will update Apache’s configuration to use the correct PHP version and restart Apache automatically.
Disable the Old PHP Module (PHP 7.4):
Find the line that loads PHP 7.4 and comment it out. It will look something like this:
#LoadModule php7_module /opt/homebrew/opt/php@7.4/lib/httpd/modules/libphp7.so
You can comment it out by adding a # at the beginning of the line.
Enable the PHP 8.1 Module:
Now, add or uncomment the line to load PHP 8.1. It should look something like this:
LoadModule php_module /opt/homebrew/opt/php@8.1/lib/httpd/modules/libphp.so
If the line doesn’t exist, you can add it manually to point to PHP 8.1.
Restart Apache:
After updating the configuration, restart Apache to apply the changes:
sudo brew services restart httpd
Verify PHP 8.1 is Active in Apache:
Create a PHP file in your web server’s document root (usually /opt/homebrew/var/www/ or similar). Create a file called info.php with the following content:
<?php phpinfo(); ?>
Visit http://localhost/info.php in your browser, and you should see the PHP 8.1 information page.
This will make Apache use PHP 8.1 for handling .php files! Let me know if you run into any issues.
Leave a Reply