Jump to content

Check Login Process/Error


justlukeyou

Recommended Posts

  • Replies 71
  • Created
  • Last Reply

Top Posters In This Topic

So a header is the location someone goes to when they login?

 

No.  The header function sends an HTTP header to the client.  The header can do multiple things (as the example code in the documentation illustrates).  Among them, it can send the client to another resource (that's what 'Location: blah' does), it can set the HTTP status (like 500 for an internal server error, 404 not found, etc.), and other things as well.

 

HTTP stands for HyperText Transfer Protocol.  It's the primary protocol of the web, and essentially describes the format and behavior of messages sent and received by the client and server.  HTTP headers are the beginning of those messages, and tell whichever thing (client or server) how to handle the rest of the message.

Link to comment
Share on other sites

I have set up the registration which enables people to create a profile.  I am now trying create a login test page but I am struggling with the header.

 

I know the following code reads the database because if I enter a false name or password it returns the message "The username or password was incorrect."  However if I enter the correct name and password I dont seem to be getting anywhere.  I get this session_start() [function.session-start]: Cannot send session cookie - headers already sent

 

Is there something specific I need to do such as placing the login code at the top of the page or does the header need to be centralised on the homepage.

 

NO HTML HERE

 

<?php

   if(!$ses_user && !$ses_pass){
      echo "You need to be logged in to view this page.";
   }


?>

 

HTML HERE

 

<?php
    if(!$ses_user && !$ses_pass){
        if($_POST["submit"]){
            $u = $_POST["firstname"];
            $p = $_POST["password"];
            
            if(!$u && !$p){
                $msg = "<p>The login form is empty. Try again.</p>";
            }
            else{
                if(!$u){
                    $msg .= "<p>The username is empty. Try again.</p>";
                }
                else{
                    if(!$p){
                        $msg .= "<p>The password is empty. Try again.</p>";
                    }
                    else{
                        
                        $log = mysql_query("SELECT * FROM organisermembers WHERE firstname = '$u' AND password = '$p'");
                        
                        $check = mysql_fetch_assoc($log);
                        
                        $u_check = $check["firstname"];
                        $p_check = $check["password"];
                        
                        if($u != $u_check && $p != $p_check){
                            $msg .= "<p>The username or password was incorrect.</p>";
                        }
                        
                        if($u === $u_check && $p === $p_check){
                            session_start();
            
                            $_SESSION['log_user'] = $u;

                            $_SESSION['log_pass'] = $p;
                                    
                            header("Location: /logintest.php");
                        }
                    }
                }                        
            }
            echo "<div class='bad'>".$msg."</div>";
        }
        echo '<form action="" method="POST">';
	?>
	<div class="logincells">
			<?php
            echo '<label>Firstname:</label><input type="text" name="firstname" class="fields" />';
				?>
		</div>
			<div class="logincells">
		<?php
            echo '<label>Password:</label><input type="password" name="password" class="fields" />';
			?>
					</div>
					<div class="user-area">
					<?php
            echo '<input type="submit" name="submit" value="Login" class="submit-button" />';
			?>
		</div>
			<?php
        echo '</form>';
        echo '<a href="/users/register.php">Register</a>
            <div class="clear"></div>';
    }    
    else
    {
        echo '<div class="good">Login was successful.<br>You are logged in as: '.$ses_user.'</div>';
        
        $join = mysql_query("SELECT * FROM users WHERE organisermembers = '$ses_user'");
        if($joined = mysql_fetch_assoc($join))
        {
            $join_num = $joined["joined"];
            
            if($join_num < 1)
            {
                echo '<a href="join.php">Join the Team</a>';
            }
        }
    }
?>

 

HTML HERE

Link to comment
Share on other sites

Did you read the sticky we have on that error?

 

Many thanks for pointing that out, wish I understood it fully.  I have come across this issue before with Chrome.  It wouldn't allow me to use include, I tried ob_start() but just couldn't get it to work.

 

So the page go:

 

Connect Code

Header

Login Processing Code

HTML

Form

 

I tried to remove all the white space and move the processing code to the top but it just pushes the error code right to the top of the page.

Link to comment
Share on other sites

What my code does is display the form which requires the user to enter the username and password that they registered in the registration page, once they click "submit" the form then submits to itself whereby the information then goes through a series of validations, and should the username and password be correct, it then takes them straight to their profile page and dispalys "Login successful you are logged in as 'username'".

 

Have you managed to create the registration page which allows the user information to be entered into the database which the login script can then check against?

Link to comment
Share on other sites

justlukeyou: What the people above have been saying is that you should put this project on ice, and learn about PHP, HTML, HTTP and security first. Then, once you've done that, you can get back to this and finish it properly. Right now all you're doing is wasting time, yours and ours, since you don't know what you're doing. It's the same in any profession, as you wouldn't even start to attempt building a house if you've never touched a hammer before.

Programming is especially hard to get into, as every single detail matters. There are literally no margin of errors. Just like in mathematics, it either works or it doesn't. Understanding and proper planning is prerequisite for making things work.

 

White_lilly & justlukeyou: This is an example of how I write my login scripts. Note my use of a template engine here, to save all of the generated output into. The $Page variable is also used by the template engine, to determine the name and location of the HTML template file to use as the main content. This is so that I can ensure that no output happens until all of the PHP processing is done, and thus allowing me the most amount of flexibility in my code. Not to mention it makes reading the code a lot easier, than when mixing PHP and HTML.

 

<?php
// Check if user is logged in already.
if (Check_Login ('user_id')) {
	// Is, send to profile.
	header ("Location: {$Template->_PHP_INDEX}user");
	die ();
}

// Select the login form.
$Page = "user/_login_form";

// Check if log in is requested.
if (Check_Submit ($Template->BUTTON_LOGIN, 600)) {
	// Initialize variables for later use.
	$Check = $Void = true;
	$Message = '';

	// Retrieve and validate input.
	$Email = Validate ("email", "email", "EMAIL", "FORM_EMAIL", $Check, $Message, 30);
	if (!isset ($_POST['password']) || empty ($_POST['password'])) {
		$Message .= substr ($Template->FORM_PASSWORD, 0, -1).'", "';
		$Check = false;
	}

	// Check to see if everything validated correctly.
	if (!$Check) {
		// Didn't, prepare the error message for display, and stop processing.
		$Message = substr ($Message, 0, -3);
		$Template->_MESSAGE = '<p id="form_error" class="message error">'.sprintf ($Template->ERROR_FORM, $Message)."</p>\n";
		return;
	}

	// Determine what fields to retrieve from DB.
	$Fields = array ('user_id', 'email', 'status', 'username');

	// Log in and retrieve data from database into session.
	if (!Login_User ($Email, $_POST['password'], $Fields, $DB)) {
		// Failed login, return to form and show error.
		return;
	}

	// Logged in, send to main page.
	header ("Location: {$Template->_PHP_INDEX}");
	die ();
}

if (Check_Submit ($Template->BUTTON_LOGIN)) {
	// Add error message and repopulate field.
	$Template->_MESSAGE = '<p id="form_error" class="message error">'.$Template->ERROR_TIME_EXPIRED."</p>\n";
	$Template->_FORM_FIELD_EMAIL = htmlspecialchars ($_POST['email']);

	// Recheck "Remember me" if set.
	if (isset ($_POST['remember']) && !empty ($_POST['remember'])) {
		$Template->_FORM_FIELD_REMEMBER = ' checked="checked"';
	}
}

 

Before I wrote any of this code, however, I knew exactly what I wanted it to do. In fact, you could take the comments from this code, paste them into a text document, and you'd have something very similar to the docs I wrote when planning the code. Having it planned out in that amount of detail makes the code itself trivial to write, as you've solved all of the logic in the planning stage.

Reduce complexity, and keep things simple, in other words.

Link to comment
Share on other sites

Have you managed to create the registration page which allows the user information to be entered into the database which the login script can then check against?

 

Yes I have the registration system and the start of the process for password retreval.  But I am currently stuck on the header.  Currently I cant login and indicate that I am logged in.

 

My plan is write the code so the registration system works. 

 

When I have working system I am then going to go through it line by line and ensure that it the security is of a high level.  But by learning how the system should work and applying the security is like a mine field.

 

To learn it effectively I need to break it down.  Processing code first and then security. Im not going to use it until I am sure it safe to use.  But stewp by step the code is getting their.

Link to comment
Share on other sites

Hi,

 

I have read through the sticky topic based on headers and as far as I can the error I have is that the processing code for the form is below some of the HTML.  However what I'm confused about is that the login form is coded inside the code for processing the form so I have no choice to set the input cells inside the processing code.

 

With the code I have to the following form cells within the HTML.  Is there a way to seperate all code out so that some of it can be below HTML?

 

			</div>
			<?php
        echo '</form>';
        echo '<a href="/users/register.php">Register</a>
            <div class="clear"></div>';
    }    
    else
    {
        echo '<div class="good">Login was successful.<br>You are logged in as: '.$ses_user.'</div>';
        
        $join = mysql_query("SELECT * FROM users WHERE organisermembers = '$ses_user'");
        if($joined = mysql_fetch_assoc($join))
        {
            $join_num = $joined["joined"];
            
            if($join_num < 1)
            {
                echo '<a href="join.php">Join the Team</a>';
            }
        }
    }
