PHP Login System

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

DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

PHP Login System

Post by DarkAngel »

Im trying to intergrate a login script coded by someone else into my partly php site.
what im looking at doing;
having a login form in the bottom corner (in a table) of my site so that when a user enters their username and pass they are logged in with a session cookie and are able to access scripts/files/folders that would otherwise be protected.
BUT im having major problems because i want the login form to be half way through the html of the index.php in my site, and because im using seessions and the like it gives me the "Warning: session_start(): Cannot send session cookie - headers already sent by blah blah line in index.php"
Now how can i make my own / modify this login form so that i have username password fields on the sites main page, when if a user enters their details, they are logged in (but not navigated away from index.php - im using iframes) and are able to access files they otherwise wouldnt be able to get to.

Thanks in advance, DarkAngel the PHP n00b

:D
McGruff
DevNet Master
Posts: 2893
Joined: Thu Jan 30, 2003 8:26 pm
Location: Glasgow, Scotland

Post by McGruff »

You can call session_start anywhere in a script PROVIDED there hasn't been any html output up to this point.

Output buffering should provide a quick and dirty fix.
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

McGruff wrote:You can call session_start anywhere in a script PROVIDED there hasn't been any html output up to this point.

Output buffering should provide a quick and dirty fix.
I know this, but how can I make it work the way i want?
User avatar
tim
DevNet Resident
Posts: 1165
Joined: Thu Feb 12, 2004 7:19 pm
Location: ohio

Post by tim »

Like McGruff already advised

Output buffering

check out ob_start(); @ php.net
User avatar
mendingo
Forum Commoner
Posts: 28
Joined: Sun May 23, 2004 1:27 pm

Post by mendingo »

I would do it by having the username and password box post back to the same page, then have the php that deals with the login process at the top of the page.

How do you currently have the username and password delivered to your php code?
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

mendingo wrote:I would do it by having the username and password box post back to the same page, then have the php that deals with the login process at the top of the page.

How do you currently have the username and password delivered to your php code?
Good plan, will try now.
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

Just tried that, didnt really work, im a total n00b.

Code: Select all

<?php
include("config.php");  //the config file that has the db usrname and pwd

$connect = mysql_connect("$user_hostname", "$user_username", "$user_password"); //connect to mysql with the info in config.php
mysql_select_db("$user_database", $connect); //connect to the user database defined in config.php

session_start(); //start the session
session_register("username"); //register the (i think this is what happens) username from the form below (which it doesnt seem to get to)
session_register("password"); //register the pwd 

$sql = "SELECT * FROM users WHERE username = "$username" AND password = "$password""; //check if the user is in the db
$result = @mysql_query($sql) or die("No.");		//and again

if(mysql_num_rows($result) == "0") &#123;	//and if they arent in the db

session_unregister("username"); //kill the session
session_unregister("password");	//and again

echo "<h2 align=center>Wrong username and password, try again</h2>"; //and tell the user that they are stupid
exit;

&#125;

$username = mysql_result($result,0,"username"); //and if they are in the db, then leave the session alone

mysql_close($connect); //and disconnect
?>
<html>
<head>
<LINK REL="StyleSheet" HREF="theme\style.css" TYPE="text/css">
<title>blah</title>
</head>
<body background="images/bg.png">


//all the content and shig thats not really relevant to what im trying to do//

<?php echo "<form method="POST" action=$PHP_SELF>					// echo
<center>										// the 
<table>
<tr>											/form
<td>Username:</td>
<td><input type="text" name="username" size="20"></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" size="20"></td>
</tr>
<tr>
<td colspan="2">
<p align="center"><input type="submit" value="Submit" name="submit"></td>
</tr>
</table>
</center>
</form>";
?>
</html>
if i got any of the commenting wrong, please tell me.
User avatar
mendingo
Forum Commoner
Posts: 28
Joined: Sun May 23, 2004 1:27 pm

Post by mendingo »

