Password protect a page?(with db access) - php

Couple questions here: My end goal is to password protect the file logged_in.php.
Note: I'm only a beginner/intermediate programmer so i would like clear explanations, please.
First off, i have set a username and password within a database table.
I have two pages: login.php and logged_in.php(names are just for example purposes). How do i "require" a user to first go through login.php(the log in process) in order to gain access to logged_in.php(if the entered username/password are correct)?
Is this the best way to password protect a page?
What i've tried:
Login.php:
<?php
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
header("location:logged_in.php");
}
else
header("location:bad_login.html");
}
?>
The problem with my code at the moment is that, someone can directly type in the URL of logged_in.php and access the page without being "required" to go through login.php first(i'm sure this is obvious to everyone..).
I put require(login.php); at the top of logged_in.php; however, that didn't work out.
I've checked google for some good tutorials on this topic, unfortunately i couldn't find any that had clear explanations.
I also saw a few other questions regarding this topic on stackoverflow, but they didn't really help me out.
I'm also interested in being able to pass-protect my page using the method phpMyAdmin uses(when you type in the URL and press enter it drops down a menu from the top of the browser asking for a username/password). I don't know how that works. If someone can tell me how that works i'm willing to completely disregard the method i'm attempting to use at the moment(if the phpMyAdmin method is secure enough and is fairly easy to implement).
Thanks in advance!

Use $_SESSION variable:
<?php
session_start();
$db_host="host";
$db_user="user";
$db_pass="pass";
$db_name="name";
$db_table="table";
mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
$user = mysql_real_escape_string(strip_tags($_POST['user']));
$pass = mysql_real_escape_string(strip_tags($_POST['pass']));
if(isset($user) && isset($pass))
{
$sql = "SELECT * FROM $db_table WHERE username='$user' AND password='$pass'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['username'] = $user;
header("location:logged_in.php");
exit();
}
else
header("location:bad_login.html");
exit();
}
?>
logged_in.php:
<?php
session_start();
// check if $_SESSION was setting before
if (!isset($_SESSION['username']))
{
header("Location: login.php?e=access_denied");
exit();
}
?>
The phpMyAdmin login is different because use the MySQL username and password to login, so phpMyAdmin does not need to create a database and table to login like your code
Also you need the logout:
logout.php
<?php
session_start(); // <-- Oops!!
// unset all $_SESSION variables
session_unset();
session_destroy();
header("Location: logged_in.php?m=logout_success");
exit;
?>

Related

Unable to protect pages/area with password

I'm trying to create a password protected area of a website.
I'd like to allow access by checking username and password from a MySql table, then start a session and allow access to a number of pages while the session is active. If someone tries to directly access one of these pages directly, I'd like to redirect them to login page.
My code for the login page is:
if (isset($_POST['submit']))
{
include("config.php");
session_start();
$username=$_POST['username'];
$password=$_POST['password'];
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
$_SESSION["username"] = $user;
echo "<script language='javascript' type='text/javascript'> location.href='admin_view.php' </script>";
}else{
echo "<script type='text/javascript'>alert('User Name Or Password Invalid!')</script>";
}
}
It seems to work (correctly redirects if username and password matches, shows alert if not).
What I fail to do, is actually protect my pages from display if session is not active.
session_start();
if (!$_SESSION["username"]) {
header("Location: login.php");
}
I'm not a programmer or fully-educated web developer. I know HTML and CSS, and I'm barely able to use ready-to-use php and js scripts following readme files.
Any help would be greatly appreciated.
modify your login code as
if (isset($_POST['submit']))
{
include("config.php");
$username= $crud->escape_string($_POST['username']);
$password= $crud->escape_string($_POST['password']);
$passwordc=md5($password);
$query = "SELECT username FROM admin WHERE username='$username' AND
password='$passwordc'";
$result2 = $conn->query($query);
if ($result2->num_rows != 0) {
session_start();
$_SESSION["username"] = $user;
header("Location:admin_view.php");
}else{
$Message = urlencode("user name password invalid!");
header("Location:login.php?Message=".$Message);
}
}
if your values successfully stored in session then you can use like
session_start();
if(!isset($_SESSION['username']))
{
header("Location: login.php");
}
on everypage top
you must store name from query into session