?>

Link to comment
Share on other sites

You've made two fallacies in your second to last post:

  1. [*]This is not effective learning, this is bashing your head against a wall until the wall falls down.

Get a chisel, and work at the seams. (IOW, start small and read tutorials/manuals.)

[*]Security is a part of the process, not a product to be tacked on at the end.

The only way to ensure that you have a secure product is to plan for it from the start. To identify all potential security hazards and how to protect against them, before you're standing knee deep in shit wondering how to get out of it. Lift your gaze to spot that hole a mile ahead, and avoiding it is quite simple.

Or to use your analogy: The worst time to learn how to clear a minefield, is when you're right smack in the middle of one.

 

As for your last post: Did you actually read my post, or did you just skim it assuming to know what I meant with my words? Reason I'm asking, is that I can tell you right away that you will not learn to be a (good) programmer if you don't start to really pay attention to the details, all of them.

Link to comment
Share on other sites

The header error message tells you where the output is occurring at that is causing the problem. It's your job to find what that output is and eliminate it. If you want someone here to help do that, you would need to post the error message and the code from the start of your main file up to where that output is occurring at.

Link to comment
Share on other sites

Hi,

 

This is the error message and the code for everything excluding the login code.

 

I have tried changing the file away from UTF-8 but that no impact.  I am also trying to enable output buffering in php.ini. but Im not sure how to do that.

 

