script to instert text at the begining of every php file in a directory

Roccat
Roccat used Ask the Experts™
on
Can you help me get started with writing a script that will insert text at the very top of ever php file in a directory? This is what I need.
<?php
if (!isset($_SESSION)){
 session_start();
 }
 ?>
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
David FavorFractional CTO
Distinguished Expert 2018
Commented:
This will be a bit tricky, as you have to manage interrupts (block/ignore) FPM or Apache restarts/reloads, while you have a file open.

General logic...

1) Setup interrupt handler to tell you when an interrupt is pending, by incrementing a global $interrupt variable...

2) Open tmp file in same directory.

3) Write preamble text to top of tmp file + then append old file to tmp file.

4) Then delete old file.

5) Rename tmp file to old file name.

6) If isset($interrupt) stop

7) Rinse + Repeat for all files in a directory.

As you can see if an interrupt stops processing anywhere in step 2-5, you can end up with a tmp file + no real file or tmp file accumulation.

Biggest issue with this type of logic is ensuring you only process interrupts on your terms, rather than when the interrupt occurs.

If this is your first time with code like this, you might consider opening a Gig + seeing how someone else approaches this.
Commented:
Is it safe to assume that this is just a one-time change to these files and that they're not in active production use?

You might want to consider updating all the files to have a single line like:
include("header.inc");

And then put your session start code into that header file. That way, if you need to make any more changes to that logic in the future, you just need to update the header file and everything else will automatically get it n

Author

Commented:
Somehting like this is what I was thinking in powershell

Get-ChildItem "C:\Backup1" -Filter *.php | Foreach-Object {
Add-Content -path $_ (Get-Content "C:\Scripts\code.txt")
}

Just trying to get it to work now.
Why Diversity in Tech Matters

Kesha Williams, certified professional and software developer, explores the imbalance of diversity in the world of technology -- especially when it comes to hiring women. She showcases ways she's making a difference through the Colors of STEM program.

Jeremy WeisingerSenior Network Consultant / Engineer

Commented:
Please test this as I have not but something like this might work:

$phpstr = @"
<?php
if (!isset($_SESSION)){
 session_start();
 }
 ?>
"@

Get-ChildItem "C:\Backup1" -Filter *.php | Foreach-Object {
    $content = Get-Content $_
    $phpstr | Set-Content $_ -Force
    $content | Add-Content -path $_ 
}

Open in new window

Commented:
If you want a simple PHP script to do the work and be semi-smart about it so that it doesn't add things twice if you run it twice:
<?php
process("C:/path/to/folder");

function process($folder, $recurse = true)
{
  // Open the folder and start looping through it
  $subdirs = array();
  $dh = opendir($folder);
  while(($file = readdir($dh)) !== false)
  {
    if(($file == ".") || ($file == "..")) { continue; } // Skip the . and .. special dirs
    $fullfile = $folder . "/" . $file; // Get the full file path
    if(is_dir($fullfile))
    {
      // Keep tabs on subdirs for recursing
      if($recurse)
      {
        $subdirs[] = $fullfile;
      }
    }
    else
    {
      // Read in the original file
      $contents = file_get_contents($fullfile);
      
      /*************************************************
       * HERE IS WHERE YOU MAKE THE CHANGES TO THE FILE
       *************************************************/
      
      $textToAdd = "<"."?php\n".
      "session_start();\n".
      "?".">";
      
      // Don't add to the file if we've already added it before
      if(strpos($contents,$textToAdd) === 0)
      {
        // Skip to next file
        continue;
      }
      
      // Prepend the content and save the file
      file_put_contents($fullfile,$textToAdd . $contents);

      /*************************************************
       * END OF THE FILE-HANDLING SECTION
       *************************************************/
    }
  }
  closedir($dh);
  
  // Handle optional recursion
  foreach($subdirs as $subdir) { process($subdir); }
}

Open in new window


Again, I recommend using an include() with a header for better future management of your code, but the above example uses the "session_start()" content for now.

Also, you don't need the "if (!isset($_SESSION)){" check - the session_start() will handle all of that stuff automatically.

Author

Commented:
Jeremy that script is similar to mine but I think the reason it does not work is because in this line "$content | Add-Content -path $_ " the $_ does not contain the path. It just conaitns the name of the file.
Senior Network Consultant / Engineer
Commented:
Ah yes.
$phpstr = @"
<?php
if (!isset($_SESSION)){
 session_start();
 }
 ?>
"@

Get-ChildItem "C:\Backup1" -Filter *.php | Foreach-Object {
    $content = Get-Content $_
    Set-Content $_ -Force -Value $phpstr
    Add-Content $_  -Value $content
}

Open in new window

Author

Commented:
Thanks

Author

Commented:
Here is the final script that I used.  
$phpstr = get-content "C:\Scripts\code.txt"
Get-ChildItem "C:\htdocs" -recurse -Filter *.php | Foreach-Object {
    $content = Get-Content $_.FullName
    $phpstr | Set-Content $_.fullname
    $content | Add-Content -path $_.fullname
}
Jeremy WeisingerSenior Network Consultant / Engineer

Commented:
Glad to help. Thanks for sharing your script. :)

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial