How To Check If Mod_Rewrite Is Enabled In PHP?

Published September 13, 2024

Problem: Checking Mod_Rewrite Status in PHP

Determining if mod_rewrite is enabled in PHP is important for web applications that use URL rewriting. This Apache module allows URL manipulation, which is needed for creating clean, user-friendly links and implementing routing techniques.

Checking Mod_Rewrite Status in PHP

Method 1: Using apache_get_modules()

The apache_get_modules() function in PHP lists all loaded Apache modules. It's a simple way to check if mod_rewrite is enabled.

Here's a code snippet to check for mod_rewrite:

if (function_exists('apache_get_modules')) {
    $modules = apache_get_modules();
    $mod_rewrite = in_array('mod_rewrite', $modules);
    echo $mod_rewrite ? 'mod_rewrite is enabled' : 'mod_rewrite is not enabled';
} else {
    echo 'apache_get_modules() function not available';
}

This method works only with mod_php and not in CGI/FastCGI environments.

Tip: Error Handling

Add error handling to your code to manage cases where the function might not be available:

try {
    if (function_exists('apache_get_modules')) {
        $modules = apache_get_modules();
        $mod_rewrite = in_array('mod_rewrite', $modules);
        echo $mod_rewrite ? 'mod_rewrite is enabled' : 'mod_rewrite is not enabled';
    } else {
        throw new Exception('apache_get_modules() function not available');
    }
} catch (Exception $e) {
    echo 'Error: ' . $e->getMessage();
}

Method 2: Using phpinfo()

You can also use the phpinfo() function:

  1. Create a PHP file with this content:
    <?php phpinfo(); ?>
  2. Upload and run this file on your server.
  3. Look for the "mod_rewrite" section in the output.

If you see a section for mod_rewrite, it's enabled. If not, it's either disabled or not installed.

This method shows a lot of information but needs manual checking and may pose security risks if left accessible.

Method 3: Server-specific commands

For Apache servers, you can use shell commands:

$output = shell_exec('/usr/local/apache/bin/apachectl -l');
$mod_rewrite = (strpos($output, 'mod_rewrite') !== false);
echo $mod_rewrite ? 'mod_rewrite is enabled' : 'mod_rewrite is not enabled';

For IIS servers, checking mod_rewrite status through PHP is more complex and often needs server-side configuration checks.

When using server commands, be aware of security issues. These methods might not work if PHP's exec functions are disabled for security reasons.