The file is called logintest.php where I have located the header but Im not sure if Im doing that correctly.  I also have a DIV called 'header' which I hope isn't affecting it.

 

 

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at /home/test.php:10) in /home/test.php on line 43

 

 

<?php
   if(!$ses_user && !$ses_pass){
      echo "You need to be logged in to view this page.";
   }
?><?php
    if(!$ses_user && !$ses_pass){
        if($_POST["submit"]){
            $u = $_POST["firstname"];
            $p = $_POST["password"];
            
            if(!$u && !$p){
                $msg = "<p>The login form is empty. Try again.</p>";
            }
            else{
                if(!$u){
                    $msg .= "<p>The username is empty. Try again.</p>";
                }
                else{
                    if(!$p){
                        $msg .= "<p>The password is empty. Try again.</p>";
                    }
                    else{
                        
                        $log = mysql_query("SELECT * FROM organisermembers WHERE firstname = '$u' AND password = '$p'");
                        
                        $check = mysql_fetch_assoc($log);
                        
                        $u_check = $check["firstname"];
                        $p_check = $check["password"];
                        
                        if($u != $u_check && $p != $p_check){
                            $msg .= "<p>The username or password was incorrect.</p>";
                        }
                        
                        if($u === $u_check && $p === $p_check){
                            session_start();
            
                            $_SESSION['log_user'] = $u;

                            $_SESSION['log_pass'] = $p;
                                    
                            header("Location: logintest.php");
                        }
                    }
                }                        
            }
            echo "<div class='bad'>".$msg."</div>";
        }
        echo '<form action="" method="POST">';
	?>
<!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">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Contact Us - .com</title>
<meta name="keywords" content="content" />
<meta name="description" content=" Feel free to get in touch" />
<link rel="stylesheet" href="/stylesheet.css" type="text/css" />
</head>
<body>





<div class="container">
<div class="content-container1">
	<div class="content-container2">
<div class="section-navigation">
		</div>
					<div class="content">
				<div class="topheader">		
					<div class="headersignin">
					<a href="/users/login.php"   rel="nofollow" class='blacklink'   >
Sign in
</a>
</div>

					<div class="headerjoin">
					<a href="/users/register.php"   rel="nofollow" class='whitelink'   >
Join free
</a>
</div>

					<div class="headerlinkright">
	<a href="/siteinfo/aboutus.php"   rel="nofollow" class='bloglink'   >About Us</a>
</div>
					<div class="headerlinkright">
<a href="/blog/blog.php"   rel="nofollow" class='bloglink'   >Blog</a>
</div>

					</div>	





<div class="header">
<div class="headerlogo">
<a href="http://.com"  rel="nofollow" >
<img src="/images/logo.png" alt=".com"/>
</a>
</div>

<div class="internalheaderlinks">
<div class="homepagesearchformcell">
<form action="/test/searchresults.php" method="post">
<input type="text" name="keywords" placeholder='perform a search...' class="internalsearch" />
</form>
</div>
<div class="internalsearchimagecell">
<input type="image"  value="Submit" src="/images/internalsearch.png" alt="Search" name="image" />
</div>
</div>
</div>

	</div>
</div>







<div class="content-container1">
	<div class="content-container2">
<div class="section-navigation">
		</div>
		<div class="content">

<div class="siteinfocell">
<div class="aboutuslinkscell">
<div class="aboutuslinks">
<a href="/siteinfo/aboutus.php" class='aboutuslink' rel="nofollow" >
<div class="aboutusfeature">
About Us
</div></a>
<a href="/siteinfo/howitworks.php" class='aboutuslink' rel="nofollow" ><div class="aboutusfeature">
How it Works
</div></a>
</div>
<div class="aboutuslinksheader">
Contact
</div>
<div class="aboutuslinks">
<a href="/siteinfo/terms.php" class='aboutuslink' rel="nofollow" >
<div class="aboutusfeature">
Terms & Conditions
</div></a>
<a href="/siteinfo/cookiepolicy.php" class='aboutuslink' rel="nofollow" >

</a>
</div>
</div>
<div class="aboutustextcell">

<div class="aboutuscontent">




<div class='aboutuscontent'> 


			<div class="logincells">
			<?php
            echo '<label>Firstname:</label><input type="text" name="firstname" class="fields" />';
				?>


			<div class="logincells">
		<?php
            echo '<label>Password:</label><input type="password" name="password" class="fields" />';
			?>
					</div>
					<div class="user-area">
					<?php
            echo '<input type="submit" name="submit" value="Login" class="submit-button" />';
			?>
		</div>
			<?php
        echo '</form>';
        echo '<a href="/users/register.php">Register</a>
            <div class="clear"></div>';
    }    
    else
    {
        echo '<div class="good">Login was successful.<br>You are logged in as: '.$ses_user.'</div>';
        
        $join = mysql_query("SELECT * FROM users WHERE organisermembers = '$ses_user'");
        if($joined = mysql_fetch_assoc($join))
        {
            $join_num = $joined["joined"];
            
            if($join_num < 1)
            {
                echo '<a href="join.php">Join the Team</a>';
            }
        }
    }
