Posted By

IanLewis on 05/21/07


Tagged

http redirect


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

hudge
heinz1959


Redirect using absolute or relative paths


 / Published in: PHP
 

Parses the given path and creates a http redirect to that page.

  1. // func: redirect($to,$code=307)
  2. // spec: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
  3. function redirect($to,$code=301) {//{{{
  4. $location = null;
  5. $sn = $_SERVER['SCRIPT_NAME'];
  6. $cp = dirname($sn);
  7. if (substr($to,0,4)=='http') $location = $to; // Absolute URL
  8. else
  9. {
  10. $schema = $_SERVER['SERVER_PORT']=='443'?'https':'http';
  11. $host = strlen($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:$_SERVER['SERVER_NAME'];
  12. if (substr($to,0,1)=='/') $location = "$schema://$host$to";
  13. elseif (substr($to,0,1)=='.') // Relative Path
  14. {
  15. $location = "$schema://$host";
  16. $pu = parse_url($to);
  17. $cd = dirname($_SERVER['SCRIPT_FILENAME']).'/';
  18. $np = realpath($cd.$pu['path']);
  19. $np = str_replace($_SERVER['DOCUMENT_ROOT'],'',$np);
  20. $location.= $np;
  21. if ((isset($pu['query'])) && (strlen($pu['query'])>0)) $location.= '?'.$pu['query'];
  22. }
  23. }
  24.  
  25. $hs = headers_sent();
  26. if ($hs==false)
  27. {
  28. if ($code==301) header("301 Moved Permanently HTTP/1.1"); // Convert to GET
  29. elseif ($code==302) header("302 Found HTTP/1.1"); // Conform re-POST
  30. elseif ($code==303) header("303 See Other HTTP/1.1"); // dont cache, always use GET
  31. elseif ($code==304) header("304 Not Modified HTTP/1.1"); // use cache
  32. elseif ($code==305) header("305 Use Proxy HTTP/1.1");
  33. elseif ($code==306) header("306 Not Used HTTP/1.1");
  34. elseif ($code==307) header("307 Temorary Redirect HTTP/1.1");
  35. else trigger_error("Unhandled redirect() HTTP Code: $code",E_USER_ERROR);
  36. header("Location: $location");
  37. header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
  38. }
  39. elseif (($hs==true) || ($code==302) || ($code==303))
  40. {
  41. // todo: draw some javascript to redirect
  42. $cover_div_style = 'background-color: #ccc; height: 100%; left: 0px; position: absolute; top: 0px; width: 100%;';
  43. echo "<div style='$cover_div_style'>\n";
  44. $link_div_style = 'background-color: #fff; border: 2px solid #f00; left: 0px; margin: 5px; padding: 3px; ';
  45. $link_div_style.= 'position: absolute; text-align: center; top: 0px; width: 95%; z-index: 99;';
  46. echo "<div style='$link_div_style'>\n";
  47. echo "<p>Please See: <a href='$to'>".htmlspecialchars($location)."</a></p>\n";
  48. echo "</div>\n</div>\n";
  49. }
  50. exit(0);
  51. }//}}}

Report this snippet  

You need to login to post a comment.