I have been trying to make a page protection for the Administrator page, and I can not get it to work. I am sure this would not have been a problem if I was not new to PHP coding, hehe.
So what I am trying to do is, when a normal user with the type '0' is trying to access the administrator page, index_admin.php, the user will get redirected to the normal user page, index.php. And if the user have the type '1', then the user/admin will stay on the page.
So here is the code I have been trying to get working. (This file is required in index_admin.php and it is called index_admin_check.php):
<?php
session_start();
?>
<?php
$vert = "localhost";
$brukarnamn = "root";
$passord = "";
$db_namn = "nettsidebunad";
$tbl_namn = "kunde_register";
// Connecting to the MySQL database.
mysql_connect("$vert", "$brukarnamn", "$passord") or die ("Kan dessverre ikkje koble til databasen.");
mysql_select_db("$db_namn") or die ("Kan ikkje finna den ynkjande databasen.");
?>
<?php
// *** Page protection *** \\
// Admin check. If `type` = 1, let the user (admin) stay on the site. If `type` = 0 kick the user (normal) off the site.
$sql = "SELECT `type` FROM $tbl_namn";
$res = mysql_query($sql);
$tell = mysql_num_rows($res);
if ($tell == 0) {
header ("location: index.php");
exit();
}
?>
Some of this text is in norwegian.
$vert = $host (in english)
$brukarnamn = $usernamn (in english)
$passord = $password (in english)
$db_namn = $db_name (in english)
$tbl_namn = $tbl_name (in english)
$sql = "SELECT `type` FROM $tbl_namn";
This SQL query will return a row for every user in your database. Using your method of simply checking whether the query returned a result or not, you need to select just the row for the current user, and then only if the user has type=1.
You need to make sure that:
The user has previously logged into the system using a username and password or some such
You have saved their details to the session.
If your user table has an ID column, and you saved the ID of the logged in user to the session as 'userid', you might use the query:
$sql = "SELECT `type` FROM $tbl_namn WHERE id = {$_SESSION['userid']} AND type = 1";
But of course that would be moot, because you would just have save the user's type in the session when you first logged them in, wouldn't you?
Well for what I can see, you don't actually check for user.
I will make some remarks to your code to make situation clear:
$sql = "SELECT `type` FROM $tbl_namn"; //Return all values of column "type" from table - instead you should search for specifyc user
$res = mysql_query($sql);
$tell = mysql_num_rows($res); //Count returned rows
So instead of finding out the user type, you get the count of registered users.
What you should do to search for user name and get user type for that name. So lets think of this table concept:
ID | name | type |
Now we can start our user check up. We will ask mysql for type of user "admin".
$name = $_POST["username"]; //username submited in POST HTML form
$name = mysql_real_escape_string($name); //Replace dangerous characters from name. This is important to avoid your database being hacked
$data = mysql_query("SELECT type FROM $tbl_namn WHERE name='$name'") or die(mysql_error()); //On failure, you will is if there is some error
$data=mysql_fetch_row($data); //Get actual data
if($data["type"]==0) {
header("HTTP/1.1 403 Acces Forbidden");
header("Location: forbidden.html"); //send user to page telling me he is not allowed to enter. As well you can use include here.
exit;
put this to login page:
<?php session_start();
if ($_POST['type'] = "1") {
Header('location: http://example.com/admin.php/');
$_SESSION['admin']; = "yes";
exit;
} else {
Header('location: http://example.com/user.php/');
$_SESSION['admin']; = "no";
exit;
}
//modify as needed
?>
and this one into admin.php filename can be any but extension needs to be .php:
<?php session_start():
if ($_SESSION['admin']; = "no") {
Header('location: http://example.com/user.php/');
exit;
}
//modify as needed
?>
and remember to put this in the very beggining of the file otherwise sessions won't work
Related
I am trying to figure out how to display user information after they've logged in. I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users. I am also having trouble grabbing the header.
here's my code for login.php
<?php
session_start();
require 'dbh.php';
$username = $_POST['uname'];
$password = $_POST['pwd'];
$sql = "SELECT * FROM registeredusers WHERE UserName = '$username'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$hashed_Password = $row['Password'];
$Dehash = password_verify($password,$hashed_Password);
if($Dehash == 0){
echo "username or password is incorrect";
exit();
} else{
$sql = "SELECT * FROM registeredusers WHERE UserName='$username' AND Password='$hashed_Password'";
$result = mysqli_query($connection,$sql);
if (!$row=mysqli_fetch_assoc($result)){
echo "Your User Name or Password is incorrect";
}
else {
$userid = $row['id'];
$_SESSION['UserName'] = $row['UserName'];
header("Location: userhomepage.php?user_id=".$userid);
}
}
?>
The following code redirects to userhomepage.php and the user ID is in the url can someone also tell me how do I grab the user ID from the url? I only started coding in PHP a week ago I am fairly new so if guys have any pointers for me that would be great.
I am not sure whether I should create a single php file which would display user information depending on the session or should I create different files for different users.
You should create a single page that displays user information based on session... you don't want to have to hand-make a new page every time a user signs up!
how do I grab the user ID from the url
echo $_GET["user_id"];
I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)
My Profile php
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
This is my php for viewing user profile.
http://mywebsite.com/profile.php?userID=5 its working fine in this way.
i want my code to check if user is available in database for example if i add ?userID=10 which is not present in database it gives out mysql error or even if i use http://mywebsite.com/profile.phpthen also it give error.
so now i want if user is not available in database it should give that user is not available and when we use simple http://mywebsite.com/profile.php it should give auto add it to userID=1 OR REDIRECT it to home.php
If there is other way of doing this please let me know. well im very newbie in this field
Thanks for looking my question and answering :)
Solved
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
$UserID = $_GET['userID'];
$CheckQuery = mysql_query("SELECT * FROM users WHERE id='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: index.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
You shouldn't use MySQL As it's depreciated,
If you really wish to use MySQL You could check at the start of the script if there is a row count for the User ID, Example:
<?
$UserID = $_GET['UserID'];
$UserID = mysql_real_escape_string($UserID);
$CheckQuery = mysql_query("SELECT * FROM users WHERE userID='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
// Do something If user is Not Found
// Redirect to Another Page OR Something
}
?>
than check that query give with result if it wont found data in database than redirect
$result = mysql_query(...);
if(mysql_num_rows($result) !=1){ //
header("Location:signup.php");
exit();
}
You shouldn't use MySQL As it's depreciated, either use PDO or mysqli
I want to display the attributes of the game character, which is under the users TABLE. So, I want it to display the specific attributes of the user who has logged in, since it should be in his row. Do I need to register my users with session, because I didn't.
This is the code I used to get the sessions for the user in when login in
<?
if(isset($_POST['Login'])) {
if (ereg('[^A-Za-z0-9]', $_POST['name'])) {// before we fetch anything from the database we want to see if the user name is in the correct format.
echo "Invalid Username.";
}else{
$query = "SELECT password,id,login_ip FROM users WHERE name='".mysql_real_escape_string($_POST['Username'])."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result); // Search the database and get the password, id, and login ip that belongs to the name in the username field.
if(empty($row['id'])){
// check if the id exist and it isn't blank.
echo "Account doesn't exist.";
}else{
if(md5($_POST['password']) != $row['password']){
// if the account does exist this is matching the password with the password typed in the password field. notice to read the md5 hash we need to use the md5 function.
echo "Your password is incorrect.";
}else{
if(empty($row['login_ip'])){ // checks to see if the login ip has an ip already
$row['login_ip'] = $_SERVER['REMOTE_ADDR'];
}else{
$ip_information = explode("-", $row['login_ip']); // if the ip is different from the ip that is on the database it will store it
if (in_array($_SERVER['REMOTE_ADDR'], $ip_information)) {
$row['login_ip'] = $row['login_ip'];
}else{
$row['login_ip'] = $row['login_ip']."-".$_SERVER['REMOTE_ADDR'];
}
}
$_SESSION['user_id'] = $row['id'];// this line of code is very important. This saves the user id in the php session so we can use it in the game to display information to the user.
$result = mysql_query("UPDATE users SET userip='".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',login_ip='".mysql_real_escape_string($row['login_ip'])."' WHERE id='".mysql_real_escape_string($_SESSION['user_id'])."'")
or die(mysql_error());
// to test that the session saves well we are using the sessions id update the database with the ip information we have received.
header("Location: play.php"); // this header redirects me to the Sample.php i made earlier
}
}
}
}
?>
you need to find which user you are logged in as. How do you log in to your system? You have several options which you can try out:
use sessions (save the userID in the session, and add that to the query using something like where id = {$id}
Get your userid from your log-in code. So the same code that checks if a user is logged in, can return a userid.
Your current code shows how you log In, and this works? Then you should be able to use your session in the code you had up before.
Just as an example, you need to check this, and understand the other code. It feels A bit like you don't really understand the code you've posted, so it's hard to show everything, but it should be something like this.
<?php
session_start();
$id = $_SESSION['user_id'];
//you need to do some checking of this ID! sanitize here!
$result = mysql_query("SELECT * FROM users" where id = {$id}) or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
}
I am using sessions to pass user information from one page to another. However, I think I may be using the wrong concept for my particular need. Here is what I'm trying to do:
When a user logs in, the form action is sent to login.php, which I've provided below:
login.php
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$con = mysql_connect("xxxx","database","pass");
if (!$con)
{
die('Could not connect: ' .mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
session_start();
$_SESSION['loggedin'] = 1; // store session data
$_SESSION['loginemail'] = fldEmail;
header("Location: main.php"); }
}
mysql_close($con);
Now to use the $_SESSION['loggedin'] throughout the website for pages that require authorization, I made an 'auth.php', which will check if the user is logged in.
The 'auth.php' is provided below:
session_start();
if($_SESSION['loggedin'] != 1){
header("Location: index.php"); }
Now the point is, when you log in, you are directed BY login.php TO main.php via header. How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php? Will I have to connect again just like I did in login.php? or is there another way I can simply echo out the user's name from the MySQL table? This is what I'm trying to do in main.php as of now, but the user's name does not come up:
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$loginemail'
and Password='$loginpassword'");
//check if successful
if($result){
if(mysql_num_rows($result) == 1){
$row = mysql_fetch_array($result);
echo '<span class="backgroundcolor">' . $row['fldFullName'] . '</span><br />' ;
Will I have to connect again just like I did in login.php?
Yes. This is the way PHP and mysql works
or is there another way I can simply echo out the user's name from the MySQL table?
No. To get something from mysql table you have to connect first.
You can put connect statement into some config file and include it into all your scripts.
How can I echo out the user's fullname which is stored in 'fldFullName' column in MySQL on main.php?
You will need some identifier to get proper row from database. email may work but it's strongly recommended to use autoincrement id field instead, which to be stored in the session.
And at this moment you don't have no $loginemail nor $loginpassword in your latter code snippet, do you?
And some notes on your code
any header("Location: "); statement must be followed by exit;. Or there would be no protection at all.
Any data you're going to put into query in quotes, must be escaped with mysql_real_escape_string() function. No exceptions.
so, it going to be like this
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$loginemail = $_POST['loginemail'];
$loginpassword = md5($_POST['loginpassword']);
$loginemail = mysql_real_escape_string($loginemail);
$loginpassword = mysql_real_escape_string($loginpassword);
$query = "SELECT * FROM Members WHERE fldEmail='$loginemail' and Password='$loginpassword'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
if($row = mysql_fetch_assoc($result)) {
session_start();
$_SESSION['userid'] = $row['id']; // store session data
header("Location: main.php");
exit;
}
and main.php part
session_start();
if(!$_SESSION['userid']) {
header("Location: index.php");
exit;
}
include $_SERVER['DOCUMENT_ROOT']."/dbconn.php";
$sess_userid = mysql_real_escape_string($_SESSION['userid']);
$query = "SELECT * FROM Members WHERE id='$sess_userid'";
$result = mysql_query($query) or trigger_error(mysql_error().$query);
$row = mysql_fetch_assoc($result));
include 'template.php';
Let me point out that the technique you're using has some nasty security holes, but in the interest of avoiding serious argument about security the quick fix is to just store the $row from login.php in a session variable, and then it's yours to access. I'm surprised this works without a session_start() call at the top of login.php.
I'd highly recommend considering a paradigm shift, however. Instead of keeping a variable to indicate logged-in state, you should hang on to the username and an encrypted version of the password in the session state. Then, at the top of main.php you'd ask for the user data each time from the database and you'd have all the fields you need as well as verification the user is in fact logged in.
Yes, you do have to reconnect to the database for every pageload. Just put that code in a separate file and use PHP's require_once() function to include it.
Another problem you're having is that the variables $loginemail and $loginpassword would not exist in main.php. You are storing the user's e-mail address in the $_SESSION array, so just reload the user's info:
$safe_email = mysql_real_escape_string($_SESSION['loginemail']);
$result = mysql_query("SELECT * FROM Members
WHERE fldEmail='$safe_email'");
Also, your code allows SQL Injection attacks. Before inserting any variable into an SQL query, always use the mysql_real_escape_string() function and wrap the variable in quotes (as in the snippet above).