?>



</div>
		</div>
</div>
</div>
</div>
</div>
<div class="aside">
</div>
	</div>
</div>





<div class="content-container1">
	<div class="content-container2">
<div class="section-navigation">
		</div>
		<div class="content">

			<div class="footercell">
<div class="footercellleft">
<div class="footercellleftcells">

<div class="footercellleftcontent">

</div>
</div>



<div class="footercellleftcells">


</div>

<div class="footercellmiddlecells">
<div class="footercelllefttitle">
SIGN UP
</div>
<div class="footercellleftcontent">
<p><a href="/users/login.php"  class='footerlink' rel="nofollow" >Login</a></p>
<p><a href="/users/register.php"  class='footerlink' rel="nofollow" >Sign up</a></p>
</div>
</div>



<div class="footercellrightcell">
<div class="footercelllefttitle">
GO SOCIAL
</div>
<div class="footercellleftcontent">
<div class="footersocialimages">
<img src="/images/evfacebook.png" alt=".com Facebook Profile"/>
</div>
<div class="footersocialimages">
<img src="/images/evtwitter.png" alt=".com Facebook Profile"/>
</div>
<div class="footersocialimages">
<img src="/images/evlinkedin.png" alt=".com Facebook Profile"/>
</div>
</div>
</div>
	</div>	

	<div class="footerbottomline">
			<div class="footerbottomlinecontent">
