Hi, WebForums

I'm doing a login system, and it's working, but i'm having difficults in understand where does the "logout" go, other thing is that i want to improve the validation system - if someone could give me some tips.

Here are the codes i'm using

login form, "index.php":

<!----------JAVASCRIPT VALIDAR LOGIN---------------->
<script>
function validar() {
        if (document.getElementById("username").value.length==0) {
                alert("Introduza o seu Login");
                document.getElementById("username").focus();
                return false;           
        }
        if (document.getElementById("pass").value.length==0) {
                alert("Introduza a sua Password");
                document.getElementById("pass").focus();
                return false;           
        }
}
</script>
<!-------------------FORM LOGIN--------------------->
<td class = "table_title">
<h3> Log In </h3>
<form name="loginform" METHOD="POST" action="validapass.php" onsubmit="return validar()">
        <table class=textologin align="center" cellspacing="0" cellpadding="0" width="25%">
        <tr><td height="50"></td></tr>
                        <tr>
                <td width="50">Username:&nbsp;</td>
                <td width="150" align="left"><input name="username" size="15"></td>
                </tr>
               
                        <tr>
                <td> &nbsp;</td>
                </tr>
                       
                        <tr>
                <td width="50">Password:&nbsp;</td>
                <td width="150" align="left"><input type="password" name="pass" size="15"></td>
                </tr>

                <tr><td height="20"></td></tr>
                <tr>
                <td align="center"><input type="Submit" value="Log In"></td>
                </tr>
   </table>
</form>
</td>

username and password validation, "validapass.php":

<?php
session_start();

include "db_connect.php";

$username = $_POST['username'];
$pass = $_POST['pass'];

mysql_select_db($dbname, $connect);
$sql="SELECT username, password FROM alunos WHERE username='". $username. "'";

$resultado = mysql_query($sql, $connect) or die(mysql_error());

$num = mysql_fetch_assoc($resultado);

if ($username == $num['username'] AND $pass == $num['password']) {
        header("Location: index_log.php");
        } else {
        header("Location: login_form.php");
        }
mysql_close($con);
?>

If the login it's correct it opens "index_log.php":

In the end the "index_log" is the same as "index.php" the only diference is that appears "Login successful, user_name".

Can someone help me and give me some tips to improve the Login System?!

Thank you a lot,
PF2G

to log out just unset variables you did set and destroy the session. I can see validation in JS, that is bad unless it there is of course another check in Server side.

to log out just unset variables you did set and destroy the session. I can see validation in JS, that is bad unless it there is of course another check in Server side.

Why is it bad the JS, it is working perfectly...

to log out just unset variables you did set and destroy the session. I can see validation in JS, that is bad unless it there is of course another check in Server side.

Hello I do not want to seem to contradict you but I've always been taught that validation (client side) is a good way rather than doing it server side, this is because:

1) Reduces time : Why have something that has to wait for something (the server) when you can get an instant response?

2) What is the point of submitting data to the server, only to throw an error that certain information hasn't been submitted?

3) What if the server is down?

=)

It's unclear what you want to do...

<?php
session_start();

include "db_connect.php";
mysql_select_db($dbname, $connect);

$username = $_POST['username'];
$password  = $_POST['pass'];

$sql="SELECT username, password FROM alunos WHERE username='". $username. " AND password='".$password. "'";
$resultado = mysql_query($sql, $connect) or die(mysql_error());
if(mysql_affected_rows() == 1)
{
       header("Location: index.php");
}else{
    header("Location: login_form.php");
}
mysql_close($con);
?>

What is "index_log.php"? Are you declaring your sessions/cookies in this file?

Hope this helps =)

It's unclear what you want to do...

What is "index_log.php"? Are you declaring your sessions/cookies in this file?

Hope this helps =)

The "index_log.php" is the "index.php" but only with "log successful." this index_log only appears if the username and password are the same as the DB.

I don't get why you have two index pages? :S

If for example your index.php page contained the login form, and the index_log didn't contain the login form but contained "Hello {username}" then wouldn't it be easier to have one index file that did:

<?php

   if(isset($_SESSION['username'])) { // user is signed in
       // display "Hello username"
   }else{
     // displat the login form
   }
?>

and then just refresh to index.php? And if it's failed, just display a message?

That index_log was just a test so i could see the login was working...

