Login with php
Moderators: egami, macek, gesf
I'm new to PHP, so be gentle with me. I'm setting up a members' area on my website. I've created the login page and a MYSql table to hold the authorised users usernames and passwords, I've drafted a php file to access the database (it works) and to validate the username and password (that works too).
Now I display a message saying either "valid user" or "invalid username or password", depending on input. I want to change that so that a successful login will open a members' page, and an unsuccessful one will re-display the login page.
I've been trying various examples I've found online, but I'm really confused about things like Session and Location. Can someone explain in simple words how to do it?
Thanks.
Now I display a message saying either "valid user" or "invalid username or password", depending on input. I want to change that so that a successful login will open a members' page, and an unsuccessful one will re-display the login page.
I've been trying various examples I've found online, but I'm really confused about things like Session and Location. Can someone explain in simple words how to do it?
Thanks.
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
Are you using sessions at all yet (you will need to)?
Also can you post the code you have so far so we can help better.
Also can you post the code you have so far so we can help better.
I tried to introduce some code to start a session, but it didn't work, hence my question. This is the current version:
<?php
$uname = $_POST["user"];
$upassword = $_POST["upword"];
$link = mysql_connect('host.com', 'name', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully. ';
mysql_select_db(members1);
$sql="SELECT * FROM members WHERE user='$uname' and password='$upassword'";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
if
($row["user"]==$uname && $row["password"]==$upassword)
{
echo"You are a valid user.";
}
else{
echo "$row";
echo"Sorry, your credentials are not valid, Please try again.";
}
?>
<?php
$uname = $_POST["user"];
$upassword = $_POST["upword"];
$link = mysql_connect('host.com', 'name', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully. ';
mysql_select_db(members1);
$sql="SELECT * FROM members WHERE user='$uname' and password='$upassword'";
$result=mysql_query($sql);
$row = mysql_fetch_array($result);
if
($row["user"]==$uname && $row["password"]==$upassword)
{
echo"You are a valid user.";
}
else{
echo "$row";
echo"Sorry, your credentials are not valid, Please try again.";
}
?>
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
OK, that helps and this is what you need to do (I am presuming your column for each user id is called id and that you want to store just the username and id in the session but you will need to change to your requirements)
Code: Select all
<?php
session_start(); // MUST be at the top of every page where you need to use sessions and be before any other code in the page
$uname = mysql_real_escape_string(trim($_POST["user"])); // Prevention of sql injection
$upassword = mysql_real_escape_string(trim($_POST["upword"]));
$link = mysql_connect('host.com', 'name', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully. ';
mysql_select_db(members1);
$sql=mysql_query("SELECT id FROM members WHERE user='$uname' and password='$upassword' LIMIT 1");
$result=mysql_fetch_array($sql);
if ($result) {
$_SESSION['username'] = $uname;
$_SESSION['user_id'] = $result['id'];
header('location: members_page.php');
} else {
// If this PHP is in the same page as your login
echo"Sorry, your credentials are not valid, Please try again.";
//If this PHP is in its own page
header('location: login.php');
}
?>
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
OMG!!! Makes a change to help someone 'local'brocsman wrote:PS. Some coincidence - I live in Telford!

By the way, I recommend SHA1 for password encryption

Now I really am confused. I edited your code, and embedded it in my html file. After I realised I needed to put the session_start as the first line, it worked. Once. Stupidly I made one or two minor changes to get my css working without keeping a working version, and now it fails to load the location file (another html file) again. I know I am logged in to the database, and my login details have been identified as correct, but the file I am calling doesn't open. What am I doing wrong?
So my html file opens with:
<?php session_start(); ?>
Then there is some html,then the remainder of the php:
<?php
$uname = mysql_real_escape_string(trim($_POST["user"])); // Prevention of sql injection
$upassword = mysql_real_escape_string(trim($_POST["upword"]));
$link = mysql_connect('host', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully. ';
mysql_select_db(members1);
$sql=mysql_query("SELECT id FROM members WHERE user='$uname' and password='$upassword' LIMIT 1");
$result=mysql_fetch_array($sql);
if ($result) {
$_SESSION['username'] = $uname;
$_SESSION['user_id'] = $result['id'];
echo "Hi";
header('location: members.html');
} else {
// If this PHP is in the same page as your login
echo"Sorry, your credentials are not valid, Please try again.";
}
?>
So my html file opens with:
<?php session_start(); ?>
Then there is some html,then the remainder of the php:
<?php
$uname = mysql_real_escape_string(trim($_POST["user"])); // Prevention of sql injection
$upassword = mysql_real_escape_string(trim($_POST["upword"]));
$link = mysql_connect('host', 'username', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully. ';
mysql_select_db(members1);
$sql=mysql_query("SELECT id FROM members WHERE user='$uname' and password='$upassword' LIMIT 1");
$result=mysql_fetch_array($sql);
if ($result) {
$_SESSION['username'] = $uname;
$_SESSION['user_id'] = $result['id'];
echo "Hi";
header('location: members.html');
} else {
// If this PHP is in the same page as your login
echo"Sorry, your credentials are not valid, Please try again.";
}
?>
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
You cannot output anything before using header('location: ....'); so in your code, this
Needs to be this:
i.e. remove the echo
Code: Select all
echo "Hi";
header('location: members.html');
Code: Select all
header('location: members.html');
Sorry to be a pain. I only put the echo in to test if my username and password were being picked up correctly. I've just taken it out again, with the same result. I get "Connected successfully" but the location page doesn't open. As I said earlier it did once, but then stopped. Weird.
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
As I say, you cannot output any data before using header location so remove your echo about the database connection as well and see what happens.
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
Are your pages .php as I notice that the link to members is .html? They need to be php files to work.
Have you got error reporting turned on and if so do you get any errors?
Is it just the redirect to the members page that isn't working?
Have you got error reporting turned on and if so do you get any errors?
Is it just the redirect to the members page that isn't working?
Thanks for your patience. I said I was new to php.
I'll convert them to php files later today, and try again. Everything else works, (I originally put the echo in to make sure my username and password were being tested correctly), but not the redirect.
As for error reporting, I am using Dreamweaver. I haven't found out how to get error reporting. If it's possible can you tell me how?
Thanks again.
I'll convert them to php files later today, and try again. Everything else works, (I originally put the echo in to make sure my username and password were being tested correctly), but not the redirect.
As for error reporting, I am using Dreamweaver. I haven't found out how to get error reporting. If it's possible can you tell me how?
Thanks again.
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
If you put this right at the top of your php it should work for you
Code: Select all
ini_set('display_errors',1);
error_reporting(E_ALL);
I know it's not possible, but I've just tried it again. Haven't changed anything, and it has opened my header file correctly. I'm in a hotel with only thirty minutes wi-fi access, so I'm going to close everything very carefully, and try again at home tomorrow.
Thanks for the tip about error trapping. I'll keep you informed.
Thanks for the tip about error trapping. I'll keep you informed.
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
Very
Have you definitely posted all of the code involved and can you test in anything else besides DW?

Have you definitely posted all of the code involved and can you test in anything else besides DW?
As I said earlier, it seems to work sometimes, but not others. I tried inserting the code you suggested, and these are the error messages I got. No idea what they mean
Notice: Use of undefined constant sfg_members1 - assumed 'sfg_members1' in /hermes/waloraweb012/b688/moo.shropshirefungusgrou/loginphp130113.php on line 51
Warning: Cannot modify header information - headers already sent by (output started at /hermes/waloraweb012/b688/moo.shropshirefungusgrou/loginphp130113.php:21) in /hermes/waloraweb012/b688/moo.shropshirefungusgrou/loginphp130113.php on line 61
Warning: Unknown(): open(/var/php_sessions/sess_3d8fa9df16eea3af20281d4142e1790f, O_RDWR) failed: No such file or directory (2) in Unknown on line 0
Warning: Unknown(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/php_sessions) in Unknown on line 0
Notice: Use of undefined constant sfg_members1 - assumed 'sfg_members1' in /hermes/waloraweb012/b688/moo.shropshirefungusgrou/loginphp130113.php on line 51
Warning: Cannot modify header information - headers already sent by (output started at /hermes/waloraweb012/b688/moo.shropshirefungusgrou/loginphp130113.php:21) in /hermes/waloraweb012/b688/moo.shropshirefungusgrou/loginphp130113.php on line 61
Warning: Unknown(): open(/var/php_sessions/sess_3d8fa9df16eea3af20281d4142e1790f, O_RDWR) failed: No such file or directory (2) in Unknown on line 0
Warning: Unknown(): Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/php_sessions) in Unknown on line 0
One more point. When I open a browser, and call the login page either from DW or from the server, with a valid username and password, the header file opens successfully. If I try again using the back button with another username it still successfully recognises that the input is valid, but it fails to open the file, and I get the messages shown above.
Breakthrough?
Hope you are still listening, and haven't given up on me yet. I'm wondering if my problem is that I'm starting a session, so the login works first time, but then I try to repeat it without ending the session, which I haven't yet learned to do.
I've changed my header file, and the first time I call the PHP I get my header page, and can access content. It fails if I try to go back, but I wonder if I need to end the session before I can try again with a different username.
I did say I was new to PHP.
If you think I might be right, can you point me to a good PHP online reference, because I really haven't got one yet.
Thanks for your help to date, whatever happens.
Hope you are still listening, and haven't given up on me yet. I'm wondering if my problem is that I'm starting a session, so the login works first time, but then I try to repeat it without ending the session, which I haven't yet learned to do.
I've changed my header file, and the first time I call the PHP I get my header page, and can access content. It fails if I try to go back, but I wonder if I need to end the session before I can try again with a different username.
I did say I was new to PHP.
If you think I might be right, can you point me to a good PHP online reference, because I really haven't got one yet.
Thanks for your help to date, whatever happens.
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
I haven't given up 
I have just set up your code on my computer and just cannot replicate your problems for the basics of the login so it must be something else in your code that is causing you issues (for example when you used the error reporting it came back with an error in lines 51 and 61 and I don't know what code you have there.
What I have done (and works and doesn't matter if not logged out as each time the code is run it just gets and sets the new data, though this is obviously not good practice) is below (just the basic login form and php which I would suggest you try without anything else to make sure it works as expected).
One other thing I would recommend is encrypting your passwords in the database using sha1 or md5.

I have just set up your code on my computer and just cannot replicate your problems for the basics of the login so it must be something else in your code that is causing you issues (for example when you used the error reporting it came back with an error in lines 51 and 61 and I don't know what code you have there.
What I have done (and works and doesn't matter if not logged out as each time the code is run it just gets and sets the new data, though this is obviously not good practice) is below (just the basic login form and php which I would suggest you try without anything else to make sure it works as expected).
Code: Select all
<?php
session_start();
$link = mysql_connect('host.com', 'name', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$selected = mysql_select_db("members1",$link)
or die("Could not select database");
if (!empty($_POST)) {
$uname = mysql_real_escape_string(trim($_POST["user"])); // Prevention of sql injection
$upassword = mysql_real_escape_string(trim($_POST["upword"]));
$sql="SELECT id FROM members WHERE user='".$uname."' and password='".$upassword."' LIMIT 1";
$query = mysql_query($sql) or die(mysql_error());
$result=mysql_fetch_array($query);
if ($result) {
$_SESSION['username'] = $uname;
$_SESSION['user_id'] = $result['id'];
header('location: members.php');
} else {
// If this PHP is in the same page as your login
echo"Sorry, your credentials are not valid, Please try again.";
}
}
?>
<!doctype html>
<html>
<head></head>
<body>
<form name="login" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="username">Username</label>
<input type="text" id="username" class="required" name="user" value="<?php if(isset($_POST['user'])) { echo $_POST['user']; } ?>">
<label for="password">Password</label>
<input type="password" id="password" class="required" name="upword" value="">
<input type="submit" value="Login">
</form>
</body>
</html>
I apologise for returning to the same topic, but my code now works to my satisfaction, if somewhat basically, in both Firefox and Chrome, but it is clear that in IE the session fails to start, despite valid input. I included isset(), which has removed the error messages I was getting previously, so no clues as to why there is a difference. I am using IE V9 64 bit. Is there something I need to know about IE?
- simplypixie
- php-forum Active User
- Posts: 300
- Joined: Sun Dec 11, 2011 12:51 am
- Location: Shrewsbury, Shropshire
- Contact:
Can you post the code you now have