Note: If you enjoy this article, you might also check out the Geeky Stuff section.
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:
- Rename all .php files to have .sphp as their extension;
- Replace all instances of ".php" within those files with ".sphp", to take care of
includestatements, links, etc.
Here's what I came up with:
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( '.' )
That looks so fun. I’d love to learn Ruby except… My server doesn’t support it. :(