Halloween Sale 15% off Ends in See the plans
PHP

Email Alert When Disk Space Runs Low

Checks free disk space on the server twice a day and emails the admin when it drops below your threshold, before uploads, backups and the database start failing.

Don’t have WPIDE yet? Install it on your site

Code

$wpide_min_free_gb = 2;

add_action( 'init', function () {
    if ( ! wp_next_scheduled( 'wpide_disk_space_check' ) ) {
        wp_schedule_event( time() + HOUR_IN_SECONDS, 'twicedaily', 'wpide_disk_space_check' );
    }
} );

add_action( 'wpide_disk_space_check', function () use ( $wpide_min_free_gb ) {
    if ( ! function_exists( 'disk_free_space' ) || get_transient( 'wpide_disk_alert_sent' ) ) {
        return;
    }

    $free = @disk_free_space( ABSPATH ); // phpcs:ignore WordPress.PHP.NoSilencedErrors
    if ( false === $free || $free >= $wpide_min_free_gb * GB_IN_BYTES ) {
        return;
    }

    set_transient( 'wpide_disk_alert_sent', 1, DAY_IN_SECONDS );
    wp_mail(
        get_option( 'admin_email' ),
        sprintf( '[%s] Low disk space: %s free', wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), size_format( $free ) ),
        sprintf( "The server hosting %s has only %s of free disk space left (alert threshold: %d GB).\n\nClear old backups, logs or unused media, or ask your host for more space.", home_url(), size_format( $free ), $wpide_min_free_gb )
    );
} );

Notes

Does nothing on hosts that disable disk_free_space(), and repeats the alert at most once a day while space stays low.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.