php login system do not stop or send any error messages when users login incorrectly

When I coded my php login system (In MySQLi), I get an error that do not actually checks if username or password is wrong, idk what to do abot this. Please help me out here.
<?php
// If logged in
if(isset($_SESSION['user_id'])) {
header('Location: index.php');
}else {}
//error_reporting(0);
//MySQLi Login form
//Database connection
$con = mysqli_connect('localhost', 'root', '', 'console');
//Actual Login form
if(isset($_POST['login'])) {
session_start();
//Explainging details
$username = $_POST['username'];
$password = $_POST['password'];
//Fetching data
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(MYSQLI_BOTH);
//Logging in
$_SESSION['user_id'] = $row['user_id'];
header('Location: index.php');
}else{
$wrong = 'Username or password is wrong';
}
?>
Also i got a check.php that redirects you to /notloggedin.php if not logged in, but IF the user is logged in it will display their User_ID, but when user logsIn with wrong details then go to check.php it does not show anything and it does not redirect the users to /notloggedin.php.
So what do I do with that? Is there something I forgot to add, or something i did wrong???Can you write a example if you have any ideas?? Thanks.
EDIT:
Now instead of using MySQLi I got an idea from #christoandrew, so i made everything into functions. What the functions tells the system to do is its gonna check for the username first, if the username exists its gonna make a $_SESSION()for the username. Then again using the $_SESSION() to find the User_ID to the username then its gonna look for the password for the same User_ID. Then when its checked everything it will destroy all 'Sessions' it made and create a $_SESSION() for all information like User_ID, Email, Username, Password, Etc... Thanks for all the help i got in my way!
if(isset($_POST['login'])) {
session_start();
//Explainging details
$username = $_POST['username'];
$password = $_POST['password'];
//Fetching data
$result = $con->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$row = $result->fetch_array(MYSQLI_BOTH);
// Try checking if there are actually rows that are returned
// If the rows are greater than zero then the user exists else the
// user supplied wrong credentials
if(mysqli_num_rows($row) > 0){
//Logging in
$_SESSION['user_id'] = $row['user_id'];
header('Location: index.php');
}else{
$wrong = 'Username or password is wrong';
}
// The else block below is not necessary and the validation is misplaced
}
you need start the session:
session_start();

Allow content with $_Session

I've been following some tutorials and managed to get my login and logout scripts working. What I"m now trying to do it get it to only allow access to pages when the user is logged in. Right now it's just redirecting users to the login page every time, which tells me that the session isn't being set or or my code is just wrong (and I've tried everything I can think of)
This is the login.php script that my form runs in order to set the session:
<?php
// establishing the MySQLi connection
require 'init.php';
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])) {
$username = mysqli_real_escape_string($conn,$_POST['username']);
$pass = mysqli_real_escape_string($conn,$_POST['password']);
$sel_user = "select * from login where username='$username' AND password='$pass'";
$run_user = mysqli_query($conn, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0) {
$_SESSION['username']=$username;
echo "<script>window.open('index.php','_self')</script>";
} else {
echo "<script>alert('Sorry. Your username or password is not correct, try again!')</script>";
}
}
?>
And this is what I'm including at the top of every page:
<?php
session_start();
if (!(isset($_SESSION['username']) && $_SESSION['username'] != '')) {
header ("Location: account-login.php");
}
require 'init.php';
?>
I switched the login.php file from directing to a page to a popup telling me that I logged in and I get the popup, so the user and password are registering fine, it's just not storing the session somehow. Any ideas? Thanks!
OK, so I got it to work finally!
Apart from all the comments (which helped a TON), I also decided to change the name I was setting in $_SESSION. I think it may be because the session name matched the name or POST data and that eas causing a conflict somewhere.
Changed this:
$_SESSION['username']=$username;
Which I think conflicted to this:
$_SESSION['session_id']=$username;
Worked!
THANK YOU!!!!!!!

Cookies aren't working

