PHP Login script

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 2275 Views - Last Post: 07 November 2011 - 11:27 AM Rate Topic: -----

#1 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

PHP Login script

Posted 06 November 2011 - 05:16 PM

Hi, I have the following html form

login.php (some html has been removed but was only there for styling etc)
<?php
session_start();
?>

<html>
<body>

<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
                   		
   foreach($_SESSION['ERRMSG_ARR'] as $msg) {
      echo $msg; 
         }
   unset($_SESSION['ERRMSG_ARR']);
                   	}
 ?>

<form action="test.php" method="post" id="contactform"> 
   <fieldset>
      <label>Username</label>
      <input type="text" name="uname" class="textfield" id="uname" value="" />
                                                                        
<div class="contact-column-right">
   <label>Password</label>
   <input type="password" name="pass" class="textfield" id="pass" value="" />
   <label>&nbsp;</label>
   <input type="submit" name="submit" value="Login" class="button" />
</div>
   </fieldset> 
</form> 


</body>
</html>



This form posts to the following php script (test.php)
<?php
	//Start session
	session_start();
	
	//Include database connection details
	require_once('config.inc');
	
	//Array to store validation errors
	$errmsg_arr = array();
	
	//Validation error flag
	$errflag = false;
	
	//Connect to mysql server
	$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
	if(!$link) {
		die('Failed to connect to server: ' . mysql_error());
	}
	
	//Select database
	$db = mysql_select_db(DB_DATABASE);
	if(!$db) {
		die("Unable to select database");
	}
	
	//Function to sanitize values received from the form. Prevents SQL injection
	function clean($str) {
		$str = @trim($str);
		if(get_magic_quotes_gpc()) {
			$str = stripslashes($str);
		}
		return mysql_real_escape_string($str);
	}
	
	//Sanitize the POST values
	$login = clean($_POST['uname']);
	$password = clean($_POST['pass']);
	$pwd = hash('sha256', $password);
	
	//Input Validations
	if($login == '') {
		$errmsg_arr[] = 'Login ID missing';
		$errflag = true;
	}
	if($password == '') {
		$errmsg_arr[] = 'Password missing';
		$errflag = true;
	}
	
	//If there are input validations, redirect back to the login form
	if($errflag) {
		$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
		session_write_close();
		header("location: login.php");
		exit();
	}
	
	//Create query
	$qry="SELECT * FROM tbl_user WHERE u_name='$login' AND password='$pwd'";
	$result=mysql_query($qry);
	
	//Check whether the query was successful or not
	if($result) {
		if(mysql_num_rows($result) == 1) {
			//Login Successful
			session_regenerate_id();
			$member = mysql_fetch_assoc($result);
			$_SESSION['SESS_MEMBER_ID'] = $member['id_user'];
			$_SESSION['SESS_FIRST_NAME'] = $member['f_name'];
			$_SESSION['SESS_LAST_NAME'] = $member['s_name'];
			session_write_close();
			header("location: member-index.php");
			exit();
		}else {
			//Login failed
			header("location: login.php");
			exit();
		}
	}else {
		die("Query failed");
	}
?>



on successful login the script should redirect to member-index.php
but no matter if i log in with the correct or incorrect details it always directs to login.php

The database connection is fine, I've test the sql & all table names/ row names are all correct.

Ive used this script on other sites and it has worked fine before and i have no idea what is going wrong this time.

As always everybody's help is very much appreciated.

Thank you

Is This A Good Question/Topic? 0
  • +

Replies To: PHP Login script

#2 codeprada  Icon User is offline

  • Changed Man With Different Priorities
  • member icon

Reputation: 948
  • View blog
  • Posts: 2,357
  • Joined: 15-February 11

Re: PHP Login script

Posted 06 November 2011 - 06:40 PM

Two things I think you should check
  • Passwords in your database are hashed using the same algorithm, salt etc...
  • There aren't multiple rows with the same username and password combination.

Was This Post Helpful? 2
  • +
  • -

#3 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3100
  • View blog
  • Posts: 10,889
  • Joined: 08-August 08

Re: PHP Login script

Posted 06 November 2011 - 07:26 PM

Functions are your friends. Read this demonstration of why you should use them.

Oh, and don't use mysql_* functions. Use prepared statements in PDO or MySQLi.
Was This Post Helpful? 2
  • +
  • -

#4 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

Re: PHP Login script

Posted 07 November 2011 - 07:30 AM

There is only one entry in the database so no duplication, and I am using sha256 and storing as char 64 (no salt) I've checked echo-ing the encrypted password and it is the same as whats in the database.


I might just have to find a new script as i don't understand what is going on
Was This Post Helpful? 0
  • +
  • -

