I'm trying to mess around with a simple log in form, that is just for fun. The content is nothing sensitive, but I'm trying to learn SESSION and such. I've created this simple login form, that works fine, but if a user clicks the "home" button which is href'd to process_login.php, they are asked to login again. I'm trying to save the username and password it in a SESSION so if they login, and hit home from any page, it will remember their log in information and not ask them to continuously log in.
I have a form.php script, that uses the POST method, with two textfields, the username and password are saved as "admin" in the process_login.php, and if they match the POST indices from the form, then i'll include content.php. In process_login.php I take the POST data and run it like so :
SESSION_start();
//var_dump($_POST);
$match_username = 'admin' ;
$match_password = 'admin';
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == $match_username && $password == $match_password ){
include 'content.php';
}elseif($username == "" || $password != $match_password){
echo "Please try again.";
}
if(!isset($_SESSION["logged_in"])){
//Run if not set
$_SESSION["logged_in"] = array(1 => array($username => $_POST['username'], $password => $_POST['password']));
};
};
You'll see above that I'm trying to set the SESSION information, but I know i'm not doing it correctly. Once a user logs in, everything works. But if that same user clicks on "home," from another page, it will tell them to "Please try again." I'd like to let the user stay logged in once they are logged in.
All advice is appreciated. Thank you!
Your test of $_SESSION["logged_in"] should not be inside the if(isset($_POST['submit'])) block.
if (isset($_SESSION['logged_in'])) {
include 'content.php';
exit();
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if($username == $match_username && $password == $match_password ){
$_SESSION["logged_in"] = array('username' => $_POST['username'], 'password => $_POST['password']);
include 'content.php';
exit();
} elseif($username == "" || $password != $match_password){
echo "Please try again.";
}
// Put login form here
I changed your $_SESSION["logged_in"] variable. Now it's just a one-dimensional array instead of 2-dimensional, and the keys are the words username and password -- it doesn't make much sense to use variables as keys there.
Related
I'm using php but without database.
When I log in with the wrong username/password, it shows "Incorrect username/password" which is correct.
However, when I access the other webpages without logging in, it also shows "Incorrect username/password" instead of "You must be logged in to access this page".
<?php
$username = "admin";
$password = "its30305";
session_start();
if(isset($_SESSION['username])){
echo "<h1>Welcome ".$_SESSION['username]."</h1>";
}
else{
if($_POST['username] == $username && $_POST['password'] == $password){
$_SESSION['username] = $username;
echo "<script>location.href='mainmenu.php'</script>;
}
elif($_POST['username] != $username || $_POST['password'] != $password){
echo "<script>alert('Username/Password incorrect!')</script>";
echo "<script>location.href='login.php'</script>;
}
elif(!isset($_SESSION['access]){
echo "<script>alert('You must log in to access this page')</script>";
echo "<script>location.href='login.php'</script>;
}
?>
You shouldn't validate login like that but if you want to know about the problem,
check this line:
else if(!isset($_SESSION['access']){
Check $_SESSION['access'] before $_POST and you shouldn't have that problem anymore:
if(!isset($_SESSION['access']){
//Need login to access this page
}else if($_POST['username'] == $username && $_POST['password'] == $password){
//Wrong username or password
}else if ...
I strongly recommend to change structure of your code:
Use PHP forwarding instead of JavaScript forwarding
If you want to forward to the login page when user doesn't have permission to the page, use header like this:
header('location: /login.php');
die();
Always terminate the current script after forward by using die() or exit().
Check if $_POST key is set before using it
make sure $_POST set before, For example:
isset($_POST['username']) && $_POST['username'] == $username
Don't store raw password in your codes
Always store hash password, no matter you are using database or not. If you want to find out what is your password hash you can find it out with:
password_hash("its30305", PASSWORD_DEFAULT);
and you can use it in your code:
$username = 'admin';
$password = '$2y$10$ZSCf.Nlma2mBrKetjqnEB.sdWcBiGJoByhPxwo9wCW8Nvz5Zc7Omm'; //Result of password_hash("its30305", PASSWORD_DEFAULT);
Read about password_hash
Use password_verify to verify your password
You can verify password with password_verify like this:
isset($_POST['password']) && password_verify($_POST['password'],$password)
Read about password_verify.
Show proper message in login page
If you want to show to the user, you need to login to see the page content, you can set a $_SESSION['login_message'] before header(), and check that session in login page. If it is set show proper message on login page and then unset the session. For example:
$_SESSION['login_message'] = 1; //user need to login to see the content
header('location: /login.php');
die();
on login.php:
if (isset($_SESSION['login_message'])){
switch ($_SESSION['login_message']){
case 1:
echo 'Need to login to see the page.';
break;
case 2:
echo 'Wrong username or password.';
break;
}
//saw the message, not need it anymore!
unset($_SESSION['login_message']);
}
Please I need help regarding a PHP error, I want to redirect to different pages with form login input here since I do not how to know how to make an admin backend to redirect users to different pages via database, Here is my PHP
SCRIPT
// Redirect to different page
<?php $userid = $_POST['userid'];
$userpass = $_POST['password'];
if (strcmp($userid, "3495062250") && strcmp($password, "12smith00") ) {
header('location: account-dashboard/client_349506_2243/index.html');
} else{ header('location: error.html'); } ?>
Please check below code.
You did mistakes.
In if condition you have used $password instead of $userpass
You can simply compare the string using equal operator in PHP
$userid = $_POST['userid'];
$userpass = $_POST['password'];
if ($userid = "3495062250" && $userpass == "12smith00") {
header('location: account-dashboard/client_349506_2243/index.html');
} else {
header('location: error.html');
}
I have implemented a simple php Web application and uploaded it to Aruba hosting.Now my login function(which regularly works on local host) does not work anymore on the hosting,but if i try to register as a new member the record on the database is added as it should be.Anyone can give me a hint??
this is the login code
require_once "../blogics/classes/Administrator_class.php";
require_once "../blogics/administrators_services.php";
if (isset($_POST['email']) && isset($_POST['password']) && strlen($_POST["email"])>0 && strlen($_POST["password"])) {
session_start(); // Starting Session
$email=$_POST['email'];
$password=$_POST['password'];
$email=trim($email);
$password=trim($password);
$email = stripslashes($email);
$password = stripslashes($password);
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
// SQL query to fetch information of registerd users and finds user match.
$mdpass=md5($password);
$flag=0;
$admin=administrators_login($email,$mdpass);
if($admin){
$_SESSION['administrator_session']=$email; // Initializing Session
//echo "email login";
header("location: landing.php"); // Redirecting To Other Page
}else{
//echo "NO login";
header("location: login.php?error=2");
}
}else{
header("location: login.php?error=1");
}
?>
obviously at the top of landing.php there is session.start()
EDIT:
After some attempts i discovered that the problem is in reading the "password" field from database. I can't understand why the problem exists only with "password" field and with every "password" field of the existing tables. If someone has an idea of what could it be..i don't really know what to do.
I know this subject has been covered a ton, and I have looked and searched so I think I am missing something basic.
I have a Username Password log in system that is setup as:
Login page: set to Action - checklogin.php
checklogin.php - checks against the database for username and password, and then in the header brings them to their custom URL, which is in column 3 of the database. So user1 goes to folder1/, user2 goes to folder2/, etc.
It seems to work fine, but lets say I am logged in as user1 (URL /folder1/), it allows me to enter '/folder2/' in the URL window, and that folders index file comes up.
So basically if I am logged in any username, I can pull up the other users folder/index.php file.
So I think somehow the code on the index.php page is not validating the users correctly.
CODE (top is fine, connecting to DB, etc, so I left that out) :
checklogin.php:
// Define $username and $password
$username=$_POST['username'];
$password= $_POST['password'];
// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row
if($count==1){
// Register $username, $password and redirect to file "index.php"
session_start();
$_SESSION[$username];
$_SESSION[$password];
$_SESSION['loggedin'] = true;
$_SESSION[$id];
$row = mysql_fetch_assoc($result);
$result = mysql_query("SELECT folder FROM users2");
$_SESSION['folder'] = $row['folder'];
if( isset($username) ) {
$_SESSION["loggedin"] = true;
$_SESSION["username"] = $username;
header('Location: clients/'. $row['folder'].'/index.php');
exit();
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
}
?>
On the receiving URL index.php page:
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
// not logged in, move to login page
header("location:../../login.php");
exit;
}
I have tried many other variations of the receiving "Protect Page" code, but none seem to work correctly. Is it the receiving code or the checklogin code??? I feel I am missing something obvious.
Thanks in advance, any take on this will be appreciated. - Randy
You need to add additional checks in the protected pages; not only do you need a logged-in user, you also need to check the requested path and see if the user has access to that.
Something like (for example...):
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true
|| stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false) {
// not logged in, move to login page
header("location:../../login.php");
exit;
}
Apart from that you should never store plain-text passwords and you should really switch to PDO (or mysqli) and prepared statements with bound variables.
Edit: Another solution to make clear what is happening:
session_start();
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
// not logged in, move to login page
header("location:../../login.php");
exit();
}
elseif (stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false)
{
// $_SESSION['folder'] is not found in the path,
// not user's folder, go to own folder
header('Location: /clients/'. $_SESSION['folder'].'/index.php');
exit();
}
else
{
// show page of user
}
your using a lot of unnecessary !==
replace most of those with !=
also change
if($count==1){
to
while($count>=1){
change
if( isset($username) ) {
to
if( isset($username) && $username != "" && $username != NULL ) {
Var_dump $result, make sure it contains what you want, you've got it listed two times.
when you reference a variable inside a session I'd recommend double/single quoting it.
Do yourself a favor and avoid magic quotes and mssql() entirely. Switch to pdo or MYSQLI
if (!isset($_SESSION['loggedin']) |$_SESSION['loggedin'] !== true)
if (stripos($_SERVER['REQUEST_URI'], $_SESSION['folder']) === false)
{
// not logged in, move to login page
header("location:../../login.php"); exit; } – RandyS just now edit
So i'm writing a simple login script and I ran into some problems. I was able to create the login.php file that works with this dashboard.php file below. Let me describe the scenario: User come into the main page, which is the login page. Enters username and password. If entered correctly user will see the output "dashboard succesfull". If entered wrongly it will redirect them to loginfailed.php. Problem is that the browser does not remember that the user has already been logged in. If I re-enter this page, it will directly goes to loginfailed.php. So my obivous n00b question here is......is there a way to make the browser remember that the user has already been logged in?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripslashes($password);
$dblink = mysql_connect("localhost", "root", "");
mysql_select_db("user",$dblink);
$sql = "select * from members where username = '$username' and password = '$password'";
$result = mysql_query($sql) or die ( mysql_error() );
$count = 0;
while ($line = mysql_fetch_assoc($result)) {
$count++;
}
if ($count == 1) {
$_SESSION['loggedIn'] = "true";
echo "<a href='dashboard.php'>dashboard succesfull</a>";
} else {
$_SESSION['loggedIn'] = "false";
header("Location: loginfailed.php");
}
?>
Sure. You just need to put, at the top of the page but below session_start(), something like:
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] == 'true') {
# do something. maybe redirect and then exit?
}
Also, I'd suggest using a session name and escaping the username and password before putting them in your SQL.