session_start() related errors :)

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

session_start() related errors :)

Post by calumstevens »

So now im attempting to create a login, based on the username and password the visitor has signed up with.

Im getting the following error/s *deep breath*:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampplite\phpMyAdmin\login\loginaction.php:6) in C:\xampplite\phpMyAdmin\login\loginaction.php on line 9

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampplite\phpMyAdmin\login\loginaction.php:6) in C:\xampplite\phpMyAdmin\login\loginaction.php on line 9

Warning: Cannot modify header information - headers already sent by (output started at C:\xampplite\phpMyAdmin\login\loginaction.php:6) in C:\xampplite\phpMyAdmin\login\loginaction.php on line 31



Any help hugely appreciated :)

Code: Select all

<?php
	include "connection.php"
?>


<?php


session_start();
// (2) Collect data from form and save in variables

$appUsername = $_POST['username'];

$appPassword = $_POST['password'];



// (3) Create query to search the user table
$query = "SELECT * FROM users WHERE userName='$appUsername' AND  password='$appPassword'";

// (3) Run query through connection

$result = mysql_query ($query, $connection);

// (4) Check result of query using code below

// if rows found set authenticated user to the user name entered 
if (mysql_num_rows($result) > 0) { 
$_SESSION["authenticatedUser"] = $appUsername;
// Relocate to the logged-in page
header("Location: loggedon.php");
} 
else
// login failed redirect back to login page with error message
{
$_SESSION["message"] = "Could not connect as $appUsername " ;
header("Location: login.php");
}
?>
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Please search these boards for your problem. This has been brough up many times before. In fact, the guy that set these forums up to start wrote a tutorial on handling this.

In a nutshell, you are trying to send header information (using header(), setcookie() or session_start()) after output has been sent to the browser.
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

Bingo thanks for that! Really good tutorial - even I found it easy to follow.

Got past the header problems,

Now all appears to be working, apart from the fact that I get 'ERROR: Incorrect username or password!' regardless of the data I insert.

Any suggestions greatly appreciated, thanks in advance :)

Code: Select all

<?php
	include "connection.php"
?>



<?php 

if (isset($_POST['username']) || isset($_POST['password'])) { 
    // form submitted 
    // check for required values 
    if (empty($_POST['username'])) { 
        die ("ERROR: Please enter username!"); 
    } 
    if (empty($_POST['password'])) { 
        die ("ERROR: Please enter password!"); 
    } 

   

     
 
    // create query 
    $query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = SHA1('" . $_POST['password'] . "')"; 
     
    // execute query 
    $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); 
     
    // see if any rows were returned 
    if (mysql_num_rows($result) == 1) { 
        // if a row was returned 
        // authentication was successful 
        // create session and set cookie with username 
        session_start(); 
        $_SESSION['auth'] = 1; 
        setcookie("username", $_POST['username'], time()+(84600*30)); 
        echo "Access granted!"; 
    } 
    else { 
        // no result 
        // authentication failed 
        echo "ERROR: Incorrect username or password!"; 
    } 
     
    // free result set memory 
    mysql_free_result($result); 
     
    // close connection 
    mysql_close($connection); 
} 
else { 
    // no submission 
    // display login form 
?> 
    <html> 
    <head></head> 
    <body> 
    <center> 
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
    Username <input type="text" name="username" value="<?php echo $_COOKIE['username']; ?>"> 
    <p /> 
    Password <input type="password" name="password"> 
    <p /> 
    <input type="submit" name="submit" value="Log In"> 
    </center> 
    </body> 
    </html> 
<?php 
} 

?>
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Run that same query in your database admin tool (phpMyAdmin, MySQL query browser, SQLYog, etc) and see what is returned. Are you sure your passwords are hashed with SHA1 and not some other hashing algorithm?
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

aha! my passwords arent hashed at all currently :)

was just experimenting with the whole login concept xD! will fiddle with it some more and post the results hehe.

Regards
Calum
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

While you're working on it, make sure to hash your passwords. Just a security suggestion.
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

So after going over it again I realised I had missed that this was all one file, I was previously running a form.html posting to my loginaction.php.

I've changed that so this is all one file. I downloaded the sha-1.inc and put the file in the directory, Im not sure if thats all there is to it or not.

