i've just started learning php, i'm using an if statement to control what will be displayed on my webpage depending on whether a user is logged in or not.
I know how to show things to the user if they are logged in under their session, by using this session statement. But how would i create the reverse to tell the site to display something else if the user is not logged in under their session?
Here's the code i'm using.
<?php if (isset($_SESSION['user_id'])) {
if ($user['id'] == $_SESSION['user_id']){
if ($user['account_type'] == "platinum"){ ?>
<html stuff>
<?}
}
}?>
It sounds like you are new to programming, not just PHP. Welcome to the community!
You are looking for the else part of the if-statement. This is common to many programming languages.
Here is an example to get you started.
<?php
if (isset($_SESSION['user_id']))
{
if ($user['id'] == $_SESSION['user_id'])
{
if ($user['account_type'] == "platinum")
{
print "Welcome, platinum user";
}
else
{
print "Welcome, non-platinum user";
}
}
else
{
print "Unexpected session";
}
}
else
{
print "You are not logged in";
}
?>
Related
Using PHP I am trying to check whether the user is an admin or a normal user. If they are a normal user then it should redirect them to home.php. However if they are an admin then it should redirect them to admin.php. When entering in the username and password of a standard user it sends me to home.php which is what is expected. However whenever I use an admin login it does not direct me to admin.php. Instead it redirects me to authentication.php which is the script that checks if the username and password are correct.
I have tried 2 different blocks of code, the first one did not work at all as it came up with syntax errors. However this one should work fine but it does not. I have also checked if the correct numbers are being stored within the database. 1 being a standard user and 2 being for an admin. I have printed the admin level on my profile page so I know that it is storing the data properly.
if (isset($_SESSION['admin'])) {
if ($_SESSION['admin'] === "2") {
header('Location: admin.php');
} else {
header('Location: home.php');
}
} else {
header('Location: home.php');
}
I expect that when an admin logs in it should direct me to admin.php, however I am just being directed to a blank screen of authentication.php.
Your code is accurate. Forexample
<?php
$_SESSION['admin'] = "2";
if (isset($_SESSION['admin'])) {
if ($_SESSION['admin'] === "2") {
header('Location: admin.php');
} else {
header('Location: home.php');
}
} else {
header('Location: home.php');
}
?>
If you run this on localhost it redirects to admin.php page properly. as you are using === so you have to make sure your datatype is matched.
for example:
<?php
$a = "1";
if ($a === 1) {
echo "not ok";
}
if ($a == 1) {
echo "ok";
}
if ($a === "1") {
echo "This time ok";
}
if ($a == "1") {
echo "it's also ok";
}
?>
First echo doesnt show as if cant matched datatype. so i suggest you to change === to == and see. hopefully it will solve your problem
<?php
if (isset($_SESSION['admin'])) {
if ($_SESSION['admin'] == "2") {
header('Location: admin.php');
exit();
} else {
header('Location: home.php');
exit();
}
} else {
header('Location: home.php');
exit();
}
?>
You can return the link page from the php script like below:
if (isset($_SESSION['admin'])) {
$data['admin_page_link'] = 'admin.php';
echo json_encode($data);
}else {
$data['home_page_link'] = 'home.php';
echo json_encode($data);
}
Then just call it in javascript ajax call to redirect to the desired page:
if (response.user === 'admin') {
window.location.href = response.admin_page_link;
} else {
window.location.href = response.home_page_link;;
}
In the above code you may check by using the full web address of php file like: http://localhost/admin.php
this is my code after success enter login and password
<?php session_start();
if(!isset($_SESSION['nik'])){ die("Anda belum login");}
if($_SESSION['level']!="admin"){
echo "<h3>Welcome ".$_SESSION['nik']."</h3>";
echo "panel user";
}
if($_SESSION['level']="admin"){
echo "panel admin";
}
?>
<a href=log.php?op=selesai>Log Out</a>
the out put that i want is :
if login = admin then display "hello admin"
if login = user then display "hello user"
if not login then say "you must login"
any suggestion how to fix that ?
please find below code as per your requirements.
<?php
session_start();
if(!isset($_SESSION['nik'])){
echo "You must login.";
exit;
}
if($_SESSION['level']!="admin"){
echo "<h3>Welcome ".$_SESSION['level']."</h3>";
echo '<a href=log.php?op=selesai>Log Out</a>';
exit;
}
else {
echo "<h3>Welcome ".$_SESSION['level']."</h3>";
echo '<a href=log.php?op=selesai>Log Out</a>';
}
?>
Thanks.
i choose and use #Ghanshyam answer,
thank you to all member at stackoverflow.
this is very helpfull site
Use following statement to set session for username while login-
session_start();
//following statement will create a session store user name.You can use this variable to display particular output.
$_SESSION["uname"] = $_GET['un'];
//in above statement 'un' is text box from which we are accepting username.
After set session variable for user name you can use it on another page-
session_start();
if(isset($_SESSION["uname"]) )
{
if($_SESSION["uname"] == 'admin')
{
echo 'hello admin';
}
else($_SESSION["uname"] == 'uname')
{
echo 'hello user';
}
}
else
{
echo "you must login"
}
The problem is in your operator selection.
if($_SESSION['level']="admin"){
echo "panel admin";
}
should be
if($_SESSION['level'] == "admin"){
echo "panel admin";
}
= is an assignment operator. And you need to use == or ===
I have a form that only opens if you're logged in, or at least thats what I'm trying to do, but it opens without having to do it. When I go to the log in page it sends me to the other page like if I was logging in, but it doesn't even show me the login page, heres the code:
this one is for the log in:
<?php
include ("conexion/conexion.php");
include("usuarios.class.php");
$usuario= $_POST['usuario'];
$clave= $_POST['clave'];
$objUsuario = new usuarios;
$srt= $objUsuario->autenticar_usuario($usuario,$clave,1);
$num =mysql_num_rows($srt);
if($usuario=="" || $clave==""){
$mensaje="campos en blanco";
header("location:loginusuario.php?mensaje=$mensaje");
}else
{
$objUsuario = new usuarios;
$srt= $objUsuario->autenticar_usuario($usuario,$clave,1);
$num =mysql_num_rows($srt);
}
if($num <= 0){
$mensaje="Usuario y/o clave Incorrectos";
header("location:loginusuario.php?mensaje=$mensaje");
}else{
$row=mysql_fetch_array($srt);
session_start();
$_SESSION['log'] = 's';
$_SESSION['nombre'] = $row['nombre'];
header("location:contrataciones.php");
}
?>
this is for the security file:
<?php
session_start();
if($_SESSION['log']!= 's'){
$mensaje="Iniciar sesion";
header("location:loginusuario.php?mensaje=$mensaje");
}
?>
and this is the class I'm using
<?php
class usuarios
{
function usuarios() {
}
function autenticar_usuario($usuario,$clave){
$sel="select usuario,clave from usuarios where usuario='".$usuario."' and clave='".$clave."' ";
$srt=mysql_query($sel) or die($sel);
return $srt;
}
?>
please tell me what am I doing wrong I'm a noob in this so I dont really get whats the problem
Why don't you try with
if(isset($_SESSION)){
//statement
//statement
}
or
if(isset($_SESSION['session_var_name'])){
//statement
//statement
}
I am creating a web based application using HTML5, it is connected to a mySQL database. I am trying to use PHP to connect the two.
I am trying to create a login page that checks the number and password against that in the database to see if it is a valid login.
Hard coding the number and password works fine but when trying to apply it to the database I always get a 'Logged in' message even though the login credentials are invalid. I tried using both $_POST and $dbRow but to no avail.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$s_number) {
if ($_POST["passwd"]==$s_pass) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
I am very new to PHP. I have searched for other examples but there seems to be many different ways to do this that I dont understand. Any help would be much appreciated!
Try this:
<?php
include ("dbConnect.php");
if(isset($_POST["snumber"]))
{
$s_number = mysql_real_escape_string($_POST["snumber"]);
$s_pass = mysql_real_escape_string($_POST["passwd"]);
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_assoc($dbResult);
if ($dbRow["staff_number"]==$s_number && $dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
}
else {
echo "<p>Bad username and password</p>";
}
?>
PS: Go for mysqli or PDO ;) ; you can try a count or a mysql_num_rows to see if the match result is zero.
Saludos .
Adrian and Robert have addressed parts of the problem.
If you're just learning PHP then all the more reason that you should start writing your code to use the mysqli API rather than the deprecated mysql_ functions. They are almost the same - but the latter will disappear at some point in the future.
If you're writing a login page then you're presumably concerned about security - however without properly escaping your code it's trivial to bypass the control mechanism (and in some cases exposes your database to serious vandalism / disclosure issues).
Further even by fixing the SQL injection problem, it's easy to get past the authentication using session fixation.
The next mistake is that you never check if the interactions with the database are successful or not.
Hence this looks like a duplicate of this question - although I've not flagged it as such due the poor quality of the answers / discussion on that post.
Further, since you've only SELECTed rows from the database matching the username / password, why do you then compare the username and password with the data you retrieved?
It's generally considered good security practice, to NOT explain why the login failed when some provided authentication details.
So trying again....
<?php
session_start();
include ("dbConnect.php");
function auth($user, $pass)
{
$user=mysqli_real_escape_string($user);
$pass=mysqli_real_escape_string($pass);
$qry="SELECT SUM(1) AS matches
FROM YOURDB.staff_details
WHERE staff_number='$user'
AND password='$pass'";
$res=mysqli_query($qry) || die "Sorry - not available";
$r=mysql_fetch_assoc($res);
return $r['matches'];
}
if (auth($_POST["snumber"], $_POST["passwd"])) {
session_regenerate_id();
echo "<p>Logged in!</p>";
} else {
echo "<p>Sorry - invalid authentication</p>";
}
You need to use $dbRow instead of $_POST.
As currently you are just comparing $_POST with $_POST.
It's always going to be the same.
Secondly, you've specified different field names in your query and array key.
Try this.
<?php
session_start();
$s_number = $_POST["snumber"];
$s_pass = $_POST["passwd"];
//$s_number = "12345";
//$s_pass = "qwerty";
//$s_permission = "manager";
include ("dbConnect.php");
$dbQuery = "SELECT * FROM staff_details WHERE staff_number='$s_number' AND password='$s_pass'";
$dbResult = mysql_query($dbQuery);
$dbRow=mysql_fetch_array($dbResult);
if ($_POST["snumber"]==$dbRow['staff_number']) {
if ($_POST["passwd"]==$dbRow['password']) {
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
else echo "<p>Bad username and password</p>";
/*if ($dbRow["username"]==$s_number) {
if ($dbRow["password"]==$s_pass) {
echo "<p>Logged in!</p>";
}
else {
echo "<p>Wrong Password</p>";
}
} else {
echo "<p>Bad username and password</p>";
}*/
?>
EDIT: Although you don't really need to do the If Statement after.
If you're getting a result from your DB query with the Username/Password matching, the credentials are correct.
So you could do,
if (!empty($dbRow)){
echo "<p>Logged in!</p>";
} else {
echo "<p>Wrong Password</p>";
}
}
I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.