As part of our web builds we like to make managing website content as easy as possible for our clients, this even includes brand assets like Logo’s etc. We have a simple rule; clients shouldn’t need to come back to us for anything that isn’t new functionality.

Our themes support SVG uploads, and to utilise the manipulation of SVGs (animations, colour changes on hover etc) we need to grab the SVG code from the upload and print that to the DOM.

We were doing this via the php function file_get_contents

But as it turns out, after a lengthy support chat with WPEngine, there’s something about the WPEngine server environment that doesn’t support file_get_contents

After a little digging, I found a workaround with the WordPress function wp_remote_get

Here’s a function I created to fetch the SVG content of an uploaded SVG asset:

// function to return svg code from an uploaded SVG asset
// first we need to grab the url to the asset
function svg_upload( $url ) {

    // Check the SVG file exists
    if (wp_check_filetype($url)['ext'] == 'svg' ) :

        $request = wp_remote_get( $url, stream_context_create([
            'ssl' => [
                'allow_self_signed'=> true
            ]
        ]) );
        return wp_remote_retrieve_body( $request );
    
    else : ?>
    // if the file is not an SVG, it should at least be an image url
        <img src="<?= $url ?>" alt=" <?= get_bloginfo('name'); ?>" />
    <?php endif;

    // Return a blank string if we can't find the file.
    return '';
}

wp_remote_get returns an array, we only want the body of the file so to get that we use the wp_remote_retrieve_body function and pass through the data we received through wp_remote_get

To use the function in our theme we simply use:

<?php echo svg_upload($url); ?>

// in our case the SVG url is pulled from a custom field and assigned
// to the variable $url

WPEngine 401 Authorization Required error

This workaround worked perfectly in my local environment but when it was uploaded to a password protected staging site on WPEngine the error message ‘401 Authorization Required’ appeared wherever the SVGs were intended to display.

This turned out to be due the password protection on the staging site which was set at the HTTP level (within WPEngine).

The problem was that we can’t present the site with these errors showing to a client, but WPEngine also doesn’t allow us to remove password protection on non-billable sites (we use non-billable sites for hosting client staging websites before transferring ownership when we’re ready for launch).

The only workaround for this was to create a backup of the staging site and copy it across to an empty dev environment of one of our billable sites. Rather frustrating but it at least did the trick. Just something to be aware of.