Only admin enters a page [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
This is my signin.php file
and I want to make a page which only admin (mousoufi) can enter.
I made a new page where I want to post only admin things can see. Else I wanted to echo to other users that they dont have permission here.
I just make a session on top of my admin page?
Any ideas?
<?php
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=new mysqli("localhost","root","","3333");
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT username FROM `3333` WHERE password='$pass' AND username='$user'";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
}
}
else {
echo "Wrong Password Try Again"; }
// Set session variables
$_SESSION["username"] = "$user";
$_SESSION["password"] = "$pass";
print_r($_SESSION);
if ("$user"=="mousoufi" AND "$pass"=="1234"){
echo "HELLO Mousoufi ";
}
$con->close();
?>

If you want to use sessions you need to start them on every single page that you need them on, and that is done with this:
session_start();
Put that at the top of your php script.
You'll need a way to distinguish admins (if you're going to have more than one?), but since your question only states one, this should work for you:
<?php
// start session
session_start();
// check if username is admin
if($_SESSION['username'] !== 'mousoufi'){
// isn't admin, redirect them to a different page
header("Location: /someotherpage.php");
}
Notes
You should have more readable table names. 3333 isn't really the best, especially when you call the table the same thing...
You should at least sanitize your user input variables - mysqli_real_escape_string() at very least. It'd be best if you go with PDO or MySQLi Prepared Statements.
Your script is wrong, badly wrong. If your user didn't log in correctly, don't set the session.
if (mysqli_num_rows($result) < 0) {
die("Wrong Password Try Again";);
} else {
// outputdata of each row
while($row = mysqli_fetch_assoc($result)) {
echo "You are now logged in " . $row["username"]."<br>";
$_SESSION['username'] = $row["username"];
// and so on...
}
}
This is what your block should look like.

Related

Displaying name (data from mySQL) on the main page using php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Good day everyone,
Firstly let me explain a little bit about my page flow, btw Im using PHP:-
User will Login to the page using their ID (NRIC No) with pw
Then, In the Main page I would like to display their full name (Eg: Welcome, fullname) whereby the name will automatically fetched from the same table with the nric no in the database.
I was successfully do that when I used the same attribute (fullname) with the ID. However, my sv wants the login ID using NRIC No. SO, When I edit the code, there is nothing appear in the main page :(
Here are my codes in the main page;
<!-- logged in user information -->
<?php if (isset($_SESSION['namapengguna'])) : ?>
<p style="margin-left:360px;margin-right:60px">Welcome<strong><?php echo $_SESSION['namapengguna']; ?></strong></p>
<?php endif ?>
***The information(NRIC No, full name) in the database was successfully inserted.
Example of my Table in database:-
namapengguna | idpengguna | password |
Maisarah | 1234567891 | dfsdfdsf |
This is code for login:-
// LOGIN USER
if (isset($_POST['login_user'])) {
$idpengguna = mysqli_real_escape_string($db, $_POST['idpengguna']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($idpengguna)) {
array_push($errors, "Masukkan ID Pengguna");
}
if (empty($password)) {
array_push($errors, "Masukkan Kata Laluan");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM users WHERE idpengguna='$idpengguna' AND password='$password'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['idpengguna'] = $idpengguna;
$_SESSION['success'] = "";
header('location: lamanutama.php');
}else {
array_push($errors, "ID Pengguna/Kata Laluan salah");
}
}
}
<?php
session_start();
// to store session values
$_SESSION['namapengguna']= $idpengguna; // Initializing Session with value of PHP Variable
?>
Main page Code:
echo $_SESSION["namapengguna"];
please visit this link best example for it. here
As long as you have session you can easily write like this
first add session_start(); and change namepenguna to idpenguna because it has to be the same session you set the time you were receiving result form mysql result
echo 'welcome' .$_SESSION['idpengguna'];
I hope this will work
In your database , password column is not encode by md5(dfsdfdsf), but $password = md5($password);.You should check it
try like this, i hope it will help you:
<?php if (isset($_SESSION['namapengguna'])){
echo 'welcome' .$_SESSION['idpengguna'];
}
?>

