I have generated a php file that has information stored in a database. To access this a person must use a login in page.
However, when you are using MAMP how can you prevent someone from accessing the file through writing the IP address and php file name e.g. 123.456.78.00:80/fileone.php. I want this fileone.php to be hidden and for them to only access it through a login page.
Thanks in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: ' . $page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Login check
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true) {
"Your script"
}
If you have a profile for your users, like a normal user = 0 and an admin = 1 you can do it like this
if(isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true && $_SESSION['profile'] == 1) {
"Your script"
}
Set sessions
To set set the sessions to true you need this
if(isset($_POST['submit'])) {
$_SESSION['loggedIn'] = true;
// for set a profile
$_SESSION['profile'] = 1;
}
Maybe I didn't understand you good, but to be sure I will explain something:
You said attached checklogin.php, but you can't use that to deny access for non members. If they know that the file exists, they can type it in the URL and still read fileone.php. The first coding block need to be in your fileone.php.
Session time
Search in your php.ini for 'session.gc_maxlifetime'. There will be a number and that is the time in seconds.
Related
I have a problem with multi-level user login in PHP MySQL. I already have a code but the user still can access the admin site, what's the problem with my code? still, I do have a problem with the session of admin and user acct. thank you! here's my code.
require('db.php');
session_start();
if (isset($_POST['username'])){
$account = stripslashes($_REQUEST['account']);
$account = mysqli_real_escape_string($con,$account);
$username = stripslashes($_REQUEST['username']); // removes backslashes
$username = mysqli_real_escape_string($con,$username); //escapes special
characters in a string
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking is user existing in the database or not
$query = "SELECT * FROM users_detail WHERE account = '$account',username=
'$username' and password= '$password' ";
$result = mysqli_query($con,$query);
$rows = mysqli_num_rows($result);
if($account == "admin" && $rows['username'] = $username &&
$rows['password']=$password){
$_SESSION['username'] = $username;
header("Location: index.php"); // Redirect user to index.php
}
if($account == "user" && $rows['username'] = $username &&
$rows['password']=$password){
$_SESSION['username'] = $username;
header("Location: add user.php"); // Redirect user to index.php
}else{
echo " <div class='alert'>
Username/password is incorrect. Click <a href = 'login.php'>here</a> to log-in.
</div> ";
}
}else{
?>`
here is the full solution,
1 , in your user table you need to create a column call user_role
every user in the table either admin or normal_user
2 in your log.php , first fetch data base get the user_role value , when you verify user password and db password , save as session .
<?php
if( isset($_POST['login_btn'])){ // someone click login btn
$username = clean($_POST['username']);
//clean is the custom function to remove all harmful code
$password = clean($_POST['password']);
// run query to get db username & password i am using prepare stmt for more secure , you can use mysqli_fetch_array , but need to implement mysql_real_escape_string for sql injection
$stmt = mysqli_prepare($connection,"SELECT username,password,email,user_role FROM your table WHERE username = ? ");
//$connection is your db connection
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $bind_username,$bind_password,$bind_email,$bind_user_role);
confirm($stmt); // confirm is also custom function to check query is successful execute
while (mysqli_stmt_fetch($stmt)) {
$db_username = $bind_username;;
$db_password = $bind_password ;
$db_email = $bind_email ;
$user_role = $bind_user_role ;
}
// do form validation
if($username =="" or $password =="" ){
echo 'All Fileds Are Required';
}elseif( $username !== $db_username ){
echo 'username not existed';
}else{
if( password_verify($password, $db_password)){
// assuming your using password_hash function to verify , or you can just use simply compare $password == db_password
// if password_verify return true meaning correct password then save all necessary sessions
$_SESSION['username'] = $db_username ;
$_SESSION['user_email'] = $db_email ;
$_SESSION['user_role'] = $user_role ;
// first method -> header('Location: portal.php');
// you can now direct to portal page{1st method } where all admin or normal user can view
// or you can now do separate redirection (2nd method below )
// remember $user_role will == 'admin' or 'normal_user'
if( $user_role == 'admin' ){
header('Location: page_admin_will_view.php');
}elseif( $user_role == 'normal_user' ){
header('Location: page_normal_user_will_view.php');
}
}else{
echo 'incorrect password';
}
}
} // end of post request
?>
3 how about normal user accidentally visit the admin page ?
we have consider this and do some extra work
put below code in the page_admin_will_view.php header
<?php
if( isset($_SESSION['user_role'] )){
// meaning user is logged in
if( $_SESSION['user_role'] !== 'admin'){
// meaning user_role is not amind , redirect to the page normal user belongs to
header("Location: ../normal_users.php");
}
} else{
//redirect to somewhere meaning user is not logged in
header("Location: ../somewhere.php");
}
?>
I hope this would help you , and I am using it, it may not be a perfect solution. but it works for me. hah
mysqli_num_rows($result) returns the number of rows.
So after $result = mysqli_query($con,$query); you need to write fetch data using mysqli_fetch_array($query)
What you are talking about is RBAC(Role Base Access Control).
if($account == "admin" && $rows['username'] = $username && $rows['password']=$password){
$_SESSION['username'] = $username;
$_SESSION['access'] = $account;
}
And on your pages where you want admin access, probably you should either redirect the user to home or send an UnAuthorised access message.
if(isset($_SESSION['access']) && $_SESSION['access'] != 'admin') {
header("Location: index.php");
}
Also if you are looking for more controlling based on the role I will suggest you to use a library like
http://phprbac.net/
first of all , create admin role like you did with $account
when user login save their admin_role in session ,
$admin_user = $_SESSION['admin_user'] ;
$normal_user = $_SESSION['normal_user'] ;
in admin site , like admin.php , the page you do not want normal user view
write this {perfectly write it in header.php}
if(isset($_SESSION['username'])){
//meaning user is logged in
if(isset($_SESSION['admin_user']) or isset($_SESSION['normal_user'])){
if( $_SESSION['admin_user'] !== 'admin_user' ){
header('Location: somewhere.php');
}
}
}else{
//meaning user is not logged or session had terminated
header('Location: index.php');
}
Seems like you're trying to implement role-based access control on your website.
Here is a possible implementation using prepared statements:
<?php
// db.php should create a mysqli insance:
// $con = new mysqli("host", "username", "password", "databaseName");
require('db.php');
session_start();
if (isset($_POST['username']) && isset($_POST['password'])) {
//Checking is user existing in the database or not
$query = "SELECT * FROM users_detail WHERE username = ? and password = ?";
//use prepared statement
$stmt = $con->prepare($query);
$stmt->bind_param('ss', $_POST['username'], $_POST['password']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows !== 0) {
//fetch user from database.
$user = $result->fetch_assoc();
//check if user is an admin.
if($user['account'] === "admin") {
$_SESSION['username'] = $username;
header("Location: admin.php"); //admin's page
}
//check if user is a normal user.
if($user['account'] === "user") {
$_SESSION['username'] = $username;
header("Location: user.php"); //user's page
}
} else {
echo '<div class="alert">Username/password is incorrect. Click here to log-in.</div>';
}
//free memory used by the prepared statement.
$stmt->close();
} else {
//username and password not provided.
}
?>
I have php scripts that confirm the password and username of a customer matches those that are stored in a database (username and password are stored in a users database). Once they login they will be redirected to their own page, but after a period of minutes inactivity I want them to be logged out, or redirected to the login.php. Can anyone help with a tried and tested method? Thank you in advance.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root","root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if($exists > 0) //IF there are no returning rows or no existing username
{
while($row = mysql_fetch_assoc($query)) //display all rows from query
{
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if(($username == $table_users) && ($password == $table_password)) // checks if there are any matching fields
{
if($password == $table_password)
{
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
//echo $table_id;
//echo $page_id;
redirect ($page_id); //take the user to the page specified in the users table
}
else
{
echo "Login Failed";
}
}
else
{
Print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
}
else
{
Print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
Print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: home.php');
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
Add this to your pages :
setcookie(session_name(), $_COOKIE[session_name()], time() + 15 * 60); // 15 is the number of minutes of inactivity before the session gets destroyed
This tells the session that it has still X minutes left before dying.
In your page heading, add a meta that will redirect the user after a giving time
<meta http-equiv="refresh" content="900;url=logout.php" />
Below are the following scripts, the first one is checklogin.php. This matches up the username and password that is stored in MYSQL database. Once this information has been checked they will get sent to their personal page by using a redirect function.
The bottom php script is user1's landing page. I want something on there that will confirm that this person has correctly logged in and is not entitled to view this page.
At the moment, when i log in as user1 i get shown the page 3.php, i.e. it's saying that i am not correctly logged in. I know i need to set up a session like:
$_SESSION[logged in'] == 'y';
and i think this should go where the passwords are being compared to what is stored in the database. At the moment I cannot enter my login details and be directed to the correct file at the end. Any help will be much appreciated.
<?php
session_start();
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
mysql_connect("localhost", "root", "root") or die(mysql_error()); //Connect to server
mysql_select_db("first_db") or die("Cannot connect to database"); //Connect to database
$query = mysql_query("SELECT * from users WHERE username='$username'"); //Query the users table if there are matching rows equal to $username
$exists = mysql_num_rows($query); //Checks if username exists
$table_users = "";
$table_password = "";
if ($exists > 0) {
//IF there are no returning rows or no existing username
//$_SESSION['logged in'] == 'y';
while ($row = mysql_fetch_assoc($query)) {
//display all rows from query
$table_users = $row['username']; // the first username row is passed on to $table_users, and so on until the query is finished
$table_password = $row['password']; // the first password row is passed on to $table_users, and so on until the query is finished
$table_id = $row['id'];
$page_id = $row['page'];
}
if (($username == $table_users) && ($password == $table_password)) {
// checks if there are any matching fields
if ($password == $table_password) {
$_SESSION['user'] = $username; //set the username in a session. This serves as a global variable
$_SESSION['logged_in'] = 'y';
//echo $table_id;
//echo $page_id;
redirect($page_id); //take the user to the page specified in the users table
} else {
echo "Login Failed";
}
} else {
print '<script>alert("1. Incorrect Password!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
} else {
print '<script>alert("Incorrect Username!");</script>'; //Prompts the user
print '<script>window.location.assign("login.php");</script>'; // redirects to login.php
}
function redirect($page_id)
{
/* Redirect browser */
header('Location: '.$page_id);
/* Make sure that code below does not get executed when we redirect. */
exit;
}
?>
And landing page
<?php
session_start();
//user logged in??
if ($_session['logged in'] != 'Y') {
//No- jump to log in page.
header("location: 3.php");
exit();
}
else
{
echo 'this works';
}
?>
You're defining the session like:
$_SESSION['logged in'] == 'y';
which should be:
$_SESSION['logged in'] = 'y';
yet you check like:
if ($_session['logged in'] != 'Y') {
it should be:
if ($_SESSION['logged in'] != 'y') {
You're checking if it's an uppercase Y while it holds a lowercase y. So it will never succeed.
Also $_SESSION is a superglobal which means:
Superglobals — Superglobals are built-in variables that are always
available in all scopes
and variables are case sensitive.
hi in my script i have it logging in users , but i want to have the script also check if the user is an admin by seeing if the account_type is a,b,c account type "c" is the admin and i would like it to redirect the admin to the admin page ...
<?php // Start Session to enable creating the session variables below when they log in
// Force script errors and warnings to show on page in case php.ini file is set to not display them
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once("security/checkuserlog.php");
if (isset($_SESSION['idx'])) {
echo '<script language="Javascript">';
echo 'window.location="home.php"';
echo '</script>';
}
//-----------------------------------------------------------------------------------------------------------------------------------
// Initialize some vars
$errorMsg = '';
$username = '';
$pass = '';
$remember = '';
if (isset($_POST['username'])) {
$username = $_POST['username'];
$pass = $_POST['pass'];
if (isset($_POST['remember'])) {
$remember = $_POST['remember'];
}
$username = stripslashes($username);
$pass = stripslashes($pass);
$username = strip_tags($username);
$pass = strip_tags($pass);
// error handling conditional checks go here
if ((!$username) || (!$pass)) {
$errorMsg = '<font color="red">Please fill in both fields</font>';
} else { // Error handling is complete so process the info if no errors
include 'connect_to_mysql.php'; // Connect to the database
$username = mysql_real_escape_string($username); // After we connect, we secure the string before adding to query
//$pass = mysql_real_escape_string($pass); // After we connect, we secure the string before adding to query
$pass = md5($pass); // Add MD5 Hash to the password variable they supplied after filtering it
// Make the SQL query
$sql = mysql_query("SELECT * FROM members WHERE username='$username' AND password='$pass'");
$login_check = mysql_num_rows($sql);
// If login check number is greater than 0 (meaning they do exist and are activated)
if($login_check > 0){
while($row = mysql_fetch_array($sql)){
// Create session var for their raw id
$id = $row["id"];
$_SESSION['id'] = $id;
// Create the idx session var
$_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$id");
$username = $row["username"];
$_SESSION['username'] = $username;
} // close while
// Remember Me Section
// All good they are logged in, send them to homepage then exit script
header("location: home.php");
exit();
} else { // Run this code if login_check is equal to 0 meaning they do not exist
$errorMsg = '<font color="red">The Username And Password did not match.</font>';
}
} // Close else after error checks
} //Close if (isset ($_POST['uname'])){
?>
if ($row["account_type"] == "c") { header("Location: admin.php"); }; in your while loop should do it.
This will basically set the "Location" header to "admin.php" or whatever admin page you want, however don't forget to check in your admin page if the user is actually logged in, to avoid users simply going manually to "admin.php" and bypassing the permission check.
$account_type= $row["account_type"];
$_SESSION['account_type'] = $account_type;
then change header("location: home.php"); into
if($account_type=='admin')
{
header("location: adminpanel.php");
}
else
{
header("location: home.php");
}
I used the following script from about.com: http://php.about.com/od/finishedphp1/ss/php_login_code_2.htm
The problem is that a few times it gives me this error: The page isn't redirecting properly. Firefox has detected that the server is redirecting the request for this address in a way that will never complete.
Code:
<?php
session_start();
// Process the POST variables
$username = $_SESSION["user_name"];
//$password = $_POST["password"];
// Set up the session variables
$_SESSION["user_name"] = $username;
$ugh = $_REQUEST['url_name'];
if($_POST){
$_SESSION['user_name']=$_POST["user_name"];
$_SESSION['password']=$_POST["password"];
}
$secret = $info['password'];
//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))
//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT user_name, password
FROM users WHERE user_name = '$username'
and url_name='$ugh'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if (# $info['password'] != $pass)
{
}
else
{
header("Location: home.php");
}
}
}
//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted
// makes sure they filled it in
if(!$_POST['user_name'] | !$_POST['password']) {
die('You did not fill in a required field.');
}
// checks it against the database
if (!get_magic_quotes_gpc()) {
$_POST['user_name'] = addslashes($_POST['user_name']);
}
$check = mysql_query("SELECT user_name,password
FROM users WHERE user_name = '".$_POST['user_name']."'
and url_name='".$ugh."'")or die(mysql_error());
//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database.
<a href=add.php>Click Here to Register</a>');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['password'] = md5($_POST['password']);
$_POST['password'] = $_POST['password'];
//gives error if the password is wrong
if (# $_POST['password'] != $info['password']) {
die('Incorrect password, please try again');
}
else
{
// if login is ok then we add a cookie
$_POST['user_name'] = stripslashes($_POST['user_name']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['user_name'], $hour);
setcookie(Key_my_site, $_POST['password'], $hour);
//then redirect them to the members area
header("Location: home.php");
}
}
}
else
{
// if they are not logged in
?>
2nd code:
Then on each member page i use the following to make sure their login is correct:
// Process the POST variables
$email = $_SESSION["user_name"];
// Set up the session variables
$_SESSION["user_name"] = $username;
if(!isset($_SESSION['user_name'])) { header("Location: log.php");}
To paraphrase Blowski: http://kb.mozillazine.org/The_page_is_not_redirecting_properly
It's like firefox has reached it's maximum recursion depth: it has detected a seemingly endless loop of redirects
What's the name of the files in the above scripts? If the name of the first script is home.php, then when a user visits home.php, it will keep reloading if the password is incorrect, so Firefox will return that message.
Alternatively, do you have anything in your .htaccess which is causing it?