Im still getting the error username or password incorrect.

If I delete the Sha1 reference then I get the error:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampplite\phpMyAdmin\new\attempt.php:5) in C:\xampplite\phpMyAdmin\new\attempt.php on line 30

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampplite\phpMyAdmin\new\attempt.php:5) in C:\xampplite\phpMyAdmin\new\attempt.php on line 30

Warning: Cannot modify header information - headers already sent by (output started at C:\xampplite\phpMyAdmin\new\attempt.php:5) in C:\xampplite\phpMyAdmin\new\attempt.php on line 32
Access granted!

Which shows that everything is referenced correctly atleast, as it grants access at the bottom! But brings me right back to square one with the whole header thing. Any ideas? Heres my source with the Sha1 reference in tact, when I take that out I get the header errors. Thanks for your help thus far.

Code: Select all

<?php
	include "connection.php"
?>

<?php 

if (isset($_POST['username']) || isset($_POST['password'])) { 
    // form submitted 
    // check for required values 
    if (empty($_POST['username'])) { 
        die ("ERROR: Please enter username!"); 
    } 
    if (empty($_POST['password'])) { 
        die ("ERROR: Please enter password!"); 
    } 

  
     
    // create query 
    $query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = SHA1('" . $_POST['password'] . "')"; 
     
    // execute query 
    $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); 
     
    // see if any rows were returned 
    if (mysql_num_rows($result) == 1) { 
        // if a row was returned 
        // authentication was successful 
        // create session and set cookie with username 
        session_start(); 
        $_SESSION['auth'] = 1; 
        setcookie("username", $_POST['username'], time()+(84600*30)); 
        echo "Access granted!"; 
    } 
    else { 
        // no result 
        // authentication failed 
        echo "ERROR: Incorrect username or password!"; 
    } 
     
    // free result set memory 
    mysql_free_result($result); 
     
    // close connection 
    mysql_close($connection); 
} 
else { 
    // no submission 
    // display login form 
?> 
    <html> 
    <head></head> 
    <body> 
    <center> 
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
    Username <input type="text" name="username" value="<?php echo $_COOKIE['username']; ?>"> 
    <p /> 
    Password <input type="password" name="password"> 
    <p /> 
    <input type="submit" name="submit" value="Log In"> 
    </center> 
    </body> 
    </html> 
<?php 
} 

?>
Last edited by calumstevens on Wed Oct 25, 2006 8:23 am, edited 1 time in total.
TexasTip
Forum Newbie
Posts: 4
Joined: Wed Oct 25, 2006 7:35 am

Hash

Post by TexasTip »

I noticed you don't hash the password when you originally ask for it...So a query with the hash will not work.

I'm pretty new to this (about 6 months) and I'm not sure about everything, but I think you must hash before you enter the data into MySQL and hash when you extract it.
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

Makes sense, so to do that, would it look something like this?

Code: Select all

Password <input type="password" name=Sha1"password">
TexasTip
Forum Newbie
Posts: 4
Joined: Wed Oct 25, 2006 7:35 am

Password

Post by TexasTip »

Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Actually, I use this:

(A line off my form code)

Code: Select all

<tr><td><label for="password">Password</label></td><td><input type="password" id="password" name="password" /></td></tr>
Then in my php file, I force a check to see if it's empty:

Code: Select all

check_pass($password);
which looks at a function and I encrypt it:

Code: Select all

function check_pass($password) {
    global $val_pass;
    global $password;
    $password = ($_POST['password']);
      if ($password != ''){ 
        $password = md5($_POST['password']); 
            return true; 
    } else { 
        $val_pass = 'The password is invalid.';
            return false; 
    } 
}
I then add the encrypted password to the database

Code: Select all

$query = "INSERT INTO db VALUES('$email', '$password',    ...etc. )";
Yours will be different, but that's how I presently do it. My live code will put the $password variable into a databased $_SESSIONS file and not a global variable.


Everah | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

Realisation dawns, the reason im getting the invalid username/password error when i try to logon using the sha1 encryption is that the data in the databse isnt encrypted in the first place :)

So I need to encrypt the password when the user submits their registration details thus creating an account, and then retrive the encrypted password when they want to login.

Thanks alot for explaining that to me:)