Other thing. This website i'm working on is for a Music School, and what i want to do is, when the user is logged the pages with the information of the instruments - guitar, drums, bass, etc - it appears a button that says "I want to learn this ...".

Do you understand this question?

I'd have a function that checks to see if the user is logged in or not:

<?php
   function is_logged()
   {
       if(isset($_SESSION['username'])) { // user is signed in
          return true;
     }else{
       return false;
     }
   }
?>

And then for each page (Let's say Guitar) have this:

<?php

     if(is_logged())
     {
          // Display button for particular music thing
     }else{
        // display nothing 
     }
?>

Then you can re-use the same code over and over again and for each page, run the function :)

In response to OP:
I sure hope that's not the only code you have in your login script. You must sanitize ALL user submitted data before sending it to a database or you risk intrusions :)

As for clientside validation, there are plenty (I mean plenty) of readymade javascript form validation scripts. I suggest you use one like LiveValidation. After it has passed the JavaScript validation, then validate it through the server. If everything checks out, create a new session for that user. destroy the session if the user clicks logout. This is a very simple implementation of sessions, but this isn't a security forum ;)

More on Sessions: http://www.tizag.com/phpT/phpsessions.php

Hello I do not want to seem to contradict you but I've always been taught that validation (client side) is a good way rather than doing it server side, this is because:

1) Reduces time : Why have something that has to wait for something (the server) when you can get an instant response?

2) What is the point of submitting data to the server, only to throw an error that certain information hasn't been submitted?

3) What if the server is down?

=)

1) It reduces time, but is completely unsecure
2) That's why you use sessions to store data
3) If the server is down, who cares what the users are doing?

I was thinking "So, how can i do to display a msg with 'log successful'", but i thought instead of a kind of Alert Box create a label that is "visbile = false" until the user is logged. If the user is logged in, the label "visible = true".

I know that's possible but with JavaScript, can u help me?

Thank you,
PF2G

Why is it bad the JS, it is working perfectly...

What about a browser with JS turned off?

Hey, i tried a code, but i created a folder where i registed and it creates a file with the info, but i can't transform this code in some way that it reads the DB:

