Posted By

mladoux on 09/21/10


Tagged

php uri rewriting


Versions (?)

URI Parser 3.1


 / Published in: PHP
 

URL: http://mark.haktstudios.com/

URI Parser 3.1

New and improved URI parser for URI renaming. Converts URI segments into usable PHP variables. Read comments for usage instructions. ( corrected small error in script )

  1. // place the following code into your index.php
  2.  
  3. define('SELF', 'index.php');
  4. define('PATH', str_replace(SELF, '', __FILE__));
  5. define('URI', str_replace(SELF, '', $_SERVER['SCRIPT_NAME']));
  6.  
  7. function seg($n)
  8. {
  9. if( $n < 1 ) return false; // prevent starting from 0
  10. // prep working vars
  11. $base_uri = explode('/', URI);
  12. $req_uri = $_SERVER['REQUEST_URI'];
  13. // $n = $n--; // doesn't perform correctly
  14. $n--;
  15.  
  16. // clean up request uri
  17. if(! file_exists(PATH.'.htaccess')) $req_uri = preg_replace('/'.SELF.'/', '', $req_uri, 1);
  18. foreach($base_uri as $base) $req_uri = preg_replace("/{$base}/", '', $req_uri, 1);
  19.  
  20. // create a clean array to work from
  21. $req_uri = array_merge(array(), array_filter(explode('/', $req_uri)));
  22.  
  23. // determine if seg is set or not
  24. $seg = (isset($req_uri[$n])) ? $req_uri[$n] : false;
  25.  
  26. // filter bad seg
  27. if( $seg === false || // $seg not set
  28. $seg[0] == "?" || // $seg is a query string
  29. $seg[0] == "#" || // $seg is an html anchor
  30. $seg[0] == "." // $seg starts with a '.'
  31. ) return false;
  32.  
  33. // clean out unwanted crap trailing on the end of the string
  34. $seg = reset(explode(".", $seg)); // file extension filter<code>ing
  35. $seg = reset(explode("?", $seg)); // query string filtering
  36. $seg = reset(explode("#", $seg)); // html anchor filtering
  37.  
  38. // return a safe string for processing
  39. return htmlspecialchars($seg, ENT_QUOTES);
  40. }

Report this snippet  

You need to login to post a comment.