PHP Login Script (Learning Purposes)

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 5829 Views - Last Post: 21 September 2012 - 08:30 PM Rate Topic: -----

#1 jcgonz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 02-February 10

PHP Login Script (Learning Purposes)

Posted 19 September 2012 - 11:48 PM

Hi!
I wrote a login "code" here that I think works for simple logins.
I think my code is really crappy and the free online tutorials on php I've read seems outdated.

I made a sql database in XAMPP named 'bscs' with table 'accounts' with fields 'UID', 'username', and 'password'.

This is my connect.php:
<?php
$conn=mysql_connect('localhost','root','') or die("Unable to connect: ".mysql_error());
mysql_select_db('bscs',$conn)or die(Cannot find database: ".mysql_error());
?>




and here is my login.php:
include("connect.php");
if (isset($_POST["submitted"]))
{
if (!empty($_POST['UID']) && !empty($_POST['username']) && !empty($_POST['password']))
 {
 $UID = trim($_POST['UID']);
 $username = trim ($_POST['username']);
 $password = trim ($_POST['password']);
 $data = mysql_query("select count(*)as urow from accounts where UID='$UID', username='$username' and password='$password'");
 $row = mysql_fetch_array($data);
 $num=$row['urow'];
 if ($num>0)
  {
  echo "<script>alert('Login Successful')</script>";
  }
 else
  {
  echo "<script>alert('Incorrect Username/Password')</script>";
  }
 }
else
 {
 echo "<script>alert('Fill up the form completely')</script>";
 }
mysql_close();
}

?>

<form action="login.php" method="post">
Username:&nbsp;<input type="text" name="username" /><br>
Password:&nbsp;<input type="password" name="password" /><br>
<input type="submit" name="login" value="Login" />
<input type="hidden" name="submitted" value="true" />
</form>
}



I've tried it and I think it works... I haven't noted any form of error.

What I want to know is how do I make it redirect to a new page without losing the data reference like the UID.
I want the next page like a menu.php to be able to display the name of the current logged in user.

Here is my code for menu.php:
<?php
include("connect.php");
$data=mysql_query("select * from accounts where username='$username' and UID='$UID'") or die("User not found: ".mysql_error());
$row=mysql_fetch_query($data);
echo "Logged in as ".$row['username']."<br>";

print 'The menu is displayed here';
?>



I don't know how to redirect and connect the two pages with each other. T_T Please help me know what the error is.
Btw, I am learning by myself so I don't know if my codes are outdated or wrong formatted.

Is This A Good Question/Topic? 0
  • +

Replies To: PHP Login Script (Learning Purposes)

#2 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 12:29 AM

You can redirect using the header() function. header("Location: http://www.example.com/"); /* Redirect browser */.

I would set a session when login is successful and then use that on subsequent page requests.

Main point. the mysql_* functions are outdated and insecure (if incorrectly used) it is much much better to switch to mysqli_* or better yet, PDO. Read this if you want to know why using mysql_* is a bad idea.
Was This Post Helpful? 3
  • +
  • -

#3 jcgonz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 02-February 10

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 12:37 AM

Header() it is then.

I will read it later after I make my test pages run.

Thank you for helping.
Was This Post Helpful? 0
  • +
  • -

#4 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 01:10 AM

Read the last paragraph first!

The mysql_* functions are slow, obsolete and insecure!

I would strongly suggest switching to PDO before proceeding any further though.
Was This Post Helpful? 0
  • +
  • -

#5 jcgonz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 02-February 10

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 03:22 AM

Yes, I've finished reading it. I Didn't knew there is a PDO and a mySQLi... as they haven't been tackled yet in the tutorial I was following. The PDO and mySQLi will be discussed in the later chapters of the book and they were just showing how the outdated is supposed to work. Sorry, I forgot to mention that.

Anyways, I've remade the login form. :D and I think I'd like to know how it properly works in the old codes first.

<body bgcolor="#DDDDDD"><center>
<?php
include("connect.php");

//verify login
if(isset($_POST["submit"]))
{
	if(!empty($_POST['user']) && !empty($_POST['pass']))
	{
		$username=mysql_real_escape_string($_POST['user']);
		$password=mysql_real_escape_string($_POST['pass']);
		//$id=$_post['id'];
		$query = mysql_query("Select count(*) as rownum from accounts where username='$username' and password='$password'");
		$result = mysql_fetch_array($query);
		$num = $result['rownum'];
		
		if($num>0)
		{
			echo "<script>alert('Login Successful!\nRedirecting you to a new page')</script>";
			echo "<script>self.location='home.php?id=".$result['AID']."</script>";
			//header("Location:home.php?id={$row['AID']}");
		}
		else
		{
			echo "<script>alert('Incorrect Login Credentials')";
			echo "<script>location.reload()</script>";
		}
	}
	else
	{
		echo "<sript>alert('Please Fill Up The Form Completely')</script>";
	}
}

