cPanel: Create a MySQL database & user using data from wp-config.php

cPanel: Create a MySQL database & user using data from wp-config.php

Here is a small script that I use when migrating WordPress websites from some other panel to cPanel.

I export the database on the old server and then simply copy the .sql dump file along with all other WP files from the old server to the new one. Afterward, run this script as root user:

./create-db.sh stefan (stefan is the cpanel username)

Th script will do the following:

  • Get the database name, user, and password from the wp-config.php file
  • Add the cp user as prefix to the database name and username – then create them in cpanel.
  • Change the database name and username in the wp-config.php file
  • Change the database host to localhost in wp-config.php file
  • Ask the user for the path to the database dump file to import it.
#!/bin/bash

USER=$1
wp_config="/home/$USER/public_html/wp-config.php"

# read data
db_name=$(grep "DB_NAME" $wp_config | cut -d "'" -f 4)
db_user=$(grep "DB_USER" $wp_config | cut -d "'" -f 4)
db_pass=$(grep "DB_PASSWORD" $wp_config | cut -d "'" -f 4)

# create
uapi --user=$USER Mysql create_database name=$USER"_"$db_name
uapi --user=$USER Mysql create_user name=$USER"_"$db_user password=$db_pass
uapi --user=$USER Mysql set_privileges_on_database user=$USER"_"$db_user database=$USER"_"$db_name privileges=ALL

#write new data
sed -i "s/'DB_NAME', '[^']*'/'DB_NAME', '$USER"_"$db_name'/g" "$wp_config"
sed -i "s/'DB_USER', '[^']*'/'DB_USER', '$USER"_"$db_user'/g" "$wp_config"
sed -i "s/'DB_HOST', '[^']*'/'DB_HOST', 'localhost'/g" "$wp_config"

# prompt user for .sql file path and import
read -p "Enter the path to the .sql import file: " sql_file_path
mysql -u$USER"_"$db_user -p$db_pass $USER"_"$db_name < $sql_file_path

Save it as create-db.sh

Add execution: chmod +x create-db.sh and run it along with the cpanel username:

./create-db.sh cp-username-here

whoami
Stefan Pejcic
Join the discussion

I enjoy constructive responses and professional comments to my posts, and invite anyone to comment or link to my site.