<a href="/siteinfo/terms.php"  class='footerlinkbase' rel="nofollow" >Terms & Conditions</a>
| 
<a href="/siteinfo/copyright.php"  class='footerlinkbase' rel="nofollow" >Copyright</a>
| <a href="/siteinfo/cookiepolicy.php"  class='footerlinkbase' rel="nofollow" >Cookie Policy</a>
					</div>
		</div>
</div>
</div>	
		</div>


Link to comment
Share on other sites

The problem is the echo at the top of your code.

 

For one, you can't send any output to the screen before calling header.  That's just the way it works.

 

But, second, your echo is pointless anyway because you're redirecting the user.  They won't ever see that error message.

 

---

 

Again, stop what you're doing and take the time to learn the basics.  I realize that you find the documentation to be difficult to understand, but, really, the difficulty only goes up from there.  Every script ever made is built upon the foundations of the language itself - how it ties into HTTP, how it can generate HTML, CSS, and JavaScript, etc.  The idea that you can somehow magically get something working and then comb through it line-by-line to figure out why after the fact is illogical.  At best, you'll be forced to learn all that stuff anyway.  At worst, and more likely, you'll learn only one way to do something and never grow.

 

We're not trying to berate you, but we see a guy who's drowning that's refusing to grab onto a ring buoy.  Stubbornness and/or fear is a bad excuse to not learn.  If you truly want to learn this stuff, then screw what others will think/see and just do it.

Link to comment
Share on other sites

@justlukeyou,

 

Sorry man, but given that you saw an error message in front of your face that states the line number where the output is occurring at and you cannot identify what your code is doing on that line number (an echo statement) that is causing the output, means that you are not going to be able to use code that you find or to write your own code that does anything.

 

In order to use code you find or to write your own code, you need to be able to look at the statements in the code and know what each statement actually does AND you must also be able to see what each statement contributes toward the overall goal you are trying to achieve.

Link to comment
Share on other sites

 

For one, you can't send any output to the screen before calling header.  That's just the way it works. 

 

