What is the difference between redirect() and header() in CI4?
Why Interviewers Ask This
This tests whether you can apply CodeIgniter knowledge to real-world scenarios. Interviewers are looking for clarity of thought and evidence that you've encountered this in production code.
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.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your CodeIgniter experience.
Previous
What is CodeIgniter 4's Encryption class?
Next
What is CodeIgniter's Active Record (Query Builder) advantages?