Advertisement
drkskwlkr

Add redis config data to wp-config.php

May 6th, 2023 (edited)
895
1
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 2.14 KB | Source Code | 1 0
  1. #!/bin/bash
  2.  
  3. # Look for wp-config.php in the current directory and if it exists, read db-name value
  4. if [ -f "wp-config.php" ]; then
  5.   # Read db-name value from wp-config.php
  6.   db_name=$(grep -oP "(?<=DB_NAME',\s').*(?=')" wp-config.php)
  7.  
  8.   # Abort execution with an error message if DB_NAME is empty
  9.   if [ -z "$db_name" ]; then
  10.     echo "Error: WordPress instance seems misconfigured. DB_NAME is not defined in wp-config.php."
  11.     exit 1
  12.   fi
  13.  
  14.   # Check if /etc/redis/redis.conf exists and abort execution with an error message if it does not
  15.   if [ ! -f "/etc/redis/redis.conf" ]; then
  16.     echo "Error: redis.conf could not be located."
  17.     exit 1
  18.   fi
  19.  
  20.   # Read bind IP, port number and password from /etc/redis/redis.conf
  21.   bind_ip=$(grep -oP '^bind\s+\K\S+' /etc/redis/redis.conf)
  22.   port=$(grep -oP '^port\s+\K\S+' /etc/redis/redis.conf)
  23.   password=$(grep -oP '^requirepass\s+\K\S+' /etc/redis/redis.conf)
  24.  
  25.   # Create a random 16-character string derived from the db-name value
  26.   salt=$(echo -n "$db_name" | md5sum | cut -c -16)
  27.  
  28.   # Determine the Redis host name or IP based on the bind IP
  29.   if [ "$bind_ip" == "127.0.0.1" ] || [ "$bind_ip" == "::1" ]; then
  30.     redis_host="localhost"
  31.   else
  32.     redis_host=$bind_ip
  33.   fi
  34.  
  35.   # Check if any Redis constants are already defined in wp-config.php, and exit with a warning if they are
  36.   if grep -qE "define\(['\"]?(WP_REDIS_HOST|WP_REDIS_PORT|WP_REDIS_PASSWORD|WP_CACHE_KEY_SALT)['\"]?\s*,\s*['\"]" wp-config.php; then
  37.     echo "Warning: Some or all Redis constants may already be defined in wp-config.php. Exiting without writing anything."
  38.     exit
  39.   fi
  40.  
  41.   # Write the new Redis constants inside wp-config.php before the "That's all, stop editing! Happy publishing." line
  42.   sed -i "s#/\* That's all, stop editing! Happy publishing\. \*/#define( 'WP_REDIS_HOST', '$redis_host' );\\
  43. define( 'WP_REDIS_PORT', '$port' );\\
  44. define( 'WP_REDIS_PASSWORD', '$password' );\\
  45. define( 'WP_CACHE_KEY_SALT', '$salt' );\\
  46. \\
  47. /\* That's all, stop editing! Happy publishing. \*/#" wp-config.php
  48.  
  49.   echo "New Redis constants added to wp-config.php"
  50. else
  51.   echo "Error: wp-config.php not found"
  52.   exit 1
  53. fi
Advertisement
Comments
Add Comment
Please, Sign In to add comment
Advertisement