views:

72

answers:

2

I am using the Zend Framework, and I use the .htaccess for some settings. I am now writing command line scripts for scheduling (e.g. cron). Command line scripts don't look at the .htaccess file because they're not served up by Apache. I would like to parse the .htaccess with my script to retrieve some settings. Here are the lines I'm specifically interested in:

SetEnv APPLICATION_ENV development

php_value date.timezone America/New_York

I noticed the PEAR File_HtAccess package, but it seems to only address authentication portions of the .htaccess file.


SOLUTION: (with credit due to Bamieater)

echo statements for debug output, removed from working code.

$htaccess = file(realpath(dirname(__FILE__)) . '/.htaccess');
echo '<pre>';
foreach ($htaccess as $line) {
    if (preg_match('/^\s*SetEnv\s+APPLICATION_ENV\s+(.*?)\s*$/', trim($line), $matches)) {
        defined('APPLICATION_ENV') || define('APPLICATION_ENV', $matches[1]);
        echo APPLICATION_ENV . PHP_EOL;
    } elseif (preg_match('/^\s*php_(?:admin_)?value\s+date\.timezone\s+(.*?)\s*$/', $line, $matches)) {
        date_default_timezone_set($matches[1]);
        echo date_default_timezone_get() . PHP_EOL;
    }
}
echo '</pre>';
+4  A: 

Read the .htaccess file per line and use a regular expression to access the data.

For example something like this:

$line = "php_value date.timezone America/New_York";
$pattern = "@^php_value date.timezone (.*)$@";

if(preg_match($pattern,$line,$matches))
{
    print_r($matches);
}
Bamieater
Just an addition: I'd use `/^\s*php_(?:admin_)?value`..., just that little bit more robustness.
Wrikken
@Wrikken - I understand the `\s*` part, but what does `(?:admin_)?` accomplish?
Sonny
Found the answer. `php_admin_value` settings set the same values, but cannot be overridden. `?:` at the beginning of a subpattern prevents it's matches from being captured.
Sonny
+1  A: 

Parsing .htaccess, despite it is easy to do, is not the best solution in my opinion.

The environment variable may be set in different places, so you'd have to check all the files (eg. main Apache configuration, other .htaccesses).

I'd recommend setting separate environment variable for your shell scripts,

export APPLICATION_ENV=staging

I keep those settings in global properties of the server (apache config and .bashrc), so automatically all the apps know where they are without changing the files upon deployment.

takeshin
I agree with your opinion, but in my case I don't have control over the Apache environment, nor do I have command-line access, so this one `.htaccess` file is the only place that this environment variable is set. My solution works for me, but may not be optimal for others.
Sonny
Agreed. I assumed if you can write command line script, you may also export an environment variable.
takeshin