需要在每个PHP文件的开头添加单行吗?

Wondering if there's a quick way to recursively find every file ending in .php and add this line at the beginning..

<? $DOCUMENT_ROOT = '/usr/share/nginx/html';?>

Have tried register_globals etc and no ball so this looks like the easiest way.

Any ideas?

$path = "somedir/";    

$directory = new RecursiveDirectoryIterator($path);
$iterator  = new RecursiveIteratorIterator($directory);
$regex     = new RegexIterator($iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH);

foreach($regex as $file) { 
    $file     = $file[0];       
    $contents = 
        "<?php $DOCUMENT_ROOT = '/usr/share/nginx/html';?>
" 
        . file_get_contents($file);    

    file_put_contents($file, $contents);        
}

I have no idea how it will perform for lots of files, use wisely. By the way, you should avoid the short open tag and always use <?php.


I've answered the question before it was updated to include "<?php $DOCUMENT_ROOT = '/usr/share/nginx/html';?> " as the line needed in every file. It's a bad idea, as @DanRay commented:

You don't want to hard-code this value in the top of every file. You want to add a reference to a single config file where it's set. I know it's unlikely to change, but it's a configuration value, and configuration values should be kept in one place, not splattered throughout your codebase.


Alternative implementation without RegexIterator:

$path = "somedir/";    

$directory = new RecursiveDirectoryIterator($path);
$iterator  = new RecursiveIteratorIterator($directory);

foreach($iterator as $file) {
    $path = $file->getRealPath();

    if(
        !$file->isFile()
        || !preg_match('/^.+\.php$/i', $path)
    ) {
        continue;
    }

    $contents = 
        "<? $DOCUMENT_ROOT = '/usr/share/nginx/html';?>
" 
        . file_get_contents($path);    

    file_put_contents($path, $contents); 
}

With PHP 4.2.3+ you could simply use the PHP directive auto_prepend_file.

For example in your php.ini:

auto_prepend_file = /var/www/html/myproject/myprepend.php

Another possibility would be to use the directive in .htaccess files:

php_value auto_prepend_file /var/www/html/myproject/myprepend.php

where /var/www/html/myproject/myprepend.php (or whatever path you use) just contains

<?php
$DOCUMENT_ROOT = '/usr/share/nginx/html';