I have adpopted some code to create a login, checklogin, successful login, failed login and logout pages. The checklogin page essentially checks the username and password posted from login. If these are correct you end up at successful login page. However I want to say something like 'Welcome John' on the successful login page, but dont know how to get the username from the session so that I can base a query on this to pull back the logged in persons name. The checklogin page is:
<?php require_once('Connections/Connection1.php'); ?>
<?php
//$host="localhost"; // Host name
//$username=""; // Mysql username
//$password=""; // Mysql password
//$db_name=""; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
//mysql_connect("$host", "$username", "$password")or die("cannot connect");
//mysql_select_db("$db_name")or die("cannot select DB");
mysql_select_db($database_Connection1, $Connection1);
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=md5($_POST['mypassword']);
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE userid='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:main.php");
}
else {
header("location:login_failed.php");
//echo "Wrong Username or Password";
}
?>
Then on my successful login page, how do I echo the username? or at least refer to it in a query to then pull back the additional information like name?
Many thanks!!
When I need to do this, I usually use php's $_SESSION array and set quick look up information in there, such as a name that might be displayed on multiple pages.
$_SESSION['username'] = $username;
$_SESSION['firstname'] = $firstname;
$_SESSION['lastname'] = $lastname;
$_SESSION['user_id'] = $id;
This gives me access to all these variables on any page that calls session_start() at the start of the php page.
On a sidenote -
using MD5 hashing passwords IS NOT SECURE! Learn how to use crypt() function with salts. It will be good practice and make your database much more secure. Unfortunately MD5 is not much more secure than plaintext at this point with people having easy access to rainbow tables and programs like ocl-hashcat.
Please look into using PDO or mysqli for your database calls. mysql_ functions are deprecated.
Changed the code a bit, this is safer..
<?php
session_start();
// Sanitize $_POST['myusername'] and $_POST['mypassword'] before loading into session variables to protect from MySQL injection
$_SESSION["myusername"]=!empty($_POST['myusername'])?mysql_real_escape_string(stripslashes($_POST['myusername'])):"";
$_SESSION["mypassword"]=!empty($_POST['mypassword'])?mysql_real_escape_string(stripslashes($_POST['mypassword'])):"";
// Load database variables, connect to server and select a database
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
mysql_connect($host, $username, $password)or die("Cannot Connect for Reason:".mysql_error());
mysql_select_db("$db_name")or die("Cannot Select DB for Reason:".mysql_error());
// Run query
$result=mysql_query("SELECT username FROM $tbl_name WHERE username='".$_SESSION["myusername"]."' AND password='".$_SESSION["mypassword"]."'");
// Check for return of single record and direct to login_success.php
if(mysql_num_rows($result)==1){header("location:login_success.php");}
else{
// On login falier, unset session variables if not needed and redirect
unset($_SESSION["myusername"]); // Optional if return value not needed or wanted
unset($_SESSION["mypassword"]); // Optional if return value not needed or wanted
header('refresh: 5; url=./login_fail.php');
die("Wrong Username or Password. Redirecting..."); // To prevent evil people manipulating the page, kill the script using die.
}
?>
To echo the user on another page: echo $_SESSION['myusername'];
You have two options...
Either you can retrieve it on main.php page as $_SESSION['myusername'];
Or, you can use pass it to main.php as header("location:main.php?username=".$myusername);
And then on main.php, you can retrieve it as $_GET['username'];
Related
I am working on a log-in system, Whenever the user tries to access the non-authorized page
then he should return on the login page to login, how can I perform it
Below is my log-in script
<?php
session_start();
$host="localhost"; // Host name
$db_username="root"; // Mysql username
$db_password=""; // Mysql password
$db_name="designshop"; // Database name
$tbl_name="member"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$db_username", "$db_password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$member_username=$_POST['member_username'];
$password=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$member_username = stripslashes($member_username);
$password = stripslashes($password);
$member_username = mysql_real_escape_string($member_username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE member_username='$member_username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
$_SESSION['member_username']=$_POST['member_username'];
$_SESSION['password']=$_POST['password'];
header("location:login_success.php");
}
else {
header("location:try_again.html");
}
?>
All you have to do is to check for the existence (and non-emptiness) of $_SESSION['member_username']. If it is set, that means that your user is logged in, and therefore, there is no need for him to relog.
Notes:
There is no need to store the user's password in session: in fact, its better not to.
You do your authentication through MySQL, which means that you store the password in cleartext: this is a bad practice. It would be better to retrieve both username and password from the database based only on the username, and do the comparaison in your PHP code: this would allow you, for example, to store sha1'd password.
Just put this at the top underneath session_start()...
if(!empty($_SESSION['member_username'])){header("location: login_success.php");}
Like so...
session_start();
if(!empty($_SESSION['member_username'])){
header("location: login_success.php");}
$host="localhost"; // Host name
$db_username="root"; // Mysql username
$db_password=""; // Mysql password
//REST OF CODE
start code with session_start() and check if the session is set whenever any user trying to access the page, if session is set then redirect to the page otherwise redirect to login page
you can check using isset()
follow this code...
<?php session_start();
include('conn.php');
$Name = $_POST['login_id'];
$Pass = $_POST['password'];
$select="select * from admin_login where admin_name='$Name' AND admin_pwd='$Pass'";
$query=mysql_query($select) or die($select);
$rows=mysql_fetch_array($query);
$row=mysql_num_rows($query);
if($row != 0)
{
$_SESSION['admin_name']=$rows['admin_name'];
echo "<script>window.location.href='index.php'</script>";
}else
{
$message = 'Invalid Username Or Password';
echo '<script type="text/javascript">alert("'.$message.'")</script>';
echo "<script>window.location.href='login.php'</script>";
}
?>
put this code to the top of the every page
<?php session_start();
if(isset($_SESSION["admin_name"])=='') print('<script>window.location.href="login.php"</script>');
I have a checklogin.php script that works fine to redirect a user to a specific page on successful login. I now want to set it to redirect to the original index.php page that redirected the user to the login form. At the top of index.php I include:
<?php
session_start();
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
if(!session_is_registered(myusername)){
header("location:main_login.php");
}
?>
I have checked that $_SESSION['url'] is getting correctly set on this page.
main_login.php just contains the login form which is processed by checklogin.php:
<form name="form1" method="post" action="checklogin.php">
and $_SESSION['url'] is getting correctly set on this page too.
checklogin.php looks like this:
<?php
session_start();
print_r($_SESSION['url']);
ob_start();
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Define $myusername and $mypassword
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$encrypted_mypassword=md5($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:$_SESSION['url']");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>
As you can see I am trying to print $_SESSION['url'] at the top of this script but nothing is getting returned.
Could someone help with this?
Thanks,
Nick
You cannot insert a "complex" variable like $_SESSION['url'] inside a litteral string, like the following statement:
header("location:$_SESSION['url']");
In my version of PHP (5.3.10), it produces the following error:
PHP Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE,
expecting T_STRING or T_VARIABLE or T_NUM_STRING in
/home/.../test.php on line ...
Indeed, if you want to output a field in an array, you should use concatenation:
header("Location: " . $_SESSION['url']);
This may be the source of your problem. Depending on PHP configuration, it may not display the error and just output a blank page, check the php logs to be sure.
The best practice is to use this whenever you want to output the value of a variable in a string.
For example, do not use echo "Foo: $foo";, use instead echo "Foo : ". $foo;
I'm having a little trouble implementing a login system that both allows users to be rememebered via cookie but at the same time not allow unauthorized access using site URL
here is my code for successful_login, the problem lies here as I get a redirect error:
<?php
session_start();
// IF USER NOT REMEMBERED OR NO SESSION THEN THROW HIM OUT TO LOGIN
if (!isset($_SESSION['valid'])|| !isset($_COOKIE['myusername']))
{
header("Location: index.php");
}
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="*****"; // Mysql password
$db_name="secure_login"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql);
?>
the session works but as soon as I close the browser and reopen it to my site I get a REDIRECT LOOP
here is the code that processes my form:
<?php
session_start();
//CHECK IF EITHER SESSION OR COOKIE EXISTS THEN REDIRECT TO LOGIN_SUCCESS ELSE CONTINUE TO FORM
function loggedin()
{
if (isset($SESSION['valid']) || isset($_COOKIE['myusername']))
{
$loggedin = TRUE;
return $loggedin;
}
}
if (loggedin())
{
header("Location: login_success.php");
}
// REST OF CODE IS PROCESSED AFTER USER CLICKS SUBMIT ON LOGIN FORM
if(isset($_POST['submit']))
{
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="*****"; // Mysql password
$db_name="secure_login"; // Database name
$tbl_name="users"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
$rememberme=$_POST['rememberme'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$encrypted_mypassword=md5($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$encrypted_mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
if(mysql_num_rows($result) == 1) //user exists
{
if ($rememberme=="on"){
setcookie("myusername", $myusername, time()+7200);
}
elseif ($rememberme==""){
$_SESSION['valid'] = 1;
}
header('Location: login_success.php');
exit();
}
if($myusername=="phillip.k#fixnode.ca" && $encrypted_mypassword=="a66d83940f5d22fa54ee51ce"){
header('Location: register.php');
}
else {
echo '<div class="alert">Incorrect Username or Password!</div>';
}
}
?>
so basically to wrap up, when a user enters a valid username and password AND clicks remember me then I like for the browser to redirect to login_success even if the user closes the browser (i.e. COOKIE from remember me button). But right now if a user closes a browser and reopens my site then the user gets a REDIRECT LOOP probably because of the cookie
ANY help is greatly appreciated
Phillip K
The problem is here:
if (!isset($_SESSION['valid'])|| !isset($_COOKIE['myusername']))
Instead of ||, you should have &&. You never have them both set in the same time, hence the redirection loop.
Another problem I found quickly is you never seem to update the cookie "myusername" when user visits the page.
As suggested, you could use an existing solution but if you really want to do it yourself I would highly suggest splitting that code into reusable functions/classes.
Md5 is not a safe way to store user passwords, you should use bcrypt or similar existing solution.
I would also confirm the IP between each page visit as a countermeasure against session hijacking (this would require storing the session data on a database which is a good idea anyway).
I would recommend a ready-to-use authentication solution.
For example http://pear.php.net/package/Auth. Have a look into the examples
I am trying to get a form to submit and check a login but it's not going from A to B, can anyone see any problems with the code please?
Here is to Form part:
<form action="check_login.php" name="form1" method="post">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider" role="heading" tabindex="0">Member login</li>
<li><input type="text" name="myusername" id="myusername" value="Email" /></li>
<li><input type="password" name="mypassword" id="mypassword" value="Password" /></li>
<li><button type="submit" name="login-submit" id="login-submit" data-icon="arrow-r" data-iconpos="right">LOG ON</button></li>
</ul>
</form>
And here is part 2 (checks the login ... doesn't seem to get here.
<?php
$host="localhost"; // Host name
$username="usernamehere"; // Mysql username
$password="passwordhere"; // Mysql password
$db_name="dbnamehere"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or
die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and
password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
session_register("myusername");
session_register("mypassword");
//header("location:login_success.php");
echo 'login success';
}
else {
echo "Wrong Username or Password";
}
?>
For more information on the login part of the code, please look here:
http://devlup.com/programming/php/toa-simple-php-login-form-mysql/200/
Any questions, please ask.
Thanks.
Final Update
For future visitors, I assume this is the answer that eventually solved the problem:
Relative paths, like the one used in the form action, always start looking in the current directory.
In the original question, the form was submitting to action="check_login.php" This means that the browser will submit the data to http://www.domain.tl/wherever/theform/was/check_login.php.
If you need to submit forms to other locations, you need to either specify absolute paths (http://www.domain.tl/handler.php) or you need to understand directory traversal, and indicate the correct path (../../handler.php).
Update
What is your file structure? Is the form html in the same place as the handler php?
To be clear it should be /{parent}/form.html and /{parent}/check_login.php. Is that the case?
You said you are not getting any data in $_POST. Does this mean it is getting TO check_login.php but not working, or not getting to it at all?
Original
I'll update this with an answer to your real question after we get more info about what is happening here, but I wanted to post this so you would make sure to see it.
It seems like you have a few poor coding practices and, while I'm certainly not a pro, I feel like I can offer some improvements. See the revised code block below.
<?php
$host="localhost"; // Host name
$username="usernamehere"; // Mysql username
$password="passwordhere"; // Mysql password
$db_name="dbnamehere"; // Database name
$tbl_name="members"; // Table name
//Ideally, your database information is stored in another file, and you include it here.
//Mostly, it's just so you're not having to change it in multiple places if it changes
//but there could be a small security benefit, too
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or
die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
//What if the $_POST vars don't exist?
//$myusername=$_POST['myusername'];
//$mypassword=$_POST['mypassword'];
//Try:
$myusername = isset($_POST['myusername']) ? $_POST['myusername'] : null;
$mypassword= isset($_POST['mypassword']) ? $_POST['mypassword'] : null;
//then you should check if the variables exist
if( $myusername == null || $myusername == "" || $mypassword == null || $mypassword == "" )
{
echo "You need to fill in both fields.";
}
// To protect MySQL injection (more detail about MySQL injection)
//why are you forcing php to write to that variable twice?
//$myusername = stripslashes($myusername);
//$mypassword = stripslashes($mypassword);
//$myusername = mysql_real_escape_string($myusername);
//$mypassword = mysql_real_escape_string($mypassword);
//Try:
$myusername = mysql_real_escape_string(stripslashes($myusername));
$mypassword = mysql_real_escape_string(stripslashes($mypassword));
//As another person said, you desperately need to store hashed passwords
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
//This is a terrible idea.
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
//from #Jimmy Sawczuk
//This is deprecated, since a while ago.
//session_register("myusername");
//session_register("mypassword");
//Try:
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
//header("location:login_success.php");
echo 'login success';
}
else {
echo "Wrong Username or Password";
}
?>
In the $_SESSION edit right at the end there, the larger question is: why are you saving those variables. If you're needing the password in the Session at a later time, you're doing your app security wrong.
Not sure if this is related but the button element causes problems in IE:
http://www.sitepoint.com/forums/html-xhtml-52/button-submit-input-submit-better-598656.html
Also, try
print_r($_POST);
before you do anything else to see if you're getting anything.
I have the following code. Now when I press the login button nothing happens and the username and password are cleared.
<?php
session_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="csduc"; // Database name
$tbl_name="students"; // Table name
// Connect to server and select databse.
$connect=mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['username'];
$mypassword=$_POST['password'];
// To protect MySQL injection (more detail about MySQL injection).
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql,$connect);
$row=mysql_fetch_array($result);
// Mysql_num_row is counting table row.
//$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row.
if($row)
{
// Register $myusername, $mypassword and redirect to file "login_success.php".
session_register("myusername");
session_register("mypassword");
header("location: main.php");
}
else
{
echo "Wrong Username or Password";
}
?>
How can I solve this?
The correct name for the header is "Location" (with a capital 'L'). This may or may not matter. Also, technically, the Location header requires an absolute URL (eg. "http://example.com/main.php") -- some browsers will accept a relative url, but the spec requires the absolute url. Again, this may or may not be causing your problem.
So, to be more "technically correct" your redirect could be changed to something like this:
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/');
header("Location: http://$host$uri/main.php");
check out the php documentation page for the header() function for more details.
Your form tag has a problem.
It needs to be as follows:
<form method="POST" action="">
Assuming action is the same page as the code above. Otherwise point the action to the page that has the code in it. Make sure the code is at the very top of the page, otherwise session start and header won't work
For testing use
echo $myusername=$_POST['username'];
echo $mypassword=$_POST['password'];
exit;
and use sql as because password may be encoded
$sql="SELECT * FROM $tbl_name WHERE username='$myusername'";
$result=mysql_query($sql,$connect);
$row=mysql_fetch_array($result);