#5 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3100
  • View blog
  • Posts: 10,889
  • Joined: 08-August 08

Re: PHP Login script

Posted 07 November 2011 - 08:05 AM

Did you read the link? It's almost a how to of exactly what you're trying to do.
Was This Post Helpful? 0
  • +
  • -

#6 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

Re: PHP Login script

Posted 07 November 2011 - 08:10 AM

Yes I've read the link it was ok, I'm not all that great with functions and i have managed to get this script (above) to work now.
does using functions make my code more efficient ???
Was This Post Helpful? 0
  • +
  • -

#7 satis  Icon User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 231
  • Joined: 26-May 11

Re: PHP Login script

Posted 07 November 2011 - 08:44 AM

Using functions makes writing code, understanding code, and editing code much easier. It does not speed code up, but the performance penalty for using functions (or objects) is minimal and not something you'll probably notice.

As the code you write gets longer, and as you start to want to re-use code snippets, using functions becomes indispensable. Once you're writing function-based code, you'll find that once it gets past a certain point of complexity, switching to object oriented code becomes similarly indispensable. Writing procedural code (what you have above) is really something that only works when you're writing really simple programs.
Was This Post Helpful? 1
  • +
  • -

#8 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

Re: PHP Login script

Posted 07 November 2011 - 08:46 AM

Thanks thats useful to know
Was This Post Helpful? 0
  • +
  • -

#9 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3100
  • View blog
  • Posts: 10,889
  • Joined: 08-August 08

Re: PHP Login script

Posted 07 November 2011 - 10:06 AM

View Postsatis, on 07 November 2011 - 11:44 AM, said:

Writing procedural code (what you have above) is really something that only works when you're writing really simple programs.

Very true, and since clarkeash is posting a question about their code we can assume that it is now too complex to continue writing procedural code.

Clarkeash, read that link again! Functions allow you to break up a project into several small projects, each of which should be easy to write. When writing a function you only need to think about what that function does because the rest of the project is irrelevant to that function. That makes your life easier.

As satis points out, after learning functions you'll probably want to learn about classes. Don't jump into them right away though. Be sure you understand functions first.
Was This Post Helpful? 0
  • +
  • -

#10 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

Re: PHP Login script

Posted 07 November 2011 - 10:37 AM

ok I am making my first function,
currently it checks if the user is logged in or not and outputs yes or no respectively.

Here is the code
<?php

function loggedIn() {
	if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')){
		echo 'no';
	}else {
		echo 'yes';
	}
	
}
?>

<?php
session_start();

loggedIn();

?>



How would i go about getting rid of the echo and doing an if based on the function

e.g.

if loggedIn() {
do something
}else{
do something else
}

this needs to be done outside the function as i will do different things based on the situation.

Thanks
Was This Post Helpful? 1
  • +
  • -

#11 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Re: PHP Login script

Posted 07 November 2011 - 10:41 AM

Instead of echoing yes or no simply return true or false.
Was This Post Helpful? 0
  • +
  • -

#12 satis  Icon User is offline

  • D.I.C Head

Reputation: 82
  • View blog
  • Posts: 231
  • Joined: 26-May 11

Re: PHP Login script

Posted 07 November 2011 - 10:42 AM

It's a good start, though returning strings of "yes" and "no" are probably the wrong way to go about it. The way you get the data back is using "return", and I would use boolean values... true and false.

A more concrete example:

<?
function loggedIn() {
	if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')){
		return false;
	}
	else{
		return true;
	}
}

if(loggedIn()){
	echo 'Welcome back member ' .$_SESSION['SES_MEMBER_ID'] .'<br>';
}
else{
	echo 'Would you care to log in?<br>';
}
?>



This is obviously very contrived, but should give you the general idea.
Was This Post Helpful? 0
  • +
  • -

#13 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

Re: PHP Login script

Posted 07 November 2011 - 10:46 AM

That helps thanks, I know its probably not the best use of a function but i wanted to start small
Was This Post Helpful? 0
  • +
  • -

#14 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3100
  • View blog
  • Posts: 10,889
  • Joined: 08-August 08

Re: PHP Login script

Posted 07 November 2011 - 10:57 AM

That's fine. As a general rule you want to keep all of your functions small. If they become large you can and probably should break them up into two or more functions.
Was This Post Helpful? 0
  • +
  • -

#15 clarkeash  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 56
  • Joined: 04-February 11

Re: PHP Login script

Posted 07 November 2011 - 10:59 AM

when i get to a stage where i have several functions should i create 1 file with all the functions in, and include that page when required or should i create a separate file for each function that way i only need to include the functions that i need for that page?

Thanks
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2