#!/bin/bash # # Universal PHP Extension Duplicate Cleanup with Dry-Run Support # - Removes duplicate extension load lines (extension=*.so, zend_extension=*.so) # - Keeps official conf.d loaders # - Backs up modified files # - Logs all actions # - Restarts PHP/Apache services based on detected OS/cPanel # # Usage: # ./php-extension-cleanup.sh -> cleanup mode (actually removes duplicates) # ./php-extension-cleanup.sh --dry -> dry-run mode (shows what would be changed) LOGFILE="/var/log/php_extension_cleanup.log" DATE=$(date +"%Y-%m-%d_%H-%M-%S") DRYRUN=false # Ensure log file exists if [ ! -f "$LOGFILE" ]; then mkdir -p "$(dirname "$LOGFILE")" touch "$LOGFILE" chmod 644 "$LOGFILE" fi # Check for dry-run flag if [[ "$1" == "--dry" ]]; then DRYRUN=true echo "[$DATE] Running in DRY-RUN mode (no changes will be applied)" | tee -a "$LOGFILE" else echo "[$DATE] Running in CLEANUP mode (duplicates will be removed)" | tee -a "$LOGFILE" fi # Find all ini files with extensions FILES=$(grep -rE "extension\s*=\s*.+\.so|zend_extension\s*=\s*.+\.so" /etc/php* /opt/cpanel/ea-php* 2>/dev/null) if [ -z "$FILES" ]; then echo "[$DATE] No extension references found. Exiting." | tee -a "$LOGFILE" exit 0 fi # Process each unique file found for ini in $(echo "$FILES" | cut -d: -f1 | sort -u); do # Skip conf.d standard loaders (we keep those) if [[ "$ini" =~ conf.d/ ]]; then continue fi if $DRYRUN; then echo "[$DATE] DRY-RUN: Would clean $ini (duplicate extension lines)" | tee -a "$LOGFILE" grep -E "extension\s*=\s*.+\.so|zend_extension\s*=\s*.+\.so" "$ini" | tee -a "$LOGFILE" else BACKUP="${ini}.bak_${DATE}" cp "$ini" "$BACKUP" echo "[$DATE] Backed up $ini -> $BACKUP" | tee -a "$LOGFILE" # Remove extension lines sed -i -E '/^\s*(extension|zend_extension)\s*=.*\.so/d' "$ini" echo "[$DATE] Cleaned $ini" | tee -a "$LOGFILE" fi done # Restart logic only in cleanup mode if ! $DRYRUN; then restart_services() { if command -v whmapi1 >/dev/null 2>&1 || [ -d "/opt/cpanel" ]; then echo "[$DATE] Detected cPanel. Restarting Apache (httpd)..." | tee -a "$LOGFILE" /scripts/restartsrv_httpd elif [ -f "/etc/debian_version" ]; then echo "[$DATE] Detected Debian/Ubuntu. Restarting apache2 and php-fpm..." | tee -a "$LOGFILE" systemctl restart apache2 2>/dev/null systemctl restart php*-fpm 2>/dev/null elif [ -f "/etc/redhat-release" ]; then echo "[$DATE] Detected RHEL/CentOS/Alma/Rocky. Restarting httpd and php-fpm..." | tee -a "$LOGFILE" systemctl restart httpd 2>/dev/null systemctl restart php*-fpm 2>/dev/null else echo "[$DATE] Could not detect OS. Please restart Apache/PHP-FPM manually." | tee -a "$LOGFILE" fi } restart_services fi if $DRYRUN; then echo "[$DATE] DRY-RUN complete. No changes were made. Check $LOGFILE for details." | tee -a "$LOGFILE" else echo "[$DATE] Cleanup complete. See $LOGFILE for details." | tee -a "$LOGFILE" echo "[$DATE] Loaded PHP extensions after cleanup:" | tee -a "$LOGFILE" php -m | tee -a "$LOGFILE" fi