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

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();
 }
 ?>
RoccatAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

David FavorLinux/LXD/WordPress/Hosting SavantCommented:
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.
1
gr8gonzoConsultantCommented:
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
3
RoccatAuthor 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.
0
Redefine Your Security with AI & Machine Learning

The implications of AI and machine learning in cyber security are massive and constantly growing, creating both efficiencies and new challenges across the board. Check out our on-demand webinar to learn more about how AI can help your organization!

Jeremy WeisingerSenior Network Consultant / EngineerCommented:
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

1
gr8gonzoConsultantCommented:
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.
1
RoccatAuthor 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.
0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
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

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RoccatAuthor Commented:
Thanks
0
RoccatAuthor 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
}
0
Jeremy WeisingerSenior Network Consultant / EngineerCommented:
Glad to help. Thanks for sharing your script. :)
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.