Your config.php file: Does it have any blank lines or whitespace outside the <? and ?> tags? If so, then they're sent to the browser, and the dreaded "header already sent" error appears.

Can't really figure out from your code where you're actually giving the sessions their data.

The structure wants to be something like this:

Code: Select all

<?php
include("config.php");
session_start();
if(isset($_POST['login'])) //check if the login button has been posted
{
  if(/*do whatever authentication you do*/)
  {
    $_SESSION['username'] = $_POST['username']; //set the session variable "username" to be the same as the value of the text field "username"
  }
}

?>
<HTML>
<BODY>
<FORM ACTION="" METHOD="POST">
  <INPUT NAME="username" TYPE="text">
  <INPUT NAME="password" TYPE="password">
  <INPUT NAME="login" TYPE="submit">
</FORM>
</BODY>
</HTML>
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

Ok what im trying to do is get the data entered in the form, check if the data matches a user in a mysql db if it doesnt then echo an error and if it does create a session cookie.
Possible?

I tried this, but it didnt appear to work (but didnt give me any errors)

Code: Select all

<?php
include("config.php");

$connect = mysql_connect("$user_hostname", "$user_username", "$user_password");
mysql_select_db("$user_database", $connect);
$sql = "SELECT * FROM users WHERE username = "$username" AND password = "$password"";
$result = @mysql_query($sql) or die("No.");

session_start();

