Another attempt at designing a user membership. Got to log in successfully, finds the data in the database. But in my index file, after logging in, it should check if I'm logged in and display links to my account instead of register and login. Here's the code:
<?php
session_start(); // Must start session first thing
// See if they are a logged in member by checking Session data
$toplinks = "";
if (isset($_SESSION['id'])) {
// Put stored session variables into local php variable
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '' . $username . ' •
Account •
Log Out';
} else {
$toplinks = 'Register • Login';
}
?>
And here is the login form code, where I think the problem is because it's not storing my session id:
<?php
if ($_POST['email']) {
//Connect to the database through our include
include_once "connect_to_mysql.php";
$email = stripslashes($_POST['email']);
$email = strip_tags($email);
$email = mysql_real_escape_string($email);
$password = preg_replace("[^A-Za-z0-9]", "", $_POST['password']);
// filter everything but numbers and letters
$password = md5($password);
// Make query and then register all database data that -
// cannot be changed by member into SESSION variables.
// Data that you want member to be able to change -
// should never be set into a SESSION variable.
$sql = mysql_query("SELECT * FROM users WHERE email='$email' AND password=
'$password'AND emailactivated='1'");
$login_check = mysql_num_rows($sql);
if($login_check > 0){
while($row = mysql_fetch_assoc($sql)){
// Get member ID into a session variable
$userid = $row["id"];
$_SESSION['id'] = $userid;
// Get member username into a session variable
$username = $row["username"];
$_SESSION['username'] = $username;
// Update last_log_date field for this member now
mysql_query("UPDATE users SET lastlogin=now() WHERE id='$userid'");
// Print success message here if all went well then exit the script
header("location: member_profile.php?id=$userid");
exit();
} // close while
} else {
// Print login failure message to the user and link them back to your login page
print '<br /><br /><font color="#FF0000">No match in our records, try again
</font> <br/>
<br />Click here to go back to the login page.';
exit();
}
}// close if post
?>
Once again I'm following someone's tutorial and trying to implement it to my website and this would be perfect if it worked. Please advice why the $toplinks aren't being set after logging in.
I think the problem is, that you have to include the session_start() in every file where you want to use your session. Otherwise its working in the file like a normal array but not global. In your form i can't see that you start your session.
Edit: You need this only if you have 2 files. When you have only one file and include the other page its working when you include in once on top.
If you want to log out, then you should create a logout file, and include
session_destroy();
probably add also a href to get redirection link by doing something like:
header('location:index.php'); // will return you to index as soon as you logout.
Related
I'm attempted to create a login authentication system using PHP. So far I've managed to query the DB to check if a username/password given by the user matches any rows in the DB. However I have a column in the DB named "isadmin" which stores a boolean value. I want to implement a check if true/false. Depending on the result depends on which php file is loaded (included).
EDIT: I have two php files, both containing the same HTML displaying the index page of a website. However, one php file is for regular users, the other is for admin users which will contain added features. When a user enters their username and password, I want a check for the user level of that login, Once the check is done it should show the appropriate php page.
$stmt = $pdo->prepare('SELECT * FROM Reg_User WHERE username = :username AND password = :password');
$details = [
'username' => $_POST['username'],
'password' => sha1($_POST['password'])
];
unset($_POST['submit']);
$stmt->execute($details);
if ($stmt->rowCount() > 0) {
$user = $stmt->fetch();
$_SESSION['loggedin'] = $user['user_id'];
echo 'Logged in as ' . $_POST['username'];
include 'index.php';
}
else {
echo 'Sorry, your username and password could not be found Please <a href="login.html">try again
or register!</a>';
}
A simple if/else statement will do it.
if ($user["isadmin"]) {
echo "Logged in as an admin.";
#you can include your related php page here.
} else {
echo "Logged in as an user.";
#you can include your related php page here.
}
There's no sanitizing of user input in your code, this is a must in a login system, try this after your login form.
info: I don't use PDO, $con is the MYSQLI connection.
<?php
// Handle log in
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// Sanitize username input
$username = strip_tags($username);
$username = trim($username);
$username = mysqli_real_escape_string($con, $username);
$username = urldecode($username);
// Sanitize password input
$password = strip_tags($password);
$password = trim($password);
$password = mysqli_real_escape_string($con, $password);
$password = urldecode($password);
}
?>
Your site should be set to https only, if it is ignore this link: htaccess redirect to https://www and you should be providing either a secure session cookie or a secure persistent cookie for users who are able to log in successfully. The code underneath this paragraph should be at the very top of your page before any html. This example is for time related persistent https secure cookie set to 1 day after which it will expire. You could use a session cookie but I find this annoys people if they frequent your site quite often, they don't want to have to log in again the same day if they close and reopen a browser or tab.
<?php
// All this code goes right at the top of your page before anything else!
function addcookie() {
global $condition;
if ($condition == "green") {
global $nameofcookie;
setrawcookie('loggedin', $nameofcookie, strtotime('+1 day'), '/', '', isset($_SERVER["HTTPS"]), true);
echo "<script>window.location.replace('https://example.com/mypage');</script>";
}
}
?>
The above code is will set a secure cookie using a function because you only want it firing after a successful login. The name of the cookie really should be random and unique, something based on microtime would work well. Make sure it's not anything important which could identify the user!IMPORTANT: the name of the cookie for reference should be created at the time of account creation and added to the users table so you can identify users and represent their login details.
Standard security measures should also include a separate table of the ip, time, date and username of who logged in. If your site is busy the table will fill quickly so you could set a cron job to clean old records to keep the size down, in that case you will need to add a column for datetime to identify the age of records.
Handling the login...
<?php
$condition = "red";
if (isset($_POST['login'])) {
$select_login = "select * from Reg_User where username='$username' and password='$password'";
$connect_login = mysqli_query($con, $select_login);
$rows_login = mysqli_num_rows($connect_login);
if ($rows_login == 0) {
// code here to handle failed logins, I would record them and use a 3 strike method
}
// Handle successful logins, add cookie
else {
while ($row_login=mysqli_fetch_array($connect_login)) {
// Retrieve cookie name here from table
$nameofcookie=$row_login['cookie'];
$condition = "green"; // This allows you to add the cookie
addcookie();
}
}
}
?>
Retrieving the cookie to authenticate users...
<?php
if (isset($_COOKIE['loggedin'])) {
$cookie = $_COOKIE['loggedin'];
$select_authenticated_user = "select * from Reg_User where cookie='$cookie'";
$connect_authenticated_user = mysqli_query($con, $select_authenticated_user);
while ($row_authenticated_user=mysqli_fetch_array($connect_authenticated_user)) {
// Retrieve values here from table
$logged_in_user=$row_authenticated_user['username'];
$logged_in_admin=$row_authenticated_user['isadmin'];
// Resolve admin status
if ($logged_in_admin == TRUE) {
$type = "admin";
} else {
$type = "member";
}
}
// Echo statement for logged in user with admin or not status, you could change the echo to a variable name if you want to use this in a specific place on your page.
echo "Welcome $logged_in_user<br/>
Type: $type
";
}
?>
Here's a link for obtaining IP's: How to get the client IP address in PHP
I am creating a login for a website. I can get the code below working: It lets me log in! Yet I can't get a start session to work: People can still get to my pages via URL.
Log in PHP:
<?php
//calling connection to database
include "connection.php";
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
Start session code which says undefined variables:
<?php
include"includes/loginrequiredb.php";
if($_SESSION['username'] !=$user){
session_destroy();
header("Location: view.php");
die();
}else
{
echo "welcome to the site you have logged in" . $_SESSION['username'];
}
?>
Without starting the session you can not get the values from $_SESSION.
You just need to start session in your both files as:
session_start();
Note that you need to start_session() in both files only in just welcome file.
Side note:
I suggest to also use isset() for checking either value set or not.
Start the session with session_start and Add a session verification file in adminmain.php page.
<?php
//calling connection to database
include "connection.php";
#session_start();
//session
//if user posts for called login
if(isset($_POST['login'])){
//declaring variables for user input and using escape string to protect php scripts
$user = mysqli_real_escape_string($dbconn,$_POST['user']);
$pass = mysqli_real_escape_string($dbconn,$_POST['pass']);
//select from users table where user input matches un and pw
$sel_user = "SELECT * from users where un='$user' AND pw='$pass'";
//put content held in sel_user into variable run_user
$run_user = mysqli_query($dbconn, $sel_user);
//use run_user counting rows and save in check_user
$check_user = mysqli_num_rows($run_user);
//if content row numbers greater than 0
if($check_user>0){
//session where un is equal to user input stored in $user
$_SESSION['username']=$user;
//display admin main page
header('Location: ../adminmain.php');
}
else {
//display log in error page
header('Location: ../loginerror.php');
}
}
//close database connection
mysqli_close($dbconn);
?>
##### file verify.php #####
<?php #session_start();
if (#$_SESSION['username']!=$user) {
header ("location: index.php");
exit;
}
?>
I have got this strange problem. I wanted to make a page which uses a Username to identify which content should be displayed. It seems to work fine, except for one thing. The wrong value is read from the session on one specific page. I have checked the session value in my browser, but there the value seems to be correct. I'll show you the code:
this is my login function, using php:
<?php
//CONNECT TO DATABASE
$db = mysqli_connect("localhost","root","MyPassword","MyDBName");
if($db->connect_errno){
die('connection error: ' . $db->connect_errno);
}
//CHECK IF LOGIN DATA IS SUBMITTED AND IS CORRECT
if(isset($_POST['action'])){
switch($_POST['action']){
case "login":
$pw = $_POST['pw'];
$loginUn = $db->real_escape_string($_POST['loginUn']);
$result = mysqli_query($db,"SELECT `Password` FROM `accounts` WHERE `Username`='" .$loginUn. "'");
if(mysqli_num_rows($result) != 0){
$dbpw = $result->fetch_object();
$VI = explode("-",$dbpw->Password);
$dbpw = openssl_decrypt($VI[1],"blowfish","",0,$VI[0]);
if($pw == $dbpw){
$login = true;
$_SESSION['login'] = true;
$_SESSION['Username'] = $_POST['loginUn'];
$un = $_POST['loginUn'];
}
}
break;
case "logout":
$_SESSION['login'] = false;
$_SESSION['Username'] = "";
break;
}
}else{
if(isset($_SESSION['login'])){
$login = $_SESSION['login'];
$un = $_SESSION['Username'];
}
}
?>
it seems to work fine, since it works in the page it is used.
I have made some dummy accounts in the database, with these usernames: Admin and User.
Here is the code of the page it went wrong:
PHP:
//THIS IS NOT THE SAME PAGE AS THE PREVIOUS PHP CODE
$login = false; //CHECK IF USER HAS LOGGED IN
$un = "";
if(isset($_SESSION['login'])){
$login = $_SESSION['login']; //IF LOGGED IN SET TO SESSION VALUE
$un = $_SESSION['Username']; //SET $UN TO USERNAME IN SESSION
}
Then I used javascript and php to alert the values which the variables contain:
<script type="text/javascript">
alert("$un = <?php echo $un;?>");
</script>
With the login variable seemed to be no problem, since it had the good value, but the variable $un was wrong. When I wasn't logged in, it had no value, which is correct, but when I was logged in, it contained the value Admin, even when I wasn't logged in with Admin. In the browser options the cookie value seemed correct. I've checked the cookie on every page, and it worked just fine, just not on this page. What am I doing wrong that makes the browser(which is firefox by the way) think that it is always Admin that is logged in?
As mentioned earlier in the comments, there are many security risks in your script.
You should take a look at PHP's sessions to build your login. Using sessions, there will be only one cookie storing an ID and all the data will be stored on your server and can't be modified by the user.
Your problem with 'Admin' staying as cookie value could be a caching problem.
I just found out what I did wrong. A piece of code which I found irrelevant, missed a = so the variable wasn't compared, but set to this wrong value.
i have created a session after my login page and wanted to redirect to a secure page with session i created earlier.. but my session data is not pass.. may i know wat is the problem..
php session:
$em = $_POST['email'];
$pw = $_POST['password'];
$em = mysql_real_escape_string($em);
$pw = mysql_real_escape_string($pw);
$query = "SELECT * FROM Register WHERE email = '$em' AND pass = '$pw'";
$result = mysql_query($query) or die("Unable to verify user because : " . mysql_error());
if (mysql_num_rows($result) > 0) {
session_start();
// store session data
$_SESSION['login']=$em;
//echo 'Connected';
// Jump to secured page
echo "<script>window.location='http://example.com/secure.php'</script>";
}
the page i redirected to:
<?php session_start(); $_SESSION['login']; ?>
<p>Welcome
<?php
//retrieve session data
echo $_SESSION['login'];
?>
to M-Cloud</b>
Firstly.
Make sure that the session_start is at the top of the pages. That is the best practice.
Make sure the $em has a value when the SESSION is being set.
Check that the web hosting you use supports SESSIONS.
And at the top of the second page, you don't need to have the $_SESSION['login']; bit
To test that $em definitely has a value. echo it out on that page to check.
If this does not work, please paste more of the code so we can find the problem.
You can remove the first $_SESSION['login']; on the second page, then show the whole $_SESSION array with print_r($_SESSION); to see if the value is correct or not.
I'm trying to make a login and logout script for a page but for some reason its not working very well for me. it seems to work fine until I try to logout. it seems to destroy the session variables, but it still lets me view the page.
heres my login code:
Code:
login.php
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
////// Logout Section. Delete all session variable.
session_destroy();
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match.
{
session_register("uname"); // Craete session username.
header("location:loged.php"); // Re-direct to loged.php
exit;
}else{ // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
// End Login authorize check.
?>
logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['uname']);
// Delete all session variables
session_destroy();
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
}
?>
thanks to every one...
You are setting the session, but you are not checking it any where that whether it is set or not. means you are not checking that user is logged in or not.. you need to do like this
if (!isset($_SESSION['uname'])) /*If uname not set then it is a guest*/
{
//page contents for guest user
}
else
{
//page for authenticated user.
}
session_register() is deprecated as of PHP 5.3.0. Replace:
session_register("uname"); // Craete session username.
with:
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
Log out with (replacing session_destroy()):
////// Logout Section.
unset($_SESSION['uname']);
The final result will look like:
<?php
// Use session variable on this page. This function must put on the top of page.
session_start();
// Logout Section
if (isset($_SESSION['uname']))
unset($_SESSION['uname']);
// Login Section
$Name=$_POST['Name'];
$Pass=$_POST['Pass'];
// To protect MySQL injection (more detail about MySQL injection)
$Name = stripslashes($Name);
$Pass = stripslashes($Pass);
$Name = mysql_real_escape_string($Name);
$Pass = mysql_real_escape_string($Pass);
$sql="SELECT * FROM reg1 WHERE uname='$Name' and pass='$Pass'";
$result=mysql_query($sql);
if(mysql_num_rows($result)!='0') // If match. {
$row = mysql_fetch_assoc($result);
$_SESSION['uname'] = $row['uname'];
header("Location: loged.php"); // Re-direct to loged.php
exit;
} else { // If not match.
echo '<script type="text/javascript">
window.alert("Wrong UserName And Password");
window.location="index.php"
</script>';
}
?>
Logout script (syntax error fixed and session_destroy(); since unnecessary):
<?php
// Inialize session
session_start();
// Delete certain session
if (isset($_SESSION['uname'])) {
unset($_SESSION['uname']);
}
// Jump to login page
header("Location: index.php?msg=Successfully Logged out");
?>
How to check if logged in:
session_start();
if (isset($_SESSION['uname']))
{
// logged in
}
else
{
// not logged in
}
In your page that you want to be accessed only by logged in user, do you check the value of $_SESSION['uname'] ?
I think only session_destroy(); function is good enough to log you out. You need not to unset the 'uname'. And for those pages that will come after user logged in then you must apply some session check functionality at the top of each page...
if uname is the value you use to validate if the user is logged you should try to put first:
session_destroy(); and then the unset($_SESSION['uname'])
I hope this works for you....