//create the login form
print '<table style="margin:250px" bgcolor="#CCCCCC" cellspacing="4" cellpadding="8">
<form action="login.php" method="post">
<tr><td>Username:</td><td><input type="text" name="user" /></td></tr>
<tr><td>Password:</td><td><input type="password" name="pass" /></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Login" /></td></tr>
</table>
</form>';
/*<input type="hidden" name="id" value="" />*/
mysql_close();
?>

</center></body>



I'm trying to make it show a new page and with the 'id' in it's url but it always reverts back to the login page and It always has an error on line 20 or 21. Can you point out my error and suggest what I could do about it?
Was This Post Helpful? 0
  • +
  • -

#6 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 03:49 AM

*
POPULAR

I am discouraged that you would waste time learning these older functions. As I have said before, they are slower and less secure than PDO. I also found it much easier to use PDO than mysql_*. There are lots of great PDO (by our very own Dormilich) tutorials for you to use as reference.

That aside, I am assuming the error is something along the lines of:

Quote

Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12


If so its because you have tried to use the header() function after you have sent content to the browser. For much more information take a look here.

Try:

if($num>0) {
  header("Location:home.php?id={$row['AID']}");
}



This should remove the error.

This post has been edited by KingCuddles: 20 September 2012 - 04:05 AM

Was This Post Helpful? 5
  • +
  • -

#7 jcgonz  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 38
  • Joined: 02-February 10

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 04:08 AM

That fixed the problem.

I'll read them all after the Beginners Guide to PDO.

I really just want to see what the book can offer. :D

Thank you!
Was This Post Helpful? 0
  • +
  • -

#8 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 04:38 AM

I know I keep going on, but I really cannot emphasise enough how bad using the mysql_* functions is.

If you need to create a user system, that's great, but a two minute Google search found me this: Simple Login System / PDO - I haven't watched it, but if it is using PDO, I can all but guarantee it is better than your book :).

This post has been edited by KingCuddles: 20 September 2012 - 04:41 AM

Was This Post Helpful? 3
  • +
  • -

#9 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2934
  • View blog
  • Posts: 10,138
  • Joined: 08-August 08

Re: PHP Login Script (Learning Purposes)

Posted 20 September 2012 - 06:27 AM

Two points:
  • Your book is going to teach you things that you will not need with prepared statements. For example, there is no need to escape strings with PDO. Why bother learning stuff you'll never need again?
  • If you're redirecting to a "page" within your site I would include or require instead of header. When you include/require you don't need to pass variables (they remain part of the script) and you cut down on unnecessary http traffic.

Was This Post Helpful? 3
  • +
  • -

#10 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 5,981
  • Joined: 08-June 10

Re: PHP Login Script (Learning Purposes)

Posted 21 September 2012 - 04:12 AM

As much as I agree with your recommendations to use the PDO or MySQLi extensions over the old MySQL API, I would still consider it a good idea to learn it. Few PHP developers will be lucky enough to avoid it altogether, at least for the foreseeable future. There is just too much code out there that uses it.

With that said, it should be learned along side PDO or MySQLi, not by itself.

View PostKingCuddles, on 20 September 2012 - 08:10 AM, said:

The mysql_* functions are slow...

What are you basing that on? (Besides the claim in that post you linked to, which is not backed up by anything.)

From all I've seen in the last few years, all the benchmarks I've managed to find, and from what I've observed in my own code, the old MySQL extension is actually slightly (emphasis on "slightly") faster than both the MySQLi and PDO extensions. Keep in mind that all three extensions rely on the exact same client library - either MySQL's Client library or, in PHP 5.3+, PHP's own MySQL Native Driver (mysqlnd) - so the only real difference in the performance is in the implementation overhead, and how it's used. As the simplest implementation of all three, the old MySQL API wrapper would (theoretically, at least) incur the least overhead.

