Skip to content

Instantly share code, notes, and snippets.

@jasondmoss
Last active August 29, 2015 13:55
Show Gist options
  • Save jasondmoss/8766416 to your computer and use it in GitHub Desktop.
Save jasondmoss/8766416 to your computer and use it in GitHub Desktop.
Redirect to new location.
<?php
/**
* Browser Redirection.
*
* @param string $url Redirect destination.
* @param integer $code Redirect code.
*
* Codes:
*
* 301 - Moved Permanently
* 302 - Found
* 303 - See Other
* 307 - Temporary Redirect (HTTP/1.1)
*
* @see http://en.wikipedia.org/wiki/HTTP_303
*/
function redirection($url, $code = 302)
{
if (0 !== strncmp('cli', PHP_SAPI, 3)) {
if (true !== headers_sent()) {
// If using sessions.
if (strlen(session_id()) > 0) {
// Avoids session fixation attacks.
session_regenerate_id(true);
// Avoids having sessions lock other requests.
session_write_close();
}
if (0 === strncmp('cgi', PHP_SAPI, 3)) {
header(sprintf('Status: %03u', $code), true, $code);
}
header('Location: '. $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
}
exit();
}
}
$newUrl = 'http'. ((isset($_SERVER['HTTPS'])) ? 's' : '') .'://'. $_SERVER['SERVER_NAME'] .'/some-new-location/';
redirection($newUrl, 303);
/* <> */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment