I recently implemented a pretty cool code-viewer for this site. You can see it in action here, or by suffixing any JavaScript file with ‘/view’. It works on absolutely any ‘js’ file on this domain as long as it ends in the conventional ‘js’ extension.
To achieve this I had to specify a rule to rewrite all URLs ending in ‘.js/view’:
# Within the .htaccess file: <IfModule mod_rewrite.c> RewriteEngine On RewriteRule ^(.+.js)/view$ /utils/codeview.php?loc=/$1 </IfModule> |
Behind the scenes, all URLs that fit the schema are rewritten and the ‘codeview.php’ script is requested for each. This script grabs the contents of the JS file (passed as ‘loc’ in the query string) abd runs it through GesHi to get some neat looking syntax highlighting:
include_once('geshi/geshi.php'); if (!isset($_GET['loc']) || substr($_GET['loc'], -3) != '.js') { die('You have not specified a real JavaScript file'); } $location = $_GET['loc']; $source = file_get_contents($_SERVER['DOCUMENT_ROOT'].$location); $geshi = new GeSHi($source, 'javascript'); // Further down in the <body>: echo $geshi->parse_code(); |
So, from now on, if you ever want to have a quick scan through the source of any of my scripts or plugins you can just suffix the location with ‘/view’!
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Nicely done. GeSHi is a wonder piece of software. I’ve used it before in a similar vein.
I would clean $_GET[‘loc’]. 😉
@James, yep, GesHi is awesome! I did consider using something like SyntaxHighlighter or Prettify but I really wanted something server-side plus I’d heard a lot of good things about GeSHi…
@Vasili, In what way does it need cleaning? The contents of the parameter is not echoed or added to a database so I don’t see any security issues.
That is awesome James.
Thanks very much!
@James Cleaning probably isn’t required, I just do it with every variable I receive. I get so paranoid. 😛
Looks great but you might want to change the regexp in the .htaccess file to allow trailing slashes… eg “^(.+.js)/view/?$”
@Rick, thanks for the tip, just changed it. 🙂
No problem… it’d only help people like myself who instinctively put a trailing slash on anything that looks like a directory.
Awesome works James. I suggest add another parameter “url”
codeview.php?url=http://jquery.offput.ca/js/jquery.bgColor.js
what u think?
Awesome idea! And thanks for sharing the code! 🙂