$error = false;
if(isset($_POST['login'])){
	$username = preg_replace('/[^A-Za-z]/', '', $_POST['username']);
	$password = ($_POST['password']);
	if(file_exists('users/' . $username . '.xml')){
		$xml = new SimpleXMLElement('users/' . $username . '.xml', 0, true);
		if($password == $xml->password){
			session_start();
			$_SESSION['username'] = $username;
			header('Location: index.php');
			die;
		}
	}
	$error = true;

By the looks of this script (I haven't ran it) but you're storing the users data in XML.. This isn't the safest route to go down..

I wouldn't go down the "Javascript" route either, do a simple check to see if the user is signed in or not.. You're already setting a session (username) if the user has successfully signed in.. Just do a check on it!

That XML was just a test, if it was working and now i'm not seeing how to instead of using that XML, make it read the MySQL DB and then go to the index:

<?PHP

include 'topo.php';

//if not
//index normal

//if user logged
//line 19 - "Login success, name_user" VISIBLE
?>

<!--content-->
<table width = 100%>
<tr>

<h2>Bem Vindo à Escola de Música de V.N.Gaia</h2>

<tr>
<font color = "green" size="3"> Welcome, <?php echo $_SESSION['username']; ?> </font>
</tr>

<td class = "table_title">
<h3> A Nossa Escola </h3>
<p align = "justify"> 
A Escola de Música de V.N.Gaia existe desde 1979. O nosso principal objectivo é incentivar o gosto musical de todas as pessoas seja qual for a idade.
<br/>
Os nossos Cursos estão divididos por graus (1º ao 5º) e no final de cada ano lectivo serão inseridas as notas dos alunos.
Essas notas resultam do trabalho, não só individual mas também a integração em grupo. 
</p>
</td>

<td width = 3%></td>

<td width = 20% class = "table_title"> 
<h3> Cursos </h3>
<table>
<tr>

<tr>
<td>Guitarra Elétrica</td>
</tr>

<tr>
<td> Piano</td>
</tr>

<tr>
<td> Violoncelo</td>
</tr>

<tr>
<td> Saxofone</td>
</tr>

<tr>
<td> <a href = "cursos.php"> <img src = "images/button.jpg"></img> </a> </td>
</tr>

</tr>
</table>
</td>


<td width = 3%></td>


<!----------JAVASCRIPT VALIDAR LOGIN---------------->
<script>
function validar() {
	if (document.getElementById("username").value.length==0) { 
		alert("Introduza o seu Login");
		document.getElementById("username").focus();
		return false;		
	}
	if (document.getElementById("pass").value.length==0) { 
		alert("Introduza a sua Password");
		document.getElementById("pass").focus();
		return false;		
	}
}
</script>

<?PHP
//user 'logado' ou nao
function is_logged()
 {
  if(isset($_SESSION['username'])) { 
    return true;
  }else{
    return false;
  }
 } 
?>
<!-------------------FORM LOGIN--------------------->
<td class = "table_title">
<h3> Log In </h3>
<form name="loginform" METHOD="POST" action="validapass.php" onsubmit="return validar()">
	<table class=textologin align="center" cellspacing="0" cellpadding="0" width="25%">
        <tr><td height="50"></td></tr>
			<tr>
               <td width="50">Username:&nbsp;</td>
               <td width="150" align="left"><input name="username" size="15"></td>
            </tr>
            
			<tr>
            <td> &nbsp;</td>
            </tr>
			
			<tr>
               <td width="50">Password:&nbsp;</td>
               <td width="150" align="left"><input type="password" name="pass" size="15"></td>
            </tr>

		<tr><td height="20"></td></tr>
            <tr>
               <td align="center"><input type="Submit" value="Log In"></td>
            </tr>
   </table>
</form>
</td>

</tr>
</table>
<!---------------------------------------------------------------------------->
<table width = 100%>
<tr>

<h2>Curiosidades</h2>

<td class = "table_title">
<h3> Destaques </h3>
10/01/2012
<br/>
Inauguração da Escola de Música de V.N.Gaia.
</td>

</tr>
</table>
			
<?PHP

include 'rodape.php';

?>

If the user is logged in or not.
Do you understand my question?

<?PHP

include 'topo.php';

//user 'logado' ou nao
function is_logged()
{
   if(isset($_SESSION['username'])) { 
     return true;
 }else{
    return false;
 }
} 
?>

<!--content-->
<table width = 100%>
<tr>

<h2>Bem Vindo à Escola de Música de V.N.Gaia</h2>

<tr>
<font color = "green" size="3">
Welcome, 
<?php 
if(is_logged())
{
   echo $_SESSION['username']; 
}else{
  echo "Guest!";
}
?> 
</font>
</tr>

<td class = "table_title">
<h3> A Nossa Escola </h3>
<p align = "justify"> 
A Escola de Música de V.N.Gaia existe desde 1979. O nosso principal objectivo é incentivar o gosto musical de todas as pessoas seja qual for a idade.
<br/>
Os nossos Cursos estão divididos por graus (1º ao 5º) e no final de cada ano lectivo serão inseridas as notas dos alunos.
Essas notas resultam do trabalho, não só individual mas também a integração em grupo. 
</p>
</td>

<td width = 3%></td>

<td width = 20% class = "table_title"> 
<h3> Cursos </h3>
<table>
<tr>

<tr>
<td>Guitarra Elétrica</td>
</tr>

<tr>
<td> Piano</td>
</tr>

<tr>
<td> Violoncelo</td>
</tr>

<tr>
<td> Saxofone</td>
</tr>

<tr>
<td> <a href = "cursos.php"> <img src = "images/button.jpg"></img> </a> </td>
</tr>

</tr>
</table>
</td>


<td width = 3%></td>


<!----------JAVASCRIPT VALIDAR LOGIN---------------->
<script>
function validar() {
	if (document.getElementById("username").value.length==0) { 
		alert("Introduza o seu Login");
		document.getElementById("username").focus();
		return false;		
	}
	if (document.getElementById("pass").value.length==0) { 
		alert("Introduza a sua Password");
		document.getElementById("pass").focus();
		return false;		
	}
}
</script>

<?php
if(!is_logged())
{
?>
<!-------------------FORM LOGIN--------------------->
<td class = "table_title">
<h3> Log In </h3>
<form name="loginform" METHOD="POST" action="validapass.php" onsubmit="return validar()">
	<table class=textologin align="center" cellspacing="0" cellpadding="0" width="25%">
        <tr><td height="50"></td></tr>
			<tr>
               <td width="50">Username:&nbsp;</td>
               <td width="150" align="left"><input name="username" size="15"></td>
            </tr>
            
			<tr>
            <td> &nbsp;</td>
            </tr>
			
			<tr>
               <td width="50">Password:&nbsp;</td>
               <td width="150" align="left"><input type="password" name="pass" size="15"></td>
            </tr>

		<tr><td height="20"></td></tr>
            <tr>
               <td align="center"><input type="Submit" value="Log In"></td>
            </tr>
   </table>
</form>
</td>

</tr>
</table>
<!---------------------------------------------------------------------------->
<?php
}
?>
<table width = 100%>
<tr>

<h2>Curiosidades</h2>

<td class = "table_title">
<h3> Destaques </h3>
10/01/2012
<br/>
Inauguração da Escola de Música de V.N.Gaia.
</td>

</tr>
</table>
			
<?PHP

include 'rodape.php';

?>

Try that (I have ran the script, dunno if there are any errors)

Remember, in your "validapass.php" you need to redirect back to this page.

Also, if this is your webpage, I wouldn't use tables as much as you do.. Look into techniques such as div attributes, as well as new HTML5 features!

Hope this helps :)

Thanks for the div and html5 advice, but i never worked with that. This is for a school evaluation work and i'm a little bit "chocked", you know? But i'm going to search that.

One more time, thanks for that ;)

