Link to home
Start Free TrialLog in
Avatar of Roccat
RoccatFlag for United States of America

asked on

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();
 }
 ?>
SOLUTION
Avatar of David Favor
David Favor
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Roccat

ASKER

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.
Avatar of Jeremy Weisinger
Jeremy Weisinger

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

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Roccat

ASKER

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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Roccat

ASKER

Thanks
Avatar of Roccat

ASKER

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
}
Glad to help. Thanks for sharing your script. :)