Computer Programming web Web programming Tips



Cannot modify header information headers already sent-PHP user authentication.

By Sergey Skudaev

$_COOKIE[]

Let us try to use $_COOKIE[ ] variable.

Edit form_methods.php and add the following piece of code. The cookie´s code must be inserted before HTML header. Other wise you will get error! The setcookie function will set $pref variable to $_COOKIE[] variable.


<?

$pref="Mrs"; setcookie("prefix",$pref); ?> <html> <head> <title>Form Methods </title> </head> <body> <form method="post" action="formoutputpage.php"> <p><input type=text name=greeting size="15"></p> <p><input type=text name=name size="15"></p> <p><input type=submit name=submit value="Salutation"></p> </form> </body> </html>

Once, I was writing a PHP user authentication script and run into the same problem. My login file included connect.inc file and down the login.php file I used cookies to store a user name, password and a role. I knew that when I call setcookie() function, a header is sent. I knew that, a header is sent also when page has any ouput.

My connect.inc file did not have any output, and '<?' tag started right away from the top of the page and there was no space characters I was aware of, however, I kept getting messages: Cannot modify header information - headers already sent by...connect.inc"

The connect.inc file contained only access parameters to mysql database.

<?php
$hostname = "localhost";
$dbuser = "mydomain_user";
$dbpassword = "Password";
$dbname = "mydomain_db";
?>




My login.php file was like that:

<?php

include(´../connect.inc´)

//data comes from login form when user enters login and password
 $username = $_POST['username'];
 $password = $_POST['password'];

//encript password:
$password=md5($password);

$num=0;

   $auth = false; // Assume user is not authenticated yet
   //Check if login and password are not empty
if (isset( $username ) && isset($password))
{
   //Connect to MySQL
   mysql_connect( $hostname, $dbuser, $dbpassword)
   or die ( ´Unable to connect to server. (login)´ );
   mysql_select_db($dbname )
   or die (´Unable to select database.(login)´);

   //for Cyrillic characters (I had russian web site)
   mysql_query("SET NAMES ´cp1251´");
   // Check if username and password exist in the database 
   //and if the user is activated.
 $sql = "SELECT username, password, role FROM usernames WHERE
   username = ´".$username."´ and
   password = ´".$password."´ and active=1";

 $result = mysql_query( $sql ) or die ( ´Unable to execute query.´ );
   $num = mysql_numrows( $result );
   if ( $num == 1 )
   {
   $auth = true;
   $row=mysql_fetch_row($result);
  $auser=$row[0];
  $apassword=$row[1];
  $arole=$row[2];
  setcookie("user",$auser);
  setcookie("role",$arole);
  setcookie("password", $apassword);
   }


if (!$auth)
{ //Check if user exists but not active, then send email to the user.
$asql = "SELECT active, email FROM usernames WHERE username = '".$username."' AND password = '".$password."'";

 $aresult = mysql_query( $asql )  or die
  ( "Unable to execute query.");

 if(mysql_numrows( $aresult ))
 {
  $arow=mysql_fetch_row($aresult);
  $active=$arow[0];
  $email=$arow[1];

  if($active == 0)
  { //Preparation parameters for mail function.
   $subject = 'User Activation';
   $headers  = 'MIME-Version: 1.0' . "\r\n";
   $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
   $headers .='From: webmaster@mydomain.com' . "\r\n";
   $parameter='-fwebmaster@mydomain.com';

$message =´Click this link to activate your account<br/>´;
$message.=´http://www.mydomain.com/activate.php?username=´.$username;
   //You must wrap message text for mail.
   $message = wordwrap($message, 70);
   mail($email, $subject, $message, $headers, $parameter);
$activatemessage="Your account is not active. Please check your email and activate your account.";
   setcookie("msg",$activatemessage);
   header("Location:sign_in.php");
   }
 }
 else
 {
   $loginmessage="Your login or password is not correct!";
    setcookie("msg",$loginmessage);
   header("Location:sign_in.php");
 }
   }
   else //if no aresult
   {
   setcookie("msg","");
   header("Location:display_mypprofile.php");
   }
}
else  //if username and password are not set
{
$nodata="Please enter username and password!";
setcookie("msg",$nodata);
header("Location:sign_in.php");
}
?>




When I tested my login script, I was getting this famous message "Cannot modify header information - headers already sent by connect,inc file. I looked at my connect.inc file content and could not undestant what could be wrong with such a simple file?

<?php
$hostname = "localhost";
$dbuser = "mydomain_user";
$dbpassword = "Password";
$dbname = "mydomain_db";
?>

I searched internet, read forum posts, but could not find the exact answer. Then I opened the file in notepad, placed my mouse cursor on the last record in the file and started to press -> key on my keyboard. To my surprise, I discovered that my cursor was moved beyond the ?> tag and all the way to the end of the line. I deleted space characters after ?> tag, save the file, uploaded it and message disappeared!

Check also if you have space characters before <?php tag. And of cause you should not have any echo or print commands or calls to seccion function.

Email account must be set on your server to send email to the user. User activation code via email will be provided on the next page.

My eBooks on Amazon.com



Subscribe to our mail list to receive free code examples.

Comments

No comments yet.

Add Comment

* Required information
(never displayed)
 
Smile Sad Huh Laugh Mad Tongue Crying Grin Wink Scared Cool Sleep Blush Unsure Shocked
 
1000
Enter the fifth word of this sentence.
 
Enter answer:
Captcha
Refresh
 
Enter code:
 
Notify me of new comments via email.
 
Remember my form inputs on this computer.
 
I have read and understand the privacy policy. *
 
I have read and agree to the terms and conditions. *
 
 
Powered by Commentics