Wordpress - Best way to abort plugin in case of insufficient PHP version?

This function and activation hook prevents the plugin from activating and allows you to check for both a minimum PHP and WordPress version.

register_activation_hook( __FILE__, array( 'Your_Plugin_Class_Name', 'activate' ) );

/**
  * Plugin Activation hook function to check for Minimum PHP and WordPress versions
  * @param string $wp Minimum version of WordPress required for this plugin
  * @param string $php Minimum version of PHP required for this plugin
  */
 function activate( $wp = '3.1', $php = '5.2.4' ) {
    global $wp_version;
    if ( version_compare( PHP_VERSION, $php, '<' ) )
        $flag = 'PHP';
    elseif
        ( version_compare( $wp_version, $wp, '<' ) )
        $flag = 'WordPress';
    else
        return;
    $version = 'PHP' == $flag ? $php : $wp;
    deactivate_plugins( basename( __FILE__ ) );
    wp_die('<p>The <strong>Insert PLugin Name Here</strong> plugin requires'.$flag.'  version '.$version.' or greater.</p>','Plugin Activation Error',  array( 'response'=>200, 'back_link'=>TRUE ) );
}

/**
 * Plugin Name: Foo
 */

// Check for required PHP version
if ( version_compare( PHP_VERSION, '5.1', '<' ) )
{
    exit( sprintf( 'Foo requires PHP 5.1 or higher. You’re still on %s.', PHP_VERSION ) );
}

// The rest of your plugin code follows

I'm not sure since which WP version this happened, but in 3.5 the plugin actually fails to activate and the error message is shown to the user in the admin, which is neat.

The error message is not translated, though. In order to do that you’d have to load your translation files right before the exit call.


You could activate it and show an error message:

// if PHP version is lower than 5.1
if(version_compare(PHP_VERSION, '5.1') < 0){

  // show a message inside the dashboard
  if(is_admin()){

    function my_plugin_notice(){      
      ?>
      <div class="error below-h2">
        <p>
        <?php
          printf(__('The abc plugin requires at least PHP 5.1. You have %s'), PHP_VERSION);
         ?>
        </p>
      </div>
      <?php
    }

    add_action('admin_notices', 'my_plugin_notice');

  }

  // stop here and do nothing further
  return;  
}

// if PHP version is equal or higher than 5.1
require dirname(__FILE__) . '/php51code.php';

It's also probably possible to deactivate it programmatically, before the return statement...