if(isset($_POST&#1111;'login'])) //check if the login button has been posted
&#123;
  if(mysql_num_rows($result) == "1")
  &#123;
    $_SESSION&#1111;'username'] = $_POST&#1111;'username']; //set the session variable "username" to be the same as the value of the text field "username"
  &#125;
&#125;

?>
<HTML>
<BODY>
<FORM ACTION="" METHOD="POST">
  <INPUT NAME="username" TYPE="text">
  <INPUT NAME="password" TYPE="password">
  <INPUT NAME="login" TYPE="submit">
</FORM>
</BODY>
</HTML>
User avatar
mendingo
Forum Commoner
Posts: 28
Joined: Sun May 23, 2004 1:27 pm

Post by mendingo »

OK, I think the confusion here is with your misunderstanding of sessions.

You can't "set a session cookie". sessions are separate to cookes. The "Session" is a PHP system that stores a variable as long as the browser is open. How it does it is something you don't have to worry about.

The way you store that variable is by putting it into the $_SESSION array.

For example:

Code: Select all

$_SESSION['Loggedin'] = false;
if($databasePassord == $enteredPassword)
{
  $_SESSION['loggedin'] = true;
}
Now, $_SESSION['Loggedin'] will always be true as long as the browser is open.

So to edit the script you posted,

Code: Select all

<?php 
include("config.php"); 

$connect = mysql_connect("$user_hostname", "$user_username", "$user_password"); 
mysql_select_db("$user_database", $connect); 
$sql = "SELECT * FROM users WHERE username = "$username" AND password = "$password""; 
$result = @mysql_query($sql) or die("No."); 

session_start(); 

if(isset($_POST['login'])) //check if the login button has been posted 
{ 
  $_SESSION['loggedin'] = false;
  if(mysql_num_rows($result) == "1") 
  { 
    $_SESSION['loggedin'] = true; 
  } 
} 

?> 
<HTML> 
<BODY> 
<FORM ACTION="" METHOD="POST"> 
  <INPUT NAME="username" TYPE="text"> 
  <INPUT NAME="password" TYPE="password"> 
  <INPUT NAME="login" TYPE="submit"> 
</FORM> 
</BODY> 
</HTML>
Now to check if a user is logged in, simply use:

Code: Select all

if($_SESSION['loggedin'])
{
  //put secret world domination plans here
}

Note this is not a particularly secure way of doing it. To be safe, you should generate a random number and store that in the session as well

Code: Select all

$_SESSION['id']=rand();
and add that same random number to the database in the same row as the username and password, so you can always compare them.
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

Excellent, that worked great.
I have a few more questions;
How would I go about making a logout button/link?
(Using session_destroy(); ?)
The welcome text (Welcome $Username) only works once, and if you follow a link on the page (which changes the src with php of an iframe) the $username doesnt print anymore, how can i fix this? Sessions to the rescue again?
And also, if a user enters the wrong password it echoes "wrong password" or whatever, BUT if they havent actually tried to log in before it doesnt show anything minus the login box?

So far i have this;

Code: Select all

<?php
include("config.php");

$connect = mysql_connect("$user_hostname", "$user_username", "$user_password");
mysql_select_db("$user_database", $connect);
$sql = "SELECT * FROM users WHERE username = "$username" AND password = "$password"";
$result = @mysql_query($sql) or die("No.");

session_start();

if(isset($_POST['login']))
{
  $_SESSION['loggedin'] = false;
  if(mysql_num_rows($result) == "1")
  {
    $_SESSION['loggedin'] = true;
  } else 	{
  			$badlogintext = "Incorrect Username or Password";
  			}
}
?>
<html>
<?php
if($_SESSION['loggedin'] == "false")
{
echo "Welcome, <b>$username</b>";
echo "<
} else {
echo "
<FORM ACTION='' METHOD='POST'>
  <p align='center'>
Username: <INPUT NAME='username' TYPE='text'>
Password:  <INPUT NAME='password' TYPE='password'>
  <INPUT NAME='login' TYPE='submit' value='Login'>
</p>
</FORM>";
}
echo $badlogintext
?>
</html>
Last edited by DarkAngel on Mon May 24, 2004 5:11 am, edited 1 time in total.
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

Btw, thanks loads for the help so far, i dont know where id be without people like you lot :D
User avatar
mendingo
Forum Commoner
Posts: 28
Joined: Sun May 23, 2004 1:27 pm

Post by mendingo »

to logout, use

Code: Select all

unset($_SESSION['loggedin']);
don't do unset($SESSION); That'll cause all kinds of problems!

In your code, you're saying

Code: Select all

if($_SESSION['loggedin'] == "false") 
{ 
  echo "Welcome, <b>$username</b>"; 
}
is that a typo?

The reason it works is that you've put "false" as a string (with ""). PHP interprets anything that isn't 0 as meaning true. When checking for true or false, don't use perentheses ("").

it should say

Code: Select all

if($_SESSION['loggedin']) // ==true is automatically assumed.
{ 
  echo "Welcome, <b>$username</b>"; 
}

You could also expand this for logoff purposes:

Code: Select all

<FORM ACTION='' METHOD='POST'> 
if($_SESSION['loggedin'])
{ 
  echo "Welcome, <b>$username</b><br>";
  echo "<input type='submit' value='logoff'>";
}
else
{
  echo "Username: <INPUT NAME='username' TYPE='text'>";
  echo "Password:  <INPUT NAME='password' TYPE='password'>";
  echo "<INPUT NAME='login' TYPE='submit' value='Login'>";
}
</FORM>
Then up at the top of the script, after you've checked for $_POST['login'] being set, you could check for a logoff:

Code: Select all

if(isset($_POST['logoff']))
{
  unset($_SESSION['loggedin']);
}
For the username, add it to the session superglobal same as loggedin. $_SESSION['username'] = $username; Just remember to unset it during logout.

If you want some stuff to appear all the time, then do it outsitde the if-else statment.
DarkAngel
Forum Newbie
Posts: 12
Joined: Sun May 23, 2004 11:01 am

Post by DarkAngel »

Ok amazing, it works, thanks loads man :D
Last edited by DarkAngel on Mon May 24, 2004 6:49 am, edited 1 time in total.
malcolmboston
DevNet Resident
Posts: 1826
Joined: Tue Nov 18, 2003 1:09 pm
Location: Middlesbrough, UK

Post by malcolmboston »

in your login authentication page (where your form action on the login box directs to)

so when it is verfying details it will also do that.
Post Reply