But, second, your echo is pointless anyway because you're redirecting the user.  They won't ever see that error message.

 

 

With point one, thanks.  Im not disputing that at all.  The problem is I dont fully understand what this means. I dont know how to call a header or where to place it.  How do I call the header?

 

With point two.  Thats fine.  I can just remove it.  Once the page is working it would indicate that the code is pointless so I would know to remove it then.

 

In a few days I've gone from having nothing to having a registration page, password reset which sends an email and a login script which is almost working.  At this rate within 2-3 weeks I should have a working membership system and it should take another 2-3 weeks to ensure it is secure.  If so I would be delighted with that.

 

 

 

Link to comment
Share on other sites

The problem is I dont fully understand what this means.

 

Stop trying to program and LEARN!

 

I dont know how to call a header or where to place it.

 

It should be pretty obvious from the comments that it should come before ANY OUTPUT.

 

echo 'output';
header('Location: doesnotwork.php');

 

This does not work because there is output. The same goes for:

 

<html>This is output</html>
<?php header('Location: doesnotwork.php'); ?>

 

This WILL work when you enable output buffering. This means putting ob_start() at the very top (right after <?php ) of your script.

 

<?php ob_start(); // first line ?>
<html>you can't see this output because you are being redirected unless you have crappy/no internet or your browser ignores Location headers!</html>
<?php header('Location: working-as-intended.php'); ?>

 

ob_start() enables output buffering, that means it keeps everything in a buffer before sending it to the browser, thus headers can still be manipulated and php does not throw warnings/errors.

 

If you want to use sessions make sure you call session_start() also at the very top (right after <?php ) of your script, it does not need to be at the same place where you use $_SESSION. session_start() simply populates $_SESSION.

 

<?php ob_start(); session_start(); // first line ?>
<html>you can't see this output because you are being redirected unless you have crappy/no internet or your browser ignores Location headers!</html>
<?php header('Location: working-as-intended.php'); ?>

 

I hope this helps!

Link to comment
Share on other sites

Many thanks for the explanation.  I have tried to use ob_start(); before with another issue but I couldn't get it to work.  I have tried to change the code to the following and it creates the following two errors.

 

Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent by

 

Warning: Cannot modify header information - headers already sent by

 

I also removed ob_start(); but this created the same error.  Does this suggest that the ob_start(); is not working.  Do I need to change the php.ini file to save the file in a different format?

 

 

<?php
   if(!$ses_user && !$ses_pass){
      echo "You need to be logged in to view this page.";
   }
?>
<?php ob_start(); session_start();  
    if($u === $u_check && $p === $p_check){
                           
                            $_SESSION['log_user'] = $u;

                            $_SESSION['log_pass'] = $p;
                                    
                            header("Location: logintest.php");
                        }
    if(!$ses_user && !$ses_pass){
        if($_POST["submit"]){
            $u = $_POST["firstname"];
            $p = $_POST["password"];
            
            if(!$u && !$p){
                $msg = "<p>The login form is empty. Try again.</p>";
            }
            else{
                if(!$u){
                    $msg .= "<p>The username is empty. Try again.</p>";
                }
                else{
                    if(!$p){
                        $msg .= "<p>The password is empty. Try again.</p>";
                    }

Link to comment
Share on other sites

Hi,

 

I tried placing it higher than that but it just follows the header.  For example the following code just jumps straight to the homeage.  And if I change the header to logintest.php the page wont load as it is going round in a continuous loop.

 

<?php
ob_start(); session_start();  ***HERE***
CONNECTION CODE
?><?php
ob_start(); session_start();  ***OR HERE***
   if(!$ses_user && !$ses_pass){
      echo "You need to be logged in to view this page.";
   }
?>
<?php     
    if($u === $u_check && $p === $p_check){
                           
                            $_SESSION['log_user'] = $u;

                            $_SESSION['log_pass'] = $p;
                                    
                            header("Location: /index.php");

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.