Recently at work, the web admin for the computer science department came into our lab and told us that my employer’s site was broken. The admin had need to make all .php files not act as PHP scripts, and instead, all files with the extension .sphp would now run as PHP scripts. Since my employer’s site was built using PHP, that meant all of its pages were showing the source code instead of actually executing. I had to whip up a quick Ruby script in order to:

  1. Rename all .php files to have .sphp as their extension;

  2. Replace all instances of “.php” within those files with “.sphp”, to take care of include statements, links, etc.

Here’s what I came up with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/usr/bin/env ruby
require 'find'
require 'fileutils'

# Used to go through, starting at the directory start_dir and working
# recursively, and rename all files that end in .php to end in .sphp
# because the CS admin got a wild hair.  Also goes through all .php
# and .sphp files and replaces all instances of ".php" in them with
# ".sphp".
def finder( start_dir )
  Find.find( start_dir ) do |path|
    if FileTest.file?( path )
      if path =~ /\.php$/i
        old_name = File.basename( path )
        new_name = old_name.gsub( /\.php$/, '.sphp' )
        dir = path.gsub( /#{old_name}$/, '' )

        if File.exists?( dir + old_name )
          puts "#{dir + old_name} to #{dir + new_name}\n"

          # Since the code is part of a Subversion repository, we use
          # the 'svn' command to let Subversion rename the file
          system( "svn mv #{dir + old_name} #{dir + new_name}" )
        end
      elsif path =~ /\.sphp$/i || path =~ /\.php$/i
        puts "Replacing instances of '.php' in #{path}\n"
        system( %Q{ruby -pe 'gsub(/\\.php/, ".sphp")' -i #{path} } )
      end
    end
  end
end

finder( '.' )