Did the session thing work?

And no problem, if you need anything else, feel free to ask =)

It's almost working, when i login it goes to the index but with the Guest message!!

validapass.php

<?php
session_start();

include "db_connect.php";

$username = $_POST['username'];
$pass = $_POST['pass'];

mysql_select_db($dbname, $connect);
$sql="SELECT username, password FROM alunos WHERE username='". $username. "'";

$resultado = mysql_query($sql, $connect) or die(mysql_error());

$num = mysql_fetch_assoc($resultado);

if ($username == $num['username'] AND $pass == $num['password']) {
	header("Location: index.php");
	} else {
	header("Location: login_form.php");
	}
mysql_close($con);
?>

Try:

<?php
session_start();

include "db_connect.php";

$username = $_POST['username'];
$pass = $_POST['pass'];

mysql_select_db($dbname, $connect);
$sql="SELECT username, password FROM alunos WHERE username='". $username. "'";

$resultado = mysql_query($sql, $connect) or die(mysql_error());

$num = mysql_fetch_assoc($resultado);

if ($username == $num['username'] AND $pass == $num['password']) {
        $_SESSION['username'] = $username; // this will store the value of username in the session value.
	header("Location: index.php");
	} else {
	header("Location: login_form.php");
	}
mysql_close($con);
?>

You can also reduce the code by querying the username AND password together in one query.

Everything is alright but it says "Welcome, Guest" weather i'm logged or not.

index.php:

<?PHP
     
    include 'topo.php';
     
    //user 'logado' ou nao
    function is_logged()
    {
    if(isset($_SESSION['username'])) {
    return true;
    }else{
    return false;
    }
    }
    ?>
     
    <!--content-->
    <table width = 100%>
    <tr>
     
    <h2>Bem Vindo à Escola de Música de V.N.Gaia</h2>
     
    <tr>
    <font color = "green" size="3">
    Welcome,
	
	<?php
    if(is_logged())
    {
    echo $_SESSION['username'];
    }else{
    echo "Guest!";
    }
    ?>
    
	</font>
    </tr>

(...)

<!----------JAVASCRIPT VALIDAR LOGIN---------------->
    <script>
    function validar() {
    if (document.getElementById("username").value.length==0) {
    alert("Introduza o seu Login");
    document.getElementById("username").focus();
    return false;
    }
    if (document.getElementById("pass").value.length==0) {
    alert("Introduza a sua Password");
    document.getElementById("pass").focus();
    return false;
    }
    }
    </script>
     
    <!-------------------FORM LOGIN--------------------->
    <td class = "table_title">
    <h3> Log In </h3>
    <form name="loginform" METHOD="POST" action="validapass.php" onsubmit="return validar()">
    <table class=textologin align="center" cellspacing="0" cellpadding="0" width="25%">
    <tr><td height="50"></td></tr>
    <tr>
    <td width="50">Username:&nbsp;</td>
    <td width="150" align="left"><input name="username" size="15"></td>
    </tr>
     
    <tr>
    <td> &nbsp;</td>
    </tr>
     
    <tr>
    <td width="50">Password:&nbsp;</td>
    <td width="150" align="left"><input type="password" name="pass" size="15"></td>
    </tr>
     
    <tr><td height="20"></td></tr>
    <tr>
    <td align="center"><input type="Submit" value="Log In"></td>
    </tr>
    </table>
    </form>
    </td>
     
    </tr>
    </table>

validapass.php:

<?php
session_start();
     
include "db_connect.php";
     
$username = $_POST['username'];
$pass = $_POST['pass'];
   
mysql_select_db($dbname, $connect);
$sql="SELECT username, password FROM alunos WHERE username='". $username. "' AND '". $pass ."'";
    
$resultado = mysql_query($sql, $connect) or die(mysql_error());
  
$num = mysql_fetch_assoc($resultado);
    
if ($username == $num['username'] AND $pass == $num['password']) {
  $_SESSION['username'] = $username; // this will store the value of username in the session value.
  header("Location: index.php");
  }
  else {
   header("Location: login_form.php");
  }
mysql_close($con);
?>
<?PHP
    ob_start();
    session_start();

    include 'topo.php';
    //user 'logado' ou nao
    function is_logged()
    {
    if(isset($_SESSION['username'])) {
    return true;
    }else{
    return false;
    }
    }
    ?>
     
    <!--content-->
    <table width = 100%>
    <tr>
     
    <h2>Bem Vindo à Escola de Música de V.N.Gaia</h2>
     
    <tr>
    <font color = "green" size="3">
    Welcome,
	
	<?php
    if(is_logged())
    {
    echo $_SESSION['username'];
    }else{
    echo "Guest!";
    }
    ?>
    
	</font>
    </tr>

Try that. Just initialised the session_start();

It worked, but when i logged out it never worked again. I'm trying to see the validapass.php and other pages...but i don't see anything wrong.

Does it work if you sign back in again? When you logout, it will unset the session and return back to "Welcome, guest"

No, that's the thing i logged out and "Welcome, Guest!" when i log back in it still has "Guest".

That's weird haha

<?PHP
    session_start();

    include 'topo.php';
    //user 'logado' ou nao
    function is_logged()
    {
    if(isset($_SESSION['username'])) {
    return true;
    }else{
    return false;
    }
    }
    ?>
     
    <!--content-->
    <table width = 100%>
    <tr>
     
    <h2>Bem Vindo à Escola de Música de V.N.Gaia</h2>
     
    <tr>
    <font color = "green" size="3">
    Welcome,
	
	<?php
    if(is_logged())
    {
    echo $_SESSION['username'];
    }else{
    echo "Guest!";
    }
    ?>
    
	</font>
    </tr>

Removed the ob_start(); should work! That's the only thing I can think it might be.

It's not, i tried that already. Sorry to disappoint you.

I tried everything and i'm not seeing the problem.

Right, I'm really sorry about this.. >.< Let me write the script (again) and I'll see what the problem is.. :) Hopefully, this should finally work haha!

Yeah, i was exciting, because the first time i tried the code it worked. Then i tried the Log out code, it worked. When i tried to log back in it didn't work :(

Let's do a test =)

Create a new page (call it test.php) that has this code in it:

<?php
    session_start();

    function is_logged()
    {
        if(isset($_SESSION['loggedin']))
        {
            return true;
        }else{
           return false;
       }
   }

   if(is_logged())
   { 
        echo "Welcome, {$_SESSION['username']}";
   }else{
      echo "Welcome, Guest";
   }

And then change your "validpass.php" to this:

<?php
session_start();

include "db_connect.php";
mysql_select_db($dbname, $connect);
     
$username = $_POST['username'];
$pass = $_POST['pass'];
   
$sql="SELECT username, password FROM alunos WHERE username='". $username. "' AND '". $pass ."'";
$resultado = mysql_query($sql, $connect) or die(mysql_error());
if(mysql_affected_rows() == 1)
{
    $_SESSION['username'] = $username;
    $_SESSION['loggedin'] = 1;
    header("Location: test.php");
}else{
  header("Location: login_form.php");
}
mysql_close($con);

?>

If this doesn't work, can you please use this (in test.php):

var_dump ($_SESSION['username']);
var_dump ($_SESSION['loggedin']);

Hope this helps you =) It worked when I tried it on my server!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.