I tried to do use cookies to remember login information but the cookies never seemed to "take" as it were. Here's the initial login script:
//try to login using cookies, but first make sure it doesn't have a $_SESSION variable for it
if (!(isset($_SESSION['valid_user']))) {
if (isset($_COOKIE["login"])) {
//try to login using cookie
$query = "select from cookie_users where uniqueid = '".$_COOKIE["login"]."')";
$conn = new mysqli('localhost', 'user', 'password', 'test');
$result = $conn->query($query);
if ($result->num_rows>0) {
$result->fetch_assoc();
$result['username'] = $username;
$result['password'] = $password;
//try to login using password and username from cookie database
$query = "select * from authorized_users where username = '".$username."' and password = '".$password."'";
$result2 = $conn->query($query);
if ($result->num_rows>0) {
$_SESSION['valid_user'] = $username;
}
}
}
}
if (isset($_POST['userid']) && isset($_POST['password'])) {
// if the user has just tried to log in
$userid = $_POST['userid'];
$password = $_POST['password'];
$db_conn=new mysqli('localhost', 'user', 'password', 'test');
if (mysqli_connect_errno()) {
echo 'Connection to database failed: '.mysqli_connect_errno();
exit;
}
$query = 'select * from authorized_users '."where name='$userid' "."and password=sha1('$password')";
$result = $db_conn->query($query);
if ($result->num_rows > 0) {
//if they are in the database, register the user id
$_SESSION['valid_user'] = $userid;
//set up cookie
setcookie("login", $uniqueid, time()*60*60*24*14);
$query = "insert into cookie_users values ('".$userid."', sha1('".$password."'), '".$uniqueid."')";
$result = $db_conn->query($query);
if (!$result) {
echo 'Could not update cookie in database';
}
}
$db_conn->close();
}
Members only content:
if (isset($_SESSION['valid_user'] {
echo "members only content goes here";
} else {
echo "you need to login"; }
The sessions and login scripts work just fine. If they login directly using the login page, it shows up. If they go to another page and then come back, it still works; so that leaves me to believe that the sessions work just fine. However, if you close down the browser and come back, it doesn't register. If something's messed up with the script, please let me know. Either way, I did a test script and not even that works. Here it is:
<?php
setcookie("test", "the test is good", time()*60*60);
?>
<html>
<body>
<?php
echo $_COOKIE["test"];
?>
</body>
</html>
So I think I'm missing something fundamental. Sorry if the answer is painfully obvious, cookies are new to me. Thanks for any help you guys can give.
Your problem is in this line:
setcookie("login", $uniqueid, time()*60*60*24*14);
Here, you're multiplying the time instead of adding to it. You've multiplied it by enough to exceed the MAX_INT size (see Y2038). For whatever reason, Apache (at least, on my system) will ignore that header and the browser will then keep it only for the length of the session. Fortunately, you can fix the problem fairly simply:
setcookie("login", $uniqueid, time() + 60*60*24*14); // Adding two weeks, not multipying by >9000

Login coded in PHP just refreshes over and over?

Using PHP and MySQL to make a login/registration system. Registration is in and I'd say it works alright. However, I'm having some problems with the login page.
No matter what, it just kind of refreshes the page and I'm not sure what's wrong. Here's the loginaccount.php script I have running on the form:
**
EDIT:
**
Thanks for the help so far guys! But I'm still running into a pretty annyoing problem. Now, no matter what, it still doesn't log in, even though now I'm actually getting the error message I set up. Updated code below:
<?php
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
session_start();
$username = $_POST[‘username’];
$password = md5($_POST[‘password’]);
$query = "select * from registerusers where username='$username' and password='$password'";
$result = mysql_query($query);
if (mysql_num_rows($result) == 0) {
$error = "Incorrect login, please try again.";
include "login.php";
echo "<span class=error_message>".$error."</span>";
} else {
$_SESSION['username'] = "$username";
include "login.php";
echo "<span class=success_message>Welcome! You are now logged in.</span>";
}
?>
I can't post comments on questions yet, but I've got a possible reason for your problem.
Since you're only including (and not redirecting) the users to a page, the login page will just stay where it is and just keep including the files - doing the same things over and over. Try header('Location: memberspage.php') instead.

Categories