Could this pass as a secured lock file? - php

I made a lock file to see whether people are logged in on certain pages and I was curious as to if it is actually secure enough to put live or if people can easily bypass this lock.
Here is my code currently:
<?php
session_start();
if ((isset($_POST['user'])) && (isset($_POST['pass']))) {
$_SESSION['user'] = $_POST['user'];
$_SESSION['pass'] = $_POST['pass'];
}
include("config.php");
if ((isset($_SESSION['user']) && (isset($_SESSION['pass'])))) {
$sql = "SELECT count(*) FROM `users` WHERE user = :name and pass = :pass";
$result = $db->prepare($sql);
$result->bindValue(':name', $_SESSION['user']);
$result->bindValue(':pass', $_SESSION['pass']);
$result->execute();
$number_of_rows = $result->fetchColumn();
if ($number_of_rows !== 1){
echo "ERROR - USER AND PASS DO NOT MATCH";
} else { echo "SUCCESS!"; }
} else { echo "YOU NEVER LOGGED IN!"; }
?>
I feel like since it checks the database for a user and password match that there isn't really any way around this but at the same time I'm somewhat new to PHP and don't really know.

you can add this on top of your code.
<?php
session_start();
if(empty($_SESSION['user']) && empty($_SESSION['pass']))
{
header("location:your_login_page.php");
exit();
}
this code automatically redirect user to login page if they are trying to enter in session or registered member area....

Related

php user login script