Ok - so if i put encryption aside for the time being to come back to, I'd like to get the login working first of all.

At the moment Im still receiving this error message:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampplite\phpMyAdmin\new\attempt.php:5) in C:\xampplite\phpMyAdmin\new\attempt.php on line 30

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampplite\phpMyAdmin\new\attempt.php:5) in C:\xampplite\phpMyAdmin\new\attempt.php on line 30

Warning: Cannot modify header information - headers already sent by (output started at C:\xampplite\phpMyAdmin\new\attempt.php:5) in C:\xampplite\phpMyAdmin\new\attempt.php on line 32
Access granted!

The headers problem is still giving me a migrane, I've read through the relevent material, this code even comes from a tutorial on it :), so not sure whats going wrong hehe.

Any help appreciated.

Code: Select all

<?php
	include "connection.php"
?>

<?php 

if (isset($_POST['username']) || isset($_POST['password'])) { 
    // form submitted 
    // check for required values 
    if (empty($_POST['username'])) { 
        die ("ERROR: Please enter username!"); 
    } 
    if (empty($_POST['password'])) { 
        die ("ERROR: Please enter password!"); 
    } 

  
     
    // create query 
    $query = "SELECT * FROM users WHERE username = '" . $_POST['username'] . "' AND password = ('" . $_POST['password'] . "')"; 
     
    // execute query 
    $result = mysql_query($query) or die ("Error in query: $query. " . mysql_error()); 
     
    // see if any rows were returned 
    if (mysql_num_rows($result) == 1) { 
        // if a row was returned 
        // authentication was successful 
        // create session and set cookie with username 
        session_start(); 
        $_SESSION['auth'] = 1; 
        setcookie("username", $_POST['username'], time()+(84600*30)); 
        echo "Access granted!"; 
    } 
    else { 
        // no result 
        // authentication failed 
        echo "ERROR: Incorrect username or password!"; 
    } 
     
    // free result set memory 
    mysql_free_result($result); 
     
    // close connection 
    mysql_close($connection); 
} 
else { 
    // no submission 
    // display login form 
?> 
    <html> 
    <head></head> 
    <body> 
    <center> 
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> 
    Username <input type="text" name="username" value="<?php echo $_COOKIE['username']; ?>"> 
    <p /> 
    Password <input type="password" name="password"> 
    <p /> 
    <input type="submit" name="submit" value="Log In"> 
    </center> 
    </body> 
    </html> 
<?php 
} 

?>
TexasTip
Forum Newbie
Posts: 4
Joined: Wed Oct 25, 2006 7:35 am

Your code

Post by TexasTip »

Whew! I learned something about posting!

I would REM out the echo lines and try it again.

Also, what's in connection.php?
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

Update:

Ok then, I now have a working stripped down version, yay! It's a login form on a blank page, and its actually working in conjunction with my registration page :)

Code: Select all

<?php 
//Start - so we can use session variables 
session_start(); 
// Check if we have already created a authenticated session 
if (isset($_SESSION["authenticatedUser"])) 
{ 
    $_SESSION["message"] = "You are already logged in as ". $_SESSION['authenticatedUser']; 
    //Redirect to the login page 
     header("Location: admin.php"); 
       
} 
else 
{ 
  // No session established, no POST variables 
  //Display the login page 
?>   


    

  <?php 
  // Include the formatted error message 
   if (isset($_SESSION['message'])) 
    echo 
      "<h3><font color=red>".$_SESSION['message']."</font></h3>"; 

  // Generate the login <form> layout 
  ?> 
</p> 
   
 
      <form method="post" action="loginaction.php"> 
        

        
           User-name:
          <input type="text" size=10 
                   maxlength=10 
                   name="formUsername">
         
           Password:<
           <input type="password" size=10 
                   maxlength=10 
                   name="formPassword">
          
    
       
                <input name="submit" type="submit" value="Log in"> 
       
      </form>
  

  <?php 
} 

  ?>
Unfortunately when I attempt to put this working login system into my actual webpage, im back to the whole:

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at C:\xampplite\phpMyAdmin\new\edit.php:7) in C:\xampplite\phpMyAdmin\new\edit.php on line 165

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at C:\xampplite\phpMyAdmin\new\edit.php:7) in C:\xampplite\phpMyAdmin\new\edit.php on line 165

