Published on

How to install PHP Extensions in wp-env

WP-ENV has became my default wordpress development setup on windows via WSL2 for WordPress theme and plugin development, however until recently i had ran into issues with configuring wp-env to install extra php extensions such as SOAP or FTP, which in this article i will explain how the installation of php extension can be automated to run when wp-env starts.

The main issue i ran into when install php extensions via wp-env was that it runs as a non root user, which meant the installation of php extensions via the wp-env command failed due to a user permissions error.

wp-env run wordpress docker-php-ext-install ftp

Location wp-env install path

Since wp-env uses docker compose, we can run commands directly on the underlying docker containers bypassing the wp-env non root user, to get the docker-compose install path you can use the following command.

wp-env install-path

Installing php extensions in wp-env

Now if we navigate to the install path of the wp-env environment, docker compose commands can be used, for example if you wanted to install the php ftp extension you would use the following command to run on the wordpress container under the root user.

docker-compose exec -it -u root wordpress docker-php-ext-install ftp

With the php extension installed an activated we need to reload the apache webserver.

docker-compose exec -it -u root wordpress service apache2 reload

Put this all together

This can be combined and automated using the wp-env lifecycle scripts to run a bash script every time wp-env is started.

.wp-env.json
{
    "lifecycleScripts": {
        "afterStart": "bash ./setup.sh"
    }
}

The following bash script has been expanded to check if the ftp extension is installed, if not it will attempt to install it and reload apache if successful.

setup.sh
#!/usr/bin/env bash

# Get install Path
cd $(wp-env install-path)

# Reload Apache flag
RELOAD=false

# Install PHP FTP Extension
if [[ $(docker-compose exec -it -u root wordpress php -m | grep ftp) != "ftp" ]]; then

    echo "Installing: FTP Extension."
    docker-compose exec -it -u root wordpress docker-php-ext-install ftp
    if [[ $(docker-compose exec -it -u root wordpress php -m | grep ftp) == "ftp" ]]; then
        echo "FTP Extension: Installed."
    else
        echo "FTP Extension: Failed."
    fi

    RELOAD=true
fi

# Reload Apache
if [[ $RELOAD == true ]]; then
    docker-compose exec -it -u root wordpress service apache2 reload
fi