0

I'm a creating WordPress wp-config.php file using wp-cli.
I'm using the option --extra-php to append some php code.

if ! [ -f $ROOT_DIR/wp-config.php ]; then
runuser $WEB_USER -s /bin/sh -c "\
wp config create \
  --dbhost=\"${WORDPRESS_DB_HOST:-mysql}\" \
  --dbname=\"${WORDPRESS_DB_NAME:-wordpress}\" \
  --dbuser=\"${WORDPRESS_DB_USER:-root}\" \
  --dbpass=\"$WORDPRESS_DB_PASSWORD\" \
  --skip-check \
  --extra-php <<PHP
  if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
  $_SERVER['HTTPS']='on';
  PHP"
fi

This is the code I need to be appended to the wp-config.php file:

if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
  $_SERVER['HTTPS']='on';

But $_SERVER is interpreted, and left empty.

if (strpos(['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
['HTTPS']='on';

I've tried to escape it like: \$_SERVER, but I got :

if (strpos($_SERVER[HTTP_X_FORWARDED_PROTO], https) !== false)
$_SERVER[HTTPS]='on';

So I lost all single quotes.

Is there an other way to do this?

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
Bigbenny
  • 243
  • 1
  • 3
  • 10

1 Answers1

2

Quite a quoting mess. You cannot embed a here-doc into a quoted string. You might want to use multiple here-docs, and use a quoted here-doc where you want to inhibit variable expansion:

if ! [ -f "$ROOT_DIR"/wp-config.php ]; then
    # a 'quoted' here-doc
    extraphp=$(cat <<'PHP'
        if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
        $_SERVER['HTTPS']='on';
PHP
    )
    # an unquoted here-doc
    wp_command=$(cat <<WP_CONFIG
        wp config create \
            --dbhost="${WORDPRESS_DB_HOST:-mysql}" \
            --dbname="${WORDPRESS_DB_NAME:-wordpress}" \
            --dbuser="${WORDPRESS_DB_USER:-root}" \
            --dbpass="$WORDPRESS_DB_PASSWORD" \
            --skip-check \
            --extra-php "$extraphp"
WP_CONFIG
    )
    runuser "$WEB_USER" -s /bin/sh -c "$wp_config"
fi

Note the importance of quoting variables.

glenn jackman
  • 238,783
  • 38
  • 220
  • 352