Welcome Guest, Not a member yet? Register   Sign In
$routes->addRedirect with regex?
#6

I have added this function to my BaseController class. It's simpler than the CI3 function in a few ways, but works for apache 2.4.41.
PHP Code:
        /**
         * CI4 lacks a redirect() function, and its recommended redirect approach does not work
         * in either __construct or initController functions, so I've added this, loosely based on
         * the CI3 redirect() function but some differences: doesn't bother using site_url for force FQDN
         * uri, cannot specify redirect method, doesn't use 307 for non-GET requests unless you explicitly specify
         * that code via parameter, doesn't allow empty uri param, only uses location header, no refresh method
         * 
         * @param string $uri
         * @param int $code
         */
        
public function redirect($uri$code NULL)
        {
            if (!
$uri) {
                throw new \
Exception("You must specify a non-empty uri");
            }
            if (!
is_null($code) && !is_int($code)) {
                throw new \
Exception("If you specify an HTTP code, value must be an integer");
            }
            
            if (!
$code)
            {
                
// default code to 302
                
$code 302;
                
                
// upgrade code to 303 if HTTP/1.1 or greater
                
$matches NULL;
                if (isset(
$_SERVER['SERVER_PROTOCOL'], $_SERVER['REQUEST_METHOD']) && preg_match('#^HTTP/([0-9\.]+)$#i'$_SERVER['SERVER_PROTOCOL'], $matches))
                {
                    
// HTTP/1.1 introduced more specific redirect response codes
                    
$version = isset($matches[1]) ? $matches[1] : "1.0";
                    if (
version_compare($version"1.1"">="))
                    {
                        
$code 303;
                    }
                }
            }

            
header('Location: ' $uriTRUE$code);
            exit;
        } 
Reply


Messages In This Thread
$routes->addRedirect with regex? - by sneakyimp - 02-10-2021, 05:31 PM
RE: $routes->addRedirect with regex? - by iRedds - 02-11-2021, 03:37 AM
RE: $routes->addRedirect with regex? - by iRedds - 02-11-2021, 11:36 PM
RE: $routes->addRedirect with regex? - by sneakyimp - 02-15-2021, 01:46 PM



Theme © iAndrew 2016 - Forum software by © MyBB