Also, the link you posted mentions that the need for a lot of string concatenation when using the old MySQL extension is another performance hit. Interestingly the default behavior for PDO's MySQL driver is to emulate prepared statements, meaning that it will actually construct the SQL string in much the same manner we did when using the old MySQL extension. It's just hidden behind the PDO API. (It's probably done in C, not PHP, but still. The performance difference is practically non-existent.) - Another interesting point is that this emulation tends to be faster than MySQL's own handling of prepared statements. (Although, again, with a trivially small margin.)


Don't get me wrong, though. I'm not suggesting anybody use the old MySQL extension because of this.
Was This Post Helpful? 3
  • +
  • -

#11 KingCuddles  Icon User is offline

  • D.I.C Regular

Reputation: 176
  • View blog
  • Posts: 496
  • Joined: 20-December 08

Re: PHP Login Script (Learning Purposes)

Posted 21 September 2012 - 04:39 AM

View PostAtli, on 21 September 2012 - 12:12 PM, said:

As much as I agree with your recommendations to use the PDO or MySQLi extensions over the old MySQL API, I would still consider it a good idea to learn it. Few PHP developers will be lucky enough to avoid it altogether, at least for the foreseeable future. There is just too much code out there that uses it.

With that said, it should be learned along side PDO or MySQLi, not by itself.

View PostKingCuddles, on 20 September 2012 - 08:10 AM, said:

The mysql_* functions are slow...

What are you basing that on? (Besides the claim in that post you linked to, which is not backed up by anything.)

From all I've seen in the last few years, all the benchmarks I've managed to find, and from what I've observed in my own code, the old MySQL extension is actually slightly (emphasis on "slightly") faster than both the MySQLi and PDO extensions. Keep in mind that all three extensions rely on the exact same client library - either MySQL's Client library or, in PHP 5.3+, PHP's own MySQL Native Driver (mysqlnd) - so the only real difference in the performance is in the implementation overhead, and how it's used. As the simplest implementation of all three, the old MySQL API wrapper would (theoretically, at least) incur the least overhead.

Also, the link you posted mentions that the need for a lot of string concatenation when using the old MySQL extension is another performance hit. Interestingly the default behavior for PDO's MySQL driver is to emulate prepared statements, meaning that it will actually construct the SQL string in much the same manner we did when using the old MySQL extension. It's just hidden behind the PDO API. (It's probably done in C, not PHP, but still. The performance difference is practically non-existent.) - Another interesting point is that this emulation tends to be faster than MySQL's own handling of prepared statements. (Although, again, with a trivially small margin.)


Don't get me wrong, though. I'm not suggesting anybody use the old MySQL extension because of this.


Apologies for not making myself clear. When I was discussing speed I was referring to development speed. I am unable to update my previous post accordingly.

As for performance of pdo vs. mysql_* vs mysqli_*, I would have to agree with you. The mysql_* functions are slightly faster, but again I have no benchmarks to prove this either way, this is based solely on my own experience.

I have always found it exceptionally difficult to find good, reliable benchmarks, and would be very interested in any you have found Atli!

As for mysql_* usage, at least where I am based, most of the web development companies I have worked with use PDO, although admittedly many of these use an MVC Framework, and those that don't use mysqli_*. I actually haven't seen any mysql_* code in a live environment for a fair old while now! Of course I would assume this would vary greatly depending on your location.
Was This Post Helpful? 0
  • +
  • -

#12 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2934
  • View blog
  • Posts: 10,138
  • Joined: 08-August 08

Re: PHP Login Script (Learning Purposes)

Posted 21 September 2012 - 06:34 AM

I think it would be easier to go from PDO/MySQLi to MySQL, and learning MySQL leads to bad habits (hence the need for prepared statements) so I'd say learn PDO/MySQLi first, and then deal with MySQL if you need to.
Was This Post Helpful? 1
  • +
  • -

#13 Nullified  Icon User is offline

  • New D.I.C Head

Reputation: 13
  • View blog
  • Posts: 49
  • Joined: 18-September 12

Re: PHP Login Script (Learning Purposes)

Posted 21 September 2012 - 06:51 AM

You should drop the php sites that you learned your code from as it looks absolutely horrible. You need to ensure that you use php sessions to keep userdata stored once user is logged in, however prior to that you need to utilize proper methods for escaping your post vars or else you put your db, site and server at risk for sql injections, especially since you are storing passwords in plaintext. look into md5 password encryption as well.
Was This Post Helpful? 0
  • +
  • -

#14 CTphpnwb  Icon User is online

  • D.I.C Lover
  • member icon

Reputation: 2934
  • View blog
  • Posts: 10,138
  • Joined: 08-August 08

Re: PHP Login Script (Learning Purposes)

Posted 21 September 2012 - 07:11 AM

Hashing is good, but md5 can be cracked. Try sha256.
Was This Post Helpful? 3
  • +
  • -

#15 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 5,981
  • Joined: 08-June 10

Re: PHP Login Script (Learning Purposes)

Posted 21 September 2012 - 04:27 PM

View PostCTphpnwb, on 21 September 2012 - 01:34 PM, said:

I think it would be easier to go from PDO/MySQLi to MySQL, and learning MySQL leads to bad habits (hence the need for prepared statements) so I'd say learn PDO/MySQLi first, and then deal with MySQL if you need to.

I don't necessarily disagree with you about that. My point was just that discouraging learning the MySQL API altogether is not a good thing.

View PostKingCuddles, on 21 September 2012 - 11:39 AM, said:

I have always found it exceptionally difficult to find good, reliable benchmarks, and would be very interested in any you have found Atli!

I don't really have any links anymore. I just remember doing research on this in the past, and based on what I read and based on my own tests it seemed pretty clear. I did write a simple benchmark myself, and used that on several servers, but I can't find that code at the moment. - It would be interesting to test it now with mysqlnd enabled.

Nullified said:

... look into md5 password encryption as well.

Just, for the record, as our friend creativecoding likes to point out: "Hash != Encryption".

These days you also have better options than traditional hashing. Like bcrypt. (See the PHP crypt() function, or the Portable PHP password hashing framework.)
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2