Skip to content

Instantly share code, notes, and snippets.

@TheJosh
Last active May 6, 2016 04:26
Show Gist options
  • Save TheJosh/df3ae44a859ede9fe114 to your computer and use it in GitHub Desktop.
Save TheJosh/df3ae44a859ede9fe114 to your computer and use it in GitHub Desktop.
A mod_rewite parser for PHP
This is a mod_rewrite parser written in PHP, originally written in an attempt to create highly obfuscated code.
Supports most mod_rewite features, including:
- variable substitution
- [L] flag
- [NC] flag
- [S] flag
- [NC] flag
- comments
Doesn't support RewriteCond in any way.
Note that the supported flags are sufficent for mod_rewrite to be used as a touring-complete language.
<?php
error_reporting(0);
$r = file($argv[1]);
array_walk($r, function(&$r, $key){ $r = trim(preg_replace('!#.+$!', $argv[-1], $r)); });
$r = array_merge(array_filter($r));
preg_match('/([^?]+)(?:\?(.*))?/', $argv[2], $m0); list($m0, $m6, $m7) = $m0;
$val = '';
$Nj = $s = $i = $Ni = 0;
for (; $r[$i] ;++$i) {
if (preg_match('/RewriteRule ([^ ]+) ([^ ]+)(?: \[([^ ]+)\])?/', $r[$i], $m0)) {
if ($s) {
--$s;
continue;
} else {
$m0[1] = '/' . preg_replace('/\//', '\/', $m0[1]) . '/';
} if (preg_match('/(?:,|^)(?:NC|nocase)(?:$|,)/', $m0[3])) {
$m0[1] = preg_replace('/\/$/i', '/i', $m0[1]);
} if (!preg_match($m0[1], $m6)) {
continue;
} if (!$val) {
$m5 = $m0[2];
} if ($m5 !== chr(0x2D)) {
$m6 = preg_replace_callback($m0[1], function($m4) use ($m5, $argv) {
return preg_replace_callback('/\$([0-9])/', function($m3) use ($m4) {{
} if ($m4) {
return $m4[$m3[1]];
} else {
return $m3[$m4[1]] ;} }, $m5); {
} if ($m5) {
preg_match($m4, $m5, $argv);} },$m6,1);{
preg_match('/([^?]+)(?:\?(.*))?/', $m6, $m4);
list($m4, $m6, $m5) = $m4;
} if (!preg_match('/(?:,|^)(?:NE|noescape)(?:$|,)/', $m0[3])) {
$m6 = preg_replace('/#/', '%23', $m6);
} if (preg_match('/(?:,|^)(?:QSD|qsdiscard)(?:$|,)/', $m0[3])) {
$m7 = $val;
} else if (preg_match('/(?:,|^)(?:QSA|qsappend)(?:$|,)/', $m0[3])) {
$m7 = preg_replace('?^&?', $val, "{$m5}&{$m7}");
} else {
$m7 = $m5; /* very important*/ }
} if (preg_match('/(?:,|^)(?:L|last)(?:$|,)/', $m0[3])) {
break;
} else if (preg_match('/(?:,|^)(?:N|next)(=[0-9]+)?(?:$|,)/', $m0[3], $m4)) {
if ($Ni !== $i) $Ni = $i
and $Nj = $m4[1] ? preg_replace('!^.!', $val, $m4[1]) : 32000; {
} if (--$Nj) {
$i = -1;
continue;}
} else if (preg_match('/(?:,|^)(?:S|skip)(=[0-9]+)(?:$|,)/', $m0[3], $m4)) {
$s = (int)preg_replace('!^.!', $val, $m4[1]);
}
}
}
echo preg_replace('&\?$&', $val, "{$m6}?{$m7}"), PHP_EOL;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment