0

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

4
Contributors
44
Replies
46
Views
5 Years
Discussion Span
Last Post by phorce
0

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.

0

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...

0

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?

=)

0

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 =)

Edited by phorce: n/a

0

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.

0

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?

0

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?

0

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 :)

0

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?

0

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

0

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;
0

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!

0

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?

0
<?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 :)

0

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 ;)

0

Did the session thing work?

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

0

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);
?>

Edited by PF2G: n/a

0

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.

0

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);
?>
0
<?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();

0

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.

0

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

0

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

0

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.

0

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

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

0

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!

0

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 :(

0

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!

Edited by phorce: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.