Heres my php inside my html:

Code: Select all

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
	<meta http-equiv="Content-Language" content="en-us" />
	<meta name="robots" content="all" />
	<meta name="author" content="Luka Cvrk (http://www.solucija.com)" />
	<meta name="Copyright" content="" />
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<link href="images/style.css" rel="stylesheet" type="text/css" />
	<title>Imperial-Base.com</title>
<SCRIPT language=JavaScript type=text/javascript>
<!--

if (document.images) {
	nav1on = new Image(); nav1on.src = "images/trooperhead.png";
	nav2on = new Image(); nav2on.src = "images/trooperarmleft.png";
	nav3on = new Image(); nav3on.src = "images/trooperarmright.png";
	nav4on = new Image(); nav4on.src = "images/trooperbody.png";
	nav5on = new Image(); nav5on.src = "images/trooperlegs.png";
	navoff = new Image(); navoff.src = "images/troopersized.png";
	
}

function rollOn(img1,img2,text){
	str = "window.status = '" + text + "'";
	if (document.all) setTimeout(str,5); // this is a hack to fix bug in IE on PC
    else window.status = text;
	if (document.images) {
		document.navs.src=eval(img1 + "on.src");
	
	}
}

function rollOff(){
    window.status = "";	
	if (document.images) {
		document.navs.src=navoff.src;
		
	}
}

//-->
</SCRIPT>

</head>

<body> 
	<div id="wrap">
		<div id="container"> 
			<div id="header">
				
      <p>&nbsp;</p>
			</div>
    	
			
    <div id="hmenu"> <a href="index.html">Home</a> <a href="products.html">Products</a> 
      <a href="contact.html">Contact</a> <a href="catalogue.html">Catalogue</a> 
      <a href="sitemap.php">Sitemap</a> <a href="login.html">Login/Register</a><a href="#"> 
      Blank</a> </div>
    	
      		<div id="left_column"> 
      			
    			
      <div id="menu"> <a href="index.html" accesskey="h" title="Accesskey: H"><span class="underline">H</span>OME<span class="white">Go 
        to homepage</span></a> <a href="products.html" accesskey="n" title="Accesskey: N"><span class="underline">PRODUCTS</span><span class="white"><font color="#FFFFFF">See 
        our Products</font></span></a> <a href="contact.html" accesskey="p" title="Accesskey: P"><span class="underline">CONTACT</span><span class="white"><font color="#FFFFFF">Contact 
        Us </font></span></a> <a href="catalogue.html" accesskey="s" title="Accesskey: S"><span class="underline">CATALOGUE</span><span class="white"><font color="#FFFFFF">Request 
        Catalogue </font></span></a> <a href="sitemap.php" accesskey="a" title="Accesskey: A"><span class="underline">SITEMAP</span><span class="white"><font color="#FFFFFF">View 
        our Sitemap</font></span></a> <a href="#" accesskey="c" title="Accesskey: C"><span class="underline">EMPTY</span><span class="white">Empty</span></a> 
     
<script language="JavaScript"> 

function openDir( form ) { 

	var newIndex = form.fieldname.selectedIndex; 

	if ( newIndex == 0 ) { 

		alert( "Please select a location!" ); 

	} else { 

		cururl = form.fieldname.options[ newIndex ].value; 

		window.location.assign( cururl ); 

	} 

} 

</script> 

 



<form name=form> 

	<tr> 

		<td nowrap> 

			<select name="fieldname" size="1" 

				onChange="openDir( this.form )"> 

				<option>Jump To </option> 

				<option value=index.html>Home</option> 

				<option value=products.html>Products</option> 
				
				<option value=contact.html>Contact</option>

				<option value=catalogue.html>Catalogue</option> 
			
				<option value=sitemap.php>Sitemap</option> 
  

			</select> 

		</td> 

	</tr> 

