What is the difference between redirect() and header() in CI4?
Answer
In CodeIgniter 4, redirect() is the recommended way to perform redirects. It returns a RedirectResponse object: return redirect()->to("https://example.com") or return redirect()->route("users.index"). Pass flash messages: return redirect()->to("/dashboard")->with("success", "Logged in!"). Redirect with old input: return redirect()->back()->withInput(). The redirect() function uses a 302 HTTP status code by default; change with: redirect()->to($url, 301). Using PHP's raw header("Location: $url"); exit bypasses CI4's response object and should be avoided — CI4's redirect properly flushes the response buffer, handles headers already sent, and integrates with the framework's response pipeline. Always return the redirect response from controller methods.
Previous
What is CodeIgniter 4's Encryption class?
Next
What is CodeIgniter's Active Record (Query Builder) advantages?