I am trying to create a simple login system in WordPress using core PHP but I am getting this error message

Warning: Cannot modify header information - headers already sent by (output started at /www/www/www/wp-content/themes/mytheme/header.php:20) in /www/www/www/wp-content/themes/mytheme/page-solutions.php on line 9

In the header.php template I have

 * The header.
<!doctype html>
<html lang="en">

and in the page-solutions.php page

 * Template Name: Solutions

if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: home");

As you can see I am trying to redirect not logged users to front-page.php which I called it Home but I am getting error on header("location: home"); Can you please let me know how to fix this?

1 Answer 1


header can't be used once the headers have been sent, the moment you output anything such as a tag, or even a blank space, PHP will send out the headers telling the browser to expect a HTML document.

In order to send a HTTP header to redirect, you need to do it before this happens. This means you cannot do this after get_header() is called, you have to do it before that call, and before any other HTML output. Generally, this is not something that works well inside templates.

Other notes:

  • you should be using the WordPress function to do this wp_safe_redirect
  • if you're redirecting to the homepage you shouldn't be using home, pass /home to go to example.com/home or use home_url() instead to retrieve the URL of the homepage
  • PHP sessions will not work on many WordPress hosts, and there are major security issues that require special handling. They're also incompatible with many caching systems. You also can't use it to bypass cookie legislation as PHP sessions use a cookie to identify which session belongs to the visitor. So use cookie based logins instead.
  • You should use the built in user management instead of reinventing it
  • Thanks a lost for perfect comment Tom, So by using the built in user management can I give access of viewing the front pages? I do not want users have access to admin panel but able to see secured front pages?
    – Suffii
    Commented Jun 16, 2022 at 16:25
  • that's possible but would be a separate independent question. If this answer answers your question consider marking it as the correct answer using the check button underneath the voting arrows
    – Tom J Nowell
    Commented Jun 16, 2022 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.