</form> 

 </div>
	<p>			
	<img src="images/troopersized.png" name=navs width=100 height=240 border=0 align="absmiddle" usemap="#map1">
                              <map name="map1">
                                <area shape="poly" coords="69,18,67,38,46,38,30,30,36,-7,33,9,55,-4,58,-1,65,4" href="#" target="_self" alt="head" 
  onMouseOver="rollOn('nav1','target1','head'); return true;" 
  onMouseOut="rollOff(); return true;" />
                                <area shape="poly" coords="29,38,68,40,71,47,73,66,70,100,29,100,28,56,26,51" href="#" target="_self" alt="body" 
  onMouseOver="rollOn('nav4','target4','body'); return true;" 
  onMouseOut="rollOff(); return true;" />
                                <area shape="poly" coords="67,109,93,238,63,238,61,195,49,136,38,182,32,237,3,237,10,204,24,126,35,111,49,129" href="#" target="_self" alt="trooperlegs" 
  onMouseOver="rollOn('nav5','target3','trooperlegs'); return true;" 
  onMouseOut="rollOff(); return true;" />
                                <area shape="poly" coords="29,28,26,46,25,64,19,70,22,79,20,130,20,87,12,133,-1,91,6,75,3,58,3,48,7,38,12,33" href="#" target="_self" alt="leftarm" 
  onMouseOver="rollOn('nav2','target2','leftarm'); return true;" 
  onMouseOut="rollOff(); return true;" />
                              <area shape="poly" coords="71,31,94,35,95,135,78,135" href="#" target="_self" alt="rightarm" 
  onMouseOver="rollOn('nav3','target2','rightarm'); return true;" 
  onMouseOut="rollOff(); return true;" />



                          </map>			
      </p>
				</div> 
			
			<div id="right_column">
				
      <div class="main_article"> 
        <h3>Sitemap<span class="red"></span></h3> 


                    </p>
<?php 
//Start - so we can use session variables 
session_start(); 
// Check if we have already created a authenticated session 
if (isset($_SESSION["authenticatedUser"])) 
{ 
    $_SESSION["message"] = "You are already logged in as ". $_SESSION['authenticatedUser']; 
    //Redirect to the login page 
     header("Location: admin.php"); 
       
} 
else 
{ 
  // No session established, no POST variables 
  //Display the login page 
?>   


    

  <?php 
  // Include the formatted error message 
   if (isset($_SESSION['message'])) 
    echo 
      "<h3><font color=red>".$_SESSION['message']."</font></h3>"; 

  // Generate the login <form> layout 
  ?> 
</p> 
   
 
      <form method="post" action="loginaction.php"> 
        

        
           User-name:
          <input type="text" size=10 
                   maxlength=10 
                   name="formUsername">
         
           Password:<
           <input type="password" size=10 
                   maxlength=10 
                   name="formPassword">
          
    
       
                <input name="submit" type="submit" value="Log in"> 
       
      </form>
  

  <?php 
} 

  ?> 



      				
        <p>&nbsp;</p>
        <p>&nbsp; </p>
      </div>
      </div>
  </div>
  <div id="footer"> <a href="contact.html">Contact</a> - <a href="copyright.html" target="_blank">Copyright</a> - <a href="privacy.html" target="_blank">Privacy 
    and Accessibility</a></div>
</div>
</body>
</html>
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

calumstevens wrote:The headers problem is still giving me a migrane, I've read through the relevent material, this code even comes from a tutorial on it :), so not sure whats going wrong hehe.
This topic has been extensively covered on these boards (and others as well). Sessions use cookies. Cookies send HTTP Response headers, but they cannot send header information if the headers have already been sent, which takes place as soon as something is output to the user agent (your browser). The error you are getting is PHP's way of telling you that you are trying to send headers (most commonly associated with the header(), setcookie() and session_start() functions) after your code has already output something to the browser.
calumstevens
Forum Commoner
Posts: 25
Joined: Mon Oct 23, 2006 5:16 am

Post by calumstevens »

im not sure what REM out means texas :)

And this is my connection.php, simply points at my database, and yes I know it's not passworded :P

Code: Select all

<?php
	$connection = mysql_connect("localhost", "root", "") or die(mysql_error());
	mysql_select_db("test", $connection) or die(mysql_error());
?>

Everah, "they cannot send header information if the headers have already been sent, which takes place as soon as something is output to the user agent (your browser)."

Is that only from php? Which is what I thought initially. But now that I had a working login until I attempted to add it into my pre existing site, I have a feeling it includes html also?
Post Reply