check the log in if user or admin with php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to check if the one who logged in is user or admin, I created a column in my DB named 'pin' and put the value whether 0 or 1.
if the pin in 0 so the logged in is an admin and user otherwise.
here is my code but it didn't work with me, please help, I'm totally beginner
$query = mysql_query("SELECT ID, password FROM facultymember ".
"WHERE password='$password' AND ID='$ID'", $connection);
$query2 = mysql_query("SELECT pin FROM facultymember ".
"WHERE password='$password' AND ID='$ID'", $connection);
$row2 = mysql_fetch_assoc($query2);
$check = $row2['pin'];
$rows = mysql_num_rows($query);
if ($rows == 1 && $check == 1) {
$_SESSION['login_user']=$ID; // Initializing Session
header("location: homeFM.php"); // Redirecting To Other Page
}
else if($rows == 1 && $check == 0) {
$_SESSION['login_user']=$ID; // Initializing Session
header("location: homeA.php"); // Redirecting To Other Page
} else {
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
}
Ok, so i rewrote what you have to try and make sense of it for you, with comments.
$query = mysql_query("SELECT ID, password, pin FROM facultymember ".
"WHERE password='$password' AND ID='$ID'", $connection);
$row = mysql_fetch_assoc($query);
if(false != $row){ // user info exists/correct
$_SESSION['login_user'] = $row['ID'];
if('1' == $row['pin']) { //not admin
header("location: homeFM.php"); // Redirecting To Other Page
die;
} else { //admin
header("location: homeA.php"); // Redirecting To Other Page
die;
}
} else { //login doesn't exist
$error = "Username or Password is invalid";
}
mysql_close($connection); // Closing Connection
And that should work for you, hopefully the comments explain it. If it doesn't work, let me know, but it should according to the info you provided.
That being said....
I hope that your passwords are hashed, the input is sanitized, and that you look in to using PDO or MySQLi classes instead of the old deprecated mysql_ functions.
As a side note session_start(); is needed to start a session, not just assigning a variable within the super-global.
Error: There is 1 more closing curly braces '}' found
I'm guessing it is the last curly brace that needs removing
$query = mysql_query("SELECT ID, password FROM facultymember WHERE password='".$password."' AND ID=".$ID, $connection);
$query2 = mysql_query("SELECT pin FROM facultymember WHERE password='".$password."' AND ID=".$ID, $connection);
Your querys had weird concatenation

