I want to make some of my php pages accessible to certain users. I flag these users in my users table as 'super_user' in the 'user_privilege' attribute. So fat I have got the login and sessions working. But I'm not sure about 'super_user' only pages. Basically this is the page I want to make accessible only to super users:
<?php
require_once('../includes/su_permission.inc.php');
require_once('../includes/session_timeout_db.inc.php');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Secret page</title>
</head>
<body>
<h1>Restricted area</h1>
<p>Back to restricted menu </p>
<?php include('../includes/logout_db.inc.php'); ?>
</body>
</html>
The session_timeout_db.inc.php doc checks if the user's session has expired and it works fine. I have also added this: require_once('../includes/su_permission.inc.php'); in the code to check if the user is a super user. This my attempt at the code:
<?php
require_once 'login.php';
$conn = new mysqli ($host, $user, $password, $database) or die("Connection Failed");
$sql = 'SELECT user_role FROM users WHERE user_email = ?';
$stmt = $conn->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param('s', $user_email);
$stmt->bind_result($user_role);
$stmt->execute();
$stmt->fetch();
if ($user_role='SU') {
$_SESSION['privilege_level'] = $user_role;
// some other code needed here
exit;
} else {
echo 'No permission to visit this page';
}
I know it is a poor attempt, but I'm not sure what else to do from here. Can someone please advice the best way I can do this ?
Thanks
Here is your problem:
if ($user_role='SU') {
You need a proper comparison operator (== or ===) here. What you are doing right now is assigning a value of SU to $user_role in all cases.
A slight programming suggestion to avoid such problems is to flip to comparison order like this:
if ('SU' == $user_role) {
That way if you accidentally type = instead of == or ===, you will get an error output, rather than having your code quietly run while doing something you don't want it to do.
I did a similar thing on the site I'm working on. I setup up three different areas, for the different user 'types'.
I then setup 3 different session check files for the groups of pages. I'm sure this could be done using only one file, and some elseifs but whatever. Anyway here is the code snippet that I use on my pages to check if a user is logged in, and if they are the right "type" of user to view the page:
if (isset($_SESSION['authenticated']) && $_SESSION['authenticated'] !== 'admin') {
//if (!isset($_SESSION['authenticated'])) {
header("Location: $redirect");
exit;
If they aren't right it redirects them. I hope that helps.
Related
I am a business student, inexperienced with php,html etc. and as part of a course we were asked to develop a website using HTML,CSS and PHP that has a registration and login page, connected to an MS Access Database. When I first did the login.php page it was a success, but then we were asked to connect it to our homepage and have a welcome message with the Loggedin username. I tried following online suggestions on how do it but I am getting "undefined index error" and "trying to get property of non-object" errors when running my login.php file.
Here is what I have done:
login.php
<html>
<head>
<title>Login</title>
</head>
<body>
<?php session_start(); ?>
<?php
$email=$_GET['email'];
$password=$_GET['password'];
$odbc = odbc_connect ('group7', 'root', '') or die( "Could Not Connect to ODBC Database!");
$query = odbc_exec($odbc, "SELECT email, username FROM users WHERE email='$email' and password='$password'") or die (odbc_errormsg());
if ($rs->Fields["email"]->value && $rs->Fields["email"]->value == $email)
if ($rs->Fields["password"]->value && $rs->Fields["password"]->value == $password)
{
$_SESSION["email"] = $email;
$_SESSION["loggedin"]= true;
// Relocate to the logged-in page
header("Location: homespace-4 copy/index.php");
}
else
{
$_SESSION["loggedin"] = false;
$_SESSION["message"] = "login Error as $email." ;
}
odbc_close($odbc);
?>
</body>
</html>
Before i put the session_start(); it worked perfectly fine on its own, but was told I needed it for displaying the username on the redirected page. Please help me figure out how to make it work.
These are the things that jump out at me.
You cannot use header("Location: homespace-4 copy/index.php"); unless there has not been any html/header data before it. It just isn't meant to work that way. You have to call it before any html.
Avoid putting PHP inside your HTML. Instead, put HTML inside your PHP. [note: Based on what I see of your code, all of the HTML is unnecessary because you are redirecting your site visitor to your homespace-4 page.]
Avoid using $_GET, it opens you to security risks. Use $_POST. Unless, in this instance, your instructor explicitly told you to do it this way.
session_start(); is essentially called for 3 reasons: to add, read, or delete data
Putting session_start(); near the top of your code is "okay", but it is probably better putting in the area you need it to be in. In this case, right above your "if" statement comparing input values. You want it there because you are adding the data (true or false) at that part. [note: Additional sets of () were added to the "if" statement. Please take the time to study them so you understand why they are there.]
<?php
session_start();
if ( (($rs->Fields["email"]->value) && ($rs->Fields["email"]->value == $email)) && ($rs->Fields["password"]->value) && ($rs->Fields["password"]->value == $password)) ) {
$_SESSION["email"] = $email;
$_SESSION["loggedin"]= true;
// Relocate to the logged-in page
header("Location: homespace-4 copy/index.php");
} else {
$_SESSION["loggedin"] = false;
$_SESSION["message"] = "login Error as $email." ;
}
?>
I'm hoping this will give you enough to work with so that you understand the assignment better. Good luck with your class!
I made a small login system for users, they can log in and change their userinformation on the account_setting page.
But since im pretty new to php I wonder how can I give each user their own page? A page that is public.
Ex, User "Steven" has user_id=17.
How can I create a page for that user, so his information gets displayed there.
Something like website.com/user=17 ... His information.
And also if the page could act as a template, just diffrent information/url depending on user.
Im not asking anyone to write this for me, a link to a good tutorial would work just fine :)
But please, no 5year old posts on the topic.
you need userprofile.php?userid=17 and use $_GET['userid'] to draw the information based on that user. HTML should be same on userprofile.php only data will change depending on the user id. If userid is not set then show an error message or something
Generally saying:
if (!empty($_GET['user']) && is_numeric($_GET['user'])){
//Find him in database
if (user_found($_GET['user'])){
include "left_column.php" ;
include "user_info.php" ;
} else {
echo "Page is not found" ; //or set header error 404
}
} else {
include "news_column.php" ;
}
website.com/index.php?user=17
<?php
require_once 'db/connect.php';
//Pull in 'user' from the query string.
$user = isset($_GET['user']) ? trim($_GET['user']) : null;
//Try to pull that user's info from the database.
$stmt = $dbh->prepare("SELECT * FROM user WHERE user_id = :user_id");
$stmt->bindParam(':user_id', $user);
$stmt->execute();
$user= $stmt->fetch(PDO::FETCH_ASSOC);
if(!is_array($user)){
//User not found. Throw 404 or redirect.
header('HTTP/1.0 404 Not Found');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo htmlentities($user['name'], ENT_QUOTES, "utf-8"); ?></title>
</head>
<body>
<h1><?php echo htmlentities($user['name'], ENT_QUOTES, "utf-8"); ?></h1>
<p>
<?php echo nl2br(htmlentities($user['bio'], ENT_QUOTES, "utf-8")); ?>
</p>
</body>
</html>
I'm going to assume that you're storing your user information in a database. For the sake of argument, we'll say it's a mysql database. What you need to do is capture the userid and then read only that column from the database.
If your URL is website.com/user/view.php?id=17, your user variable will be in $_GET['id']
So something like this:
$id = mysqli_real_escape_string($_GET['id']);
$results = mysqli->query("select * from users where id = '$id'");
$results = $results->fetch_assoc();
... will bring up the information for the user; then you just build a page to display it.
I'm writing a PHP code for my website. Currently, there's some problems with my code.
Here's my code. Ignore some Malay language used, I'd tried to translate most of them.
<?php
session_start();
include "../library/inc.connectiondb.php";
$txtUser = $_POST['txtUser'];
$txtPass = $_POST['txtPass'];
if(trim($txtUser) == "") {
echo "<b>User ID</b> is empty, please fill";
include "login.php";
}
else if(strlen(trim($txtPass)) <= 5) {
echo "<b>Password</b> is less then 6 characters, please fix";
include "login.php";
}
else {
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
$qryPeriksa = mysql_query($sqlPeriksa, $sambung);
$hslPeriksa = mysql_num_rows($qryPeriksa);
if($hslPeriksa == 0) {
# If username doesn't exist
echo "<b>UserID</b> doesn't exist";
include "login.php";
}
else {
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
if($hslPassword < 1) {
# If password is incorrect
echo "<b>Password</b> is incorrect";
include "login.php";
}
else {
# If login successful
$SES_Admin = $txtUser;
session_register('SES_Admin');
echo "LOGIN SUCCESSFUL";
# Redirect to index.php
echo "<meta http-equiv='refresh' content='0; url=index.php'>";
exit;
}
}
}
?>
The problem is this code allows me to login even if the password is wrong. I'd done some searches and it still doesn't solve my problem. I'm pretty sure that the problem is at line 27 onwards.
So, if anyone has a solution, please tell me quickly. I'm writing this code for my school, and it had to be finished before next year.
Edit
Ok, I'd already placed the mysql_real_escape_string in the code just like what many people told me. I don't know how this will help, but the mysql table for this was named "admin". It had 2 fields; userID and passID. To test the code, I'd inserted the value "admin" and "12345678" into the table.
This is where your problem is:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPeriksa, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
You see, your mysql_query is executing $sqlPeriksa which is:
$sqlPeriksa = "SELECT userID FROM admin WHERE userID='$txtUser'";
Instead, your code should be like this:
$sqlPassword = "SELECT passID FROM admin WHERE (userID='$txtUser' && passID='$txtPass')";
$qryPassword = mysql_query($sqlPassword, $sambung);
$hslPassword = mysql_num_rows($qryPassword);
Please try this out and let us know what happens.
[edit/additional] : I strongly suggest that you look into the following:
Using PDO:
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
Using stored procedures:
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html
Using PDO + stored procedures:
http://php.net/manual/en/pdo.prepared-statements.php (See example #4)
just plain troubleshoot is necessary. how many rows are returned? what are the values of userID and passID in the query that returns rows? put some breaks in and see what's going on. i don't see a problem, it but its hard to troubleshoot code posted here since it really can't be run without a db.
I don't see any reason this isn't working as you expected, I suspect the problem might be elsewhere. For example, I don't see you checking if a "SES_Admin" session is already registered. But at the very least you need to replace lines 5 and 6 with this, otherwise someone could potentially delete your entire user table, and do various other malicious things with your MySQL databases.
$txtUser = mysql_real_escape_string($_POST['txtUser']);
$txtPass = mysql_real_escape_string($_POST['txtPass']);
Please read the article on mysql_real_escape_string at http://php.net/manual/en/function.mysql-real-escape-string.php
I am hosting a website from a local computer (using MAMP Pro on a Mac), and need to switch the hosting to another local Mac. I have copied across all of the files for my website, and the MySQL tables, and checked that the server and MySQL are running OK. Everything seems to be fine, except that the login system is returning "Invalid User" when I try to log in, even though I am entering the correct user info (I have tried a few users just to be sure).
The log.php that handles the login looks like this:
<?
session_name("MyLogin");
session_start();
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","root","password"); // your MySQL connection data
$db = mysql_select_db("nick"); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM USERS WHERE login='$name'");
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM USERS WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/may.php"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
I have temporarily removed the password in the above code.
I wonder what steps I can take to troubleshoot this issue, and would be grateful for any help.
Thanks,
Nick
A few common techniques when I encounter this issue.
Output the generated SQL and test it by hand - echo $query;
See if mysql_error() outputs anything after you run your queries.
Use var_dump() and print_r() on your data objects to ensure they are as expected.
Comment out your redirects and exit() lines so you can determine where the script is breaking.
Fix or comment back with anything determined by the above.
Your code does a query to find a user with the given username, and then checks if the number of rows with that username is exactly 1.
The only way you could see the 'Invalid User' error is if there are 0 users with that username or more than 1 user with that username.
Have a look at the contents of the table and check which of these is the case (I recommend http://sequelpro.com for viewing database contents on a Mac). You can also use sequel pro to test your queries.
Hello I have a question. I have set up my login system with cookies and it works. But I wonder is there a more clean version of doing this.
<?
include('../config/db_config.php');
$username = $_COOKIE['user'];
$password = $_COOKIE['pass'];
$result = mysql_query("SELECT * FROM users WHERE isadmin = 1");
while($row = mysql_fetch_array($result))
{
if($username == $row['username'] && $password == $row['password'])
{
//User entered correct username and password
echo("ALLOW");
}
else
{
//User entered incorrect username and password
echo("DENY");
}
}
?>
You see I want all my content to be shown ONLY if I am logged in as admin. So what, now only way of doing this would be ECHO'ing out my HTML/PHP/Javascript instead of echoing ALLOW because if I just include("somepage.php") there that page would still be avialable for usage without logging in, and even if I do same check there I still would be ECHO'ing out everything.
Why are you loading every user, then comparing the username and the password? Wouldn't be easier to load a single user matching the username and the password?
Loading a single user will allow to remove the while().
In PHP, don't use mysql_query; do use PDO (if need, google for it to know why it's better).
Check your input (quite optional here, I agree).
Do never store passwords in plain text format.
You can probably do something like (I haven't used PHP/PDO for years, so the code may be inexact):
if (strlen($username)> 128)
{
// Something wrong. The username is too long.
}
$hash = sha1($password);
$sth = $dbh->prepare('if exists(select * from users where isadmin = 1 and username = :username and password = :password) select 1 else select 0');
$sth->bindParam(':username', $username, PDO::PARAM_STR, 128);
$sth->bindParam(':password', $hash, PDO::PARAM_STR, 40);
$sth->execute();
$isFound = $sth->fetchAll();
if ($isFound)
{
// User entered correct username and password.
echo 'ALLOW';
}
You could set a session variable on your login page (or any page that checks the login) that stores whether or not they're logged in and it will persist across pages. Then you can simple wrap your admin html in an if statement like so:
<?php
if ($_SESSION['isAdmin'] == true) {
?>
<p>My admin html</p>
<?php
} else {
?>
<p>My non-admin html</p>
<?php
}
?>
To save the info in a session, just add this to the part where you have echo("ALLOW");:
$_SESSION['isAdmin'] = true;
You'll also want to add session_start(); to the top of the script.
I would suggest that you do something like that only once, when the user first accesses the page, and then set a $_SESSION['is_admin'] or something for the rest of the time, so that you don't have to make an extra db call each page.
You could always put your "somepage.php" above the document root. This is a common way of preventing direct execution.
For example, if your webserver looks like 'project/public_html/index.php' put your admin-only include in 'project/somepage.php' then reference it using something like include("../somepage.php").
Obviously this will need adjustment according to the real paths you use.