Easy “Maintenance Mode” with PHP

When updating or modifying your site, it can be extremely useful to have a function which temporarily redirect your readers to a maintenance page.
Here is a snippet to do it easily.

function maintenance($mode = FALSE){
    if($mode){
        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
            header("Location: http://example.com/maintenance.php");
            exit;
        }
    }else{
        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
            header("Location: http://example.com/");
            exit;
        }
    }
}

Usage

In order to activate the maintenance mode, you only have to pass TRUE to the function:

maintenance(TRUE);

Due to the use of the header() function, always make sure that the function is called before any actual output is sent.

3 Comments

  1. Posted July 12, 2010 at 10:02 am | Permalink

    Thanks for the code.

    I’d prefer to use a htaccess for a maintenance mode in my sites. Here is a sample code – http://pastebin.com/0eReY6Xt

    • Posted July 12, 2010 at 12:50 pm | Permalink

      I generally use .htaccess as well, but I like this php solution as well. Thank you for sharing.

  2. Posted July 13, 2010 at 5:20 am | Permalink

    Or if you use a framework, you could add it to the router… if $config['maintenance'] === true then go to maintenance page;

2 Trackbacks

  1. [...] This post was mentioned on Twitter by Jean-Baptiste Jung. Jean-Baptiste Jung said: RT @phpsnippets: New PHP Snippet published: Easy “Maintenance Mode” with PHP http://bit.ly/aKATEB #php [...]

  2. By 10 life-saving PHP snippets on July 19, 2010 at 4:07 pm

    [...] == 'maintenance.php'){ header("Location: http://example.com/"); exit; } } }Source: http://www.phpsnippets.info/easy-maintenance-mode-with-phpPrevent js and css files from being cachedBy default, external files such as javascript and css are [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>