<?php
if(isset($_POST['submit'])) {
$UserName = mysql_real_escape_string($_POST['UserName']);
$password = mysql_real_escape_string($_POST['password']);
$checkbox = isset($_POST['remember_me']);
if(user_exists ($UserName, $db_connect)) {
$result = mysqli_query ($db_connect, "SELECT password FROM users WHERE UserName = '$UserName'");
$retrievepassword = mysqli_fetch_assoc($result);
if(md5($password) !== $retrievepassword['password']) {
$alert = "Invalid Password";
} else {
$_SESSION['UserName'] = $UserName;
if($checkbox == "on") {
setcookie("UserName", $UserName, time()+3600);
}
header("location: profile.php");
}
} else {
$alert = "Username doesn't exit in database";
}
}
?>
I've made the following login script which is working fine and now I want to check the user's status before login, if user is active, it will login and if it's request is pending or rejected, it will display an error.
I've done the 1st part and confused about the other part where I've to check for the status.
Can anybody help me according to my code?
I am assuming that you have a column in your DB that stores the user's status.
Sooo .. The answer to your question is, after checking if the username is existing in you DB, check if the status is "active" or not. If no, then just display the error message.
You may think of another way to query your data, like:
SELECT * FROM USERS WHERE USERNAME = 'username' AND PASSWORD = 'password' AND STATUS = true
So that you can determine right away if it is active or not if it does not return anything.
I hope this helps. :)
You can check status after checking valid password and return appropriate message. Try below code :
if(user_exists ($UserName, $db_connect))
{
$result = mysqli_query ($db_connect, "SELECT password,status FROM users WHERE
name = '$UserName'");
$retrievepassword = mysqli_fetch_assoc($result);
if(md5($password) !== $retrievepassword['password'])
{
$alert = "Invalid Password";
}
else
{
//check Status
if($retrievepassword['status'] == 1) //whatever condtion to match
{
$_SESSION['UserName'] = $UserName;
if($checkbox == "on")
{
setcookie("UserName", $UserName, time()+3600);
}
header("location: profile.php");
}
else
{
$alert = "User Not active"; //Message to display
}
}
}
else
{
$alert = "Username doesn't exit in database";
}
There are two ways :
Either add condition in your where to check whether user is active
or not.
Or, once you validated user for correct user/password, then
validate through if condition and navigate to correct page
accordingly.
Also, correct your SQL to use prepared statement.
$stmt = $dbConnection->prepare('SELECT * FROM users WHERE
UserName = ? AND password = ?');
$stmt->bind_param('s', $UserName);
$stmt->bind_param('s', md5($password));
$stmt->execute();
First of all, I would like to point out that you have used $ _SESSION without starting the session. To do this you have to write
session_start();
at the beginning of the code.
To verify that the user is logged in, write this just under session_start():
if(isset($_SESSION['UserName']) or isset($_COOKIE['UserName'])){
header("location: profile.php");
}
If you do not know how to check in profile.php if the user is logging in here is how to do it:
PS: I suggest you create a check.php file so that you just include it in the pages reserved for logged in users.
check.php
if(!isset($_SESSION['UserName']) or !isset($_COOKIE['UserName'])){
// Redirect to login or enter what you want to happen if the user is not logged in
}

isset not returning a value (or at least the right one)

I'm fairly new to PHP and have hit a brick wall. When a user logs in on my site, a session ID is generated and stored in a database, along with the expiration time, user's email and IP. The session ID is also stored in the user's cookies, and expires after 30 minutes of inactivity. When a page is loaded, part of the navbar is determined by whether or not they are logged in, which is determined by whether or not part a cookie is set. My code is shown below.
Change the navbar
<?php
if (isset($_COOKIE['sessionID'])) {
echo "<li><i class=\"material-icons\">account_circle</i></li>";
} else {
echo "<li>Login</li>\n";
}
?>
Log a user in
$sql = "SELECT * FROM users WHERE `email`='$email'";
$query = mysqli_query($conn, $sql);
if (password_verify($password, mysqli_fetch_assoc($query)['password'])) {
$sessionID = uniqid('id_', true);
$sql = "INSERT INTO sessions (`email`, `ID`, `expiration`, `ip`) VALUES ('$email', '$sessionID', '" . date("Y-m-d H:i:s", strtotime("+30 minutes")) . "', '" . $_SERVER['REMOTE_ADDR'] . "')";
setcookie("sessionID", $sessionID);
$_COOKIE['sessionID'] = $sessionID;
mysqli_query($conn, $sql);
header("Location: https://[censor]/");
exit();
} else {
header("Location: https://[censor]/login?success=false");
exit();
}
I know a user has been logged in, at least to a degree, because sessionID shows up on the database and my cookies.
Update
I started using PHP sessions, and after getting them to work once, they appear to have stopped working. My new code is below.
Logging a user in
$sql = "SELECT * FROM users WHERE `email`='$email'";
$query = mysqli_query($conn, $sql);
if (password_verify($password, mysqli_fetch_assoc($query)['password'])) {
$_SESSION['email'] = $email;
header("Location: https://[censor]/");
echo $_SESSION['email'];
exit();
} else {
header("Location: https://[censor]/login?success=false");
exit();
}
And no, I did not forget to start a session, it is started at the very beginning of the file.
Example
<?php
if (isset($_SESSION['email']))
echo "<li><i class=\"material-icons\">account_circle</i></li>";
else
echo "<li>Login</li>\n";
?>
I had the same isset error. I don't know exactly why this is not working but I solved the problem with this:
$val = true;
if(isset($_COOKIE['sessionID'])){
$val = false;
}
if($val == true){
//action 1
}
else{
//action 2
}
I think that should work in your case as well. Or is isset generally not working, if you use it without the else?
it will be better if you use SESSIONS for login; here is a sample code.Here i get the login information from the login form, assign it to respective variables and compare with what is in my DATABASE.`
<?php session_start();
if (isset($_POST['submit'])) {
$username=$_POST['username'];
$password=$_POST['password'];
$username=validate_data($username);
$query="SELECT * FROM users;";
$result=mysqli_query($connection,$query);
comfirm_query($result);
//fetching login info
while ($user=mysqli_fetch_assoc($result)) {
//verifying info
if($user['username']==$username){
if (password_verify($password,$user['password'])) {
/*if success set the session super global variable with indexes
user_id and username with the values gotten from the database*/
$_SESSION['user_id']=$user['id'];
$_SESSION['username']=$username;
redirect_to("admin.php");
}
else{
$_SESSION['login_message']="username or password not correct";
}
}
else
$_SESSION['login_message']="username or password not correct";
}
}
?>
Now to verify login on any page which requires a user to be logged on
<?php
if(!isset($_SESSION['user_id'])){
header("location:login.php");
exit;
}else{
/*continue executing code on page; the else is not really
necessary as if the variable is not set, the user
will be redirected; but if it #is set ,
the just skip (permit me to use this word)
the if and get on with the code*/
}
?>

php/html5 login authentication

I am trying to authenticate a user in a MYsql database. I have tried so many tutorials to just fail every time. I am pasting my code below, I dont care about security or sql injection right now. I am just trying to get this to work so I can go on to my next requirement. If anybody has any links to a GOOD php/html5 login authentication tutorial then please share. I easily was able to create a registration form but this login form is really giving me difficulties.
$id =$_POST['Id'];
$password =$_POST['password'];
$accessdb = "SELECT * from UserData where Id ='$id' and password ='$password";
$authenticate = mysqli_query($conn, $accessdb);
if (mysqli_num_rows($authenticate) == 1) {
session_start();
$_SESSION['auth'] = 'true';
header('location: Profile.php');
}
else {
echo "Wrong log-in credentials";
}
First of all, session_start() should be the very first thing on your page and should be on all the pages you want your user authenticated to get access to.
Then, you need to correct your query $accessdb like so:
$accessdb = "SELECT * FROM userdata WHERE id = {$id} AND password ='{$password}'";
NB: not sure if $id is a number. If it's not, then do: '{$id}' instead of {$id}.
$password =$_POST['password'];
$user = "SELECT * FROM UserData WHERE Id ='$id'";
$authenticate = $conn->query($user);
$row = $authenticate->fetch_assoc();
$hash_password = $row['password'];
$hash = password_verify($password, $hash_password);
if ($hash ==0) {
echo "Something went wrong!!";
header('Location: LogIn.php');
exit();
}
else {
`enter code here`$accessdb = "SELECT * FROM UserData WHERE Id ='$id'
AND password = '$hash_password'";
$authenticate = $conn->query($accessdb);
if (!$row = $authenticate->fetch_assoc()) {
echo "Your username is incorrect, Re-enter CREDENTIALS";
}
else {
$_SESSION['id'] = $id;
header('Location: Profile.php');
}
}

Setting an admin page using sessions and type in sql database?

I have created a website with a functioning login system and in my database in the users table there is a column names type with either standard or admin. I have created a page for the admin only to edit products etc however i'm stuck on how to set it so only the 'admin' can view the page instead of just anyone that is logged in. Heres what I have so far?
admin.php
<?session_start(); ?>
<?php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if($_SESSION['type'] = 'admin'){
//admin content here
{
<?php
if ($_SESSION['type']) = 'standard')
{
echo 'you must be an admin to see this page';
}
?>
loginaction.php
<?php
session_start();
include'connection.php';
$email = trim($_POST["email"]);
$password = trim($_POST["password"]);
$password=md5($_POST["password"]);
if (empty($email) or empty($password)) {
header("Location: homepage.php?form=invalid"); //Redirection information
exit;
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
echo "E-mail is not valid";
header("Location: homepage.php?email=invalid");
exit;
}
$query = "SELECT * FROM users WHERE email= '$email' AND password = '$password' ";
$result = mysqli_query($connection, $query) or exit("Error in query: $query. " . mysqli_error());
if ($row = mysqli_fetch_assoc($result)) {//Then we have a successful login
$_SESSION["authenticatedUserEmail"] = $email;
$_SESSION['ID'] = $row['ID'];
$_SESSION["password"] = $row['password'];
header("Location: homepage.php");
} else {//Login was unsuccessful
echo "User does not exist";
header("Location: login.php?user=invalid");
}
?>
You are not using comaprisons instead setting values for variables in the conditions where you check for the user type.
if($_SESSION['type'] ='admin'){ `should be` if($_SESSION['type'] == 'admin'){
<? session_start(); ?>
<? php
include 'login.php'; // this includes all my login form and login action
include 'connection.php'; // this is my database connection
$query1 = "SELECT type FROM users";
$result = mysqli_query($query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['usertype'];
if ($_SESSION['type'] == 'admin') {
//admin content here
}
if ($_SESSION['type']) == 'standard') {
echo 'you must be an admin to see this page';
} ?>
There are other errors in the code such as not putting the curly braces to end the statements correctly. This code should work, however it is a very unsafe code as anyone with sql injection and good programming knowledge will "tear" your website apart and worse, they steal and manipulate your data.
You should use mysql_real_escape_string() to make the input from users sql injection proof to fairly high extent.
Multiple problems seems in your code too, along with the problem mentioned by #Vish in the answers:
$result = mysqli_query($query1);
Expected a connection link as first argument.
Again:
you are trying to fetch type from the user table. But using usertype in mysqli_fetch_array. Seems it is incorrect. And the $_SESSION['type'] variable is really $_SESSION['usertype'] ?
A modified code.
$query1 = "SELECT type FROM users";
$result = mysqli_query($connection, $query1);
$user = mysqli_fetch_array($result);
$_SESSION['usertype'] = $user['type'];
if($_SESSION['usertype'] == 'admin')
{
//admin content here
}
elseif ($_SESSION['usertype']) == 'standard')
{
echo 'you must be an admin to see this page';
}
P.S: Not sure it will solve your problem

PHP MYSQL question

I am trying to do a simple login with PHP and mysql, and using Sessions as well. I have the code, which should work in theory, however it keeps redirecting me to the login page (refreshing it) instead of taking me to the profile.
$username = $_POST['username'];
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1){
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
$uid = $row[0];
session_register($uid);
header('location:profile.php?conf='.$row[0]);
}
else{
echo 'Wrong username';
}
no it shouldn't work in theory
try this
<?php
$username = mysql_real_escape_string($_POST['username']);
$query = "SELECT `confirmcode` FROM `fb_network`
WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if ($row = mysql_fetch_row($result)){
session_start();
$_SESSION['conf_code'] = $row[0];
header('Location: profile.php');
exit;
} else {
echo 'Wrong username';
}
but there can be other issues, from code you didn't post here r other reasons.
as a matter of fact, only debugging can tell you what's the problem for sure
I would use a user defined function and make it to check the login credentials and return true or false from the function.
you can use something like this.
function check_login ($username, $password) {
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '$username' AND `status`='Confirmed' ";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if( mysql_num_rows($result) == 0) {
return false;
}
if( mysql_num_rows($result) == 1) {
$_SESSION['loggedin'] = "true";
header('location:profile.php?conf='.$row[0]);
return true;
}
}
and then call the function easily and display the appropriate message.
check the following code..
<?php
session_start();
/** If the User is already Logged in then redirect to login.php **/
if(isset($_SESSION['loggedin'])){
header("Location: login.php");
}
else {
if( check_login($_POST['username'], $_POST['password'])) {
header('location:profile.php?conf='.$row[0]);
}
}
althoough the code is not exact but this might be enough to get you going.
I see that your code has only two options - display "wrong code" or redirect to the other page. no place where you are redirecting to the login page?
You need to initiate the session by sessions_start() before the rest of the code.
If you have any sort of 'test' script on the profile page that re-directs you if you're not logged in, it may be that the above code logs you in, but does not carry the session variable correctly to the profile page...and subsequently sends the user back to log in again.
Make sure the session is properly initiated on each page using the variable and make sure they match on both ends.
You have two main problems:
You are not using session_start to tell PHP to start tracking sessions
You are using session_register. session_register requires register_globals to be on, which it hopefully is not in your environment. It also expects its argument to be a string which is the name of the variable you wish to store. You should instead use $_SESSION['uid'] = $row[0];
You should also read about SQL injection, a very serious and common security flaw that your code exhibits.
Here is a corrected version of your code:
<?php
session_start(); //it's fine to just do this by habit at the top of every page
$username = $_POST['username'];
//I added mysql_real_escape_string - please read about "sql injection", as it is a very serious and common problem!
$query = "SELECT `confirmcode` FROM `fb_network` WHERE `username` = '".mysql_real_escape_string($username)."' AND `status`='Confirmed' ";
$result = mysql_query($query);
if (mysql_num_rows($result) == 1) {
$result2 = mysql_query($query);
$row = mysql_fetch_row($result2);
$_SESSION['conf_code'] = $row[0];
//not sure if this is what you weree going for or not
$_SESSION['uid'] = $row[0];
header('location:profile.php?conf='.$row[0]);
}
else {
echo 'Wrong username';
}
Then in profile.php, to check if someone is logged in:
<?php
session_start();
if( ! isset($_SESSION['uid']))
//Not logged in!
if( $_SESSION['uid'] != $_GET['conf'])
//trying to access someone else's page!

Categories