Writing an 'if' statement in order to login users using php/ mysql [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I’m wondering how you write if statements using mysql/php.
I’ve got an employee table with all their details, ‘username’ and ‘password’ then a column called ‘admin’ with a 0 or 1 as well. The user can login using the "username" and "password" form boxes. How do I write it so that it checks if the username/password exists then checks if admin = 0 and directs them to header location employee.php else if admin=1 then directs them to header location admin.php?
Any help would be greatly appreciated.
edit: This is the code I've got so far...
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
setcookie('username',$myusername,time() + (86400 * 7)); // 86400 = 1 day
if ('admin' == '0'){
header("location:employee.php");
}
else {
header("location:admin.php");
else {
header("location:fail.php");
}
}
?>
try this php code
$username = mysql_real_escape_string(stripslashes($_REQUEST['username'])); // received from post/get
$password = mysql_real_escape_string(stripslashes($_REQUEST['password'])); // received from post/get
$res = mysql_query("SELECT * FROM `employee` WHERE username='$username' AND password='$password' LIMIT 1") or die(mysql_error());
if($row = mysql_fetch_assoc($res))
{
if($row['admin']==1)
{
header("location:admin.php");
exit;
}
else
{
header("location:employee.php");
exit;
}
}
else
{
// invalid username or password
// code here to handle
}
You Can try using a select box of value ADMIN and USER . You can validate the select box in the if statement
if(select=="admin")
{
verify with DB \\admin
Redirect
}
else
{
verify with DB \\ end user
redirect
}
Hope it helps !!
You posted every step. Just code it now.
Make a new mysqli connection.
$mysqli = new mysqli("host", "user", "password", "database");
Define your query:
$query = "SELECT * FROM yourtablename WHERE username=? AND password=?";
Create a prepared statement:
$stmt = mysqli->prepare($query);
Bind the values:
$stmt->bind_param('ss', $submitted_username, $submitted_password);
Execute the statement:
$stmt->execute();
Check if there is a result or not.
If there is a result, check if admin is 0 or 1 and redirect (in case of 1) to admin php with header():
header('Location: admin.php');
You can get your selected data for example with fetch().
Just study the examples from php.net for more information how to get data with mysqli.

password and username validation in PHP [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
i have this information on my database...
Username - kam, mav, shin
Password - kam, mav, shin
this is my code...
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2=mysql_query("SELECT * FROM tablename WHERE `username` =
'".mysql_real_escape_string($_POST['username'])."' and `password` =
'".mysql_real_escape_string($_POST['password'])."'");
while($row=mysql_fetch_array($tbl2))
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
if (($row['username']!=$_POST['username'])&&($row['password']!=$_POST['password']))
{
header("location: /login.php?codeError=1");
die;
}
?>
the problem is, if i enter the username "mav" and the password is "kam", it still go through the next page. What should i do?
You should just check if the query returns any rows with mysql_num_rows():
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl2 = mysql_query("SELECT `username`, `password` FROM `tablename` WHERE
`username` = '".mysql_real_escape_string($_POST['username'])."' AND
`password` = '".mysql_real_escape_string($_POST['password'])."'
");
$rows = mysql_num_rows($tbl2);
if($rows){
// user and password exists in db
} else {
// does not exist
header("location: /login.php?codeError=1");
die;
}
Like I told you in previous question, try to move from mysql_* functions.
Just a suggestion but why not try it this way:
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}else{
header("location: /login.php?codeError=1");
die;
}
I don't understand why you need two if statements here, it's only boolean and the result will either be true or false.
Hope this helps :)!
You are checking for validation already in your query. If the user entered username and password correctly and only then, the query returns a row, containing that data.
So you only have to count the rows returned bye your Query. If it is below 1, then the user is not authenticated
Try
if (($row['username']==$_POST['username'])&&($row['password']==$_POST['password']))
{
echo " ";
}
else
{
header("location: /login.php?codeError=1");
die();
}
Anyway, a nice way to address this kind of issues is temporary printing on screen the variables (as a debug).
echo $row['username']." ".$_POST['username']." ".$row['password']." ".$_POST['password']
see if the variables are actually there of if there are issues with your DB query or with the form that posts the data.

Adding a login system [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Hey!
I bought and settled up my site long ago..
My site is a facebook like site where people can add their own or like others.
I thought about adding a login system so people can post with their username and make it easier to make posting-liking contests.
I already have the system itself - using this http://www.evolt.org/node/60384
I tried to add an option in the process file that when the session is 'loggedin' the code retrieves the username and in all other cases, 'Anonymous'.
Problem is it doesn't work :(
The code is:
$today = date("Ymdhis");
$rand = $today.mt_rand().mt_rand().mt_rand();
$count = '0';
$type = 'picture';
$username = '<? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?>';
$sql = "INSERT INTO `like` (`rand`, `like`, `count`, `created`, `youtube`, `type`,`username`) VALUES ('$rand', '$like', 0, '$today', '$string', '$type', '$username')";
I first defined $username and then 'told' the script to INSERT the $username entry into it's field.
The problem is that when I try this in real-time,
the field shows the actual code; <? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?> instead of the desired output.
Also, I've included the session.php for the login in the start of the process document.
The session.php I used along with all of the other files is available at http://www.evolt.org/node/60384 WITHOUT download.
P.S the code i used for $username is used on the main page to output the username after logged in.. I added the 'Anonymous' part myself.. which could cause it to not work..
The code you post is PHP, but gets put into your side AFTER it is parsed. So it will never 'run'.
Unless you are using some sort of templating system that parses your code twice, don't you mean this?
if($session->logged_in){
$username = $session->username;
} else {
$username = "Anonymous" ;
}
$username is a variable containing a string :
$username = '<? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?>';
Everything that is in the quotes is a string, not PHP code. It won't be executed.
You need to do something like this :
if($session->logged_in){
$username = $session->username;
} else {
$username = "Anonymous";
}
Change
$username = '<? if($session->logged_in){ echo "$session->username" } else { echo "Anonymous" } ?>';
to
if($session->logged_in) $username = $session->username; else $username = "Anonymous"

Categories