Why doesn't my session work? - php

hey guys i dunno why i couldnt echo $_SESSION['name'] on index.php
says
Undefined index: name in C:\xampp\htdocs\STT\index.php on line 52
You are logged as
PHP code:
$username = (isset($_POST['username'])) ? trim($_POST['username']) : '' ;
$password = (isset($_POST['password'])) ? trim($_POST['password']) : '' ;
if (isset($_POST['submit']) && ($_POST['submit'] = 'Login')) {
$query='SELECT * FROM user_info WHERE username = "'. $username .'" AND password = PASSWORD("'. $password .'") ';
$result = mysql_query($query) or die(mysql_error()) ;
$count = mysql_num_rows($result) ;
if ( $count == 1 ) {
$_SESSION['logged'] = 1 ;
$_SESSION['name'] = $_POST['username'] ;
echo 'successfully logged.' ;
header ('Refresh : 5 ; URL = index.php') ;
}
else {
echo 'Invalid username or password' ;
$_SESSION['logged'] = 0 ;
}
}
and index.php
<?php
if ( $_SESSION['logged'] = 1) {
echo 'You are logged as' . $_SESSION['name'] ;
}
else {
echo 'WTF';
}
?>

I don't see session_start() anywhere.
Start new or resume existing session
Be sure to add it before any output to the page (includes whitespace).

Did you have
session_start();
in every page you use session?

Related

Display User Profile after Login in php

i am new in php and still learning session in php. i want to display user profile after login. i use session. so, when user login, user can see and her profile. i have try but still cant. please help me.
this is login process.php
<?php
session_start();
require_once("connection.php");
$email = $_POST['email'];
$password = $_POST['password'];
$name = $_POST['name'];
$nname = $_POST['nname'];
$bln = $_POST['bln'];
$gender = $_POST['gender'];
$cekuser = mysql_query("SELECT * FROM user WHERE email = '$email'");
$jumlah = mysql_num_rows($cekuser);
$hasil = mysql_fetch_array($cekuser);
if($jumlah == 0) {
echo "<script>alert('Email belum terdaftar!'); window.location = 'index.php'</script>";
} else {
if($password > $hasil['password']) {
echo "<script>alert('Password Salah!'); window.location = 'index.php'</script>";
} else {
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['name'] = $name;
$_SESSION['nname'] = $nname;
$_SESSION['bln'] = $bln;
$_SESSION['gender'] = $gender;
header('location:index.php');
}
}
?>
this is index.php
<?php
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
require_once("connection.php");
include("lib_function.php");
?>
<---header--->
<?php
include "connection.php";
$sql = "SELECT name, email, nname, bln, gender e FROM user WHERE email = '" . $_SESSION['email'] . "'";
$result = mysql_query($sql);
if ($result !== false) {
$row = mysql_fetch_array($result);
echo "Hello, " . $row['name'] . " <br> " . $row['nname'] ."<br> " . $row['bln'] . " <br> " . $row['gender'] . "(" . $row['email'] . ").";
} else {
// an error has occured
echo mysql_error();
die;
}
?>
There was something wrong with your if() statement. It was telling if $password is greater than $hasil['password']. But it have to be equal and you also trying to collect it from an array. So this statement should be:
Process.php:
if($password != $jumlah["password"]) {
This line says: if $password is not equal to $jumlah["password"]
For the second file, you have defined the $_SESSION variables, so there is no need to collect the information again with MySQL (Unless you need the realtime details, than the only thing you need to remove is the include line, this is a double line. Also replace mysql_fetch_array with mysql_fetch_assoc).
You may want to check if the sessions exists, so I have write a little example to check that.
index.php would look like:
<?php
if(session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
require_once("connection.php");
include("lib_function.php");
?>
<---header--->
<?php
# Check if session 'name' exists
if(isset($_SESSION["name"])) {
echo "Hello, " . $_SESSION['name'] . " <br> " . $_SESSION['nname'] ."<br> " . $_SESSION['bln'] . " <br> " . $_SESSION['gender'] . "(" . $_SESSION['email'] . ").";\
}else{
// Do an action to show the user that there is no session.
}
?>
I hope this will solve your problem :-)
Note that MySQL is deprecated in the newer versions of PHP, use PDO or MySQLi instead. Also your code looks vulnerable to SQL and XSS injections, it's important to learn about security too while learning in PHP :-)
Use this
<?php
$cekuser = mysql_query("SELECT * FROM user WHERE email = ".mysql_real_escape_string($email) "AND password = ".mysql_real_escape_string($password));
$jumlah = mysql_num_rows($cekuser);
if($jumlah > 0) {
$_SESSION['email'] = $email;
$_SESSION['password'] = $password;
$_SESSION['name'] = $name;
$_SESSION['nname'] = $nname;
$_SESSION['bln'] = $bln;
$_SESSION['gender'] = $gender;
header('location:index.php');
} else {
echo "<script>alert('Password Salah!'); window.location = 'index.php'</script>";
}
?>
It Prevents to you from mysql injections
Try Something like this
Hope it will work
Thanks
it should work
Remove the extra blank lines between session_start() function in your process.php & index.php
like this
<?php
session_start();
//codes here
?>
<?php
if (session_status() == PHP_SESSION_NONE || session_id() == '') {
session_start();
}
// codes here
?>

Session variable not getting in another inner file PHP

I have one login form when user give username and password it leads to login.php file
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
echo "query successfull wrote to DB";
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
echo "unscccessful login";
header('location:index.php');
}
}
When I Try to print the session by print_r($_SESSION) from this file.. it shows the session and its variable with values
Array ( [userNameSession] => full name [loginStatus] => 1 )
In my admin/admin.php (opens when successful login) wrote
session_start();
print_r($_SESSION);exit;
if try to print the session by print_r($_SESSION) it shows empty array as Array()
Please help.
Why do you make an unset($_SESSION)? This may cause the session variable is deleted but the session still exists.
If you want to clean $_SESSION['LoginStatus'] and $_SESSION['userNameSession'], better clean one by one (although this is not necessary because you'll rewrite its value later):
unset($_SESSION['LoginStatus']);
unset($_SESSION['userNameSession']);
The code must be like this:
session_start();
if ( !empty($_POST['username']) && !empty($_POST['password']) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " YOUR QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
if (mysql_num_rows($result) > 0) {
//DELETE prints BEFORE header()!! -> echo "query successfull wrote to DB";
$row = mysql_fetch_assoc($result);
unset($_SESSION['userNameSession']);
unset($_SESSION['loginStatus']);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
//DELETE prints BEFORE header()!! -> echo "unscccessful login";
header('location:index.php');
}
}
One important thing that you must notice:
Don't echo before header. I think your code should be like this:
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
header('location:index.php');
}
}
Hope this helps.

login php not working

I've this set of login codes. When I type the correct password, I'll be able to get into the webpage. But I'm not sure why, when I type the wrong password, I will still be able to get into the webpage.
I am not sure where is the error.
This is my php code:
<?php
//define page title
$title = 'Sign In';
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
if(isset($_POST['btn-login']))
{
$UserEmail = isset($_GET['UserEmail']) ? $_GET['UserEmail'] : '';
$Password = isset($_GET['Password']) ? $_GET['Password'] : '';
$result=mysql_query("SELECT * FROM tbl_user WHERE UserEmail='$UserEmail'");
$row=mysql_fetch_array($res);
if($row['Password']=md5($Password))
{
$_SESSION['user'] = $row['Password'];
header("Location: home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
You are posting form then you would get variables in $_POST not $_GET.
$UserEmail = isset($_POST['UserEmail']) ? $_POST['UserEmail'] : '';
$Password = isset($_POST['Password']) ? $_POST['Password'] : '';
The first thing I noticed wrong is
if($row['Password']=md5($Password))
Use '==' (double equal) for equality check. Single equal is assignment
if($row['Password']==md5($Password))
if(isset($_SESSION['user'])!="")
that one is senseless too. I'm almost sure that it will always pass because "false"!=""
So change it to
if(isset($_SESSION['user']) && !empty($_SESSION['user']))
You are not checking user password, that is why it will allow you to access page with wrong credentials.
Try this,
<?php
//define page title
$title = 'Sign In';
session_start();
include_once 'dbconnect.php';
if(isset($_SESSION['user'])!="")
{
header("Location: home.php");
}
if(isset($_POST['btn-login']))
{
$UserEmail = isset($_GET['UserEmail']) ? $_GET['UserEmail'] : '';
$Password = isset($_GET['Password']) ? $_GET['Password'] : '';
$result=mysql_query("SELECT * FROM tbl_user WHERE UserEmail='$UserEmail' and password='$Password'");
$row=mysql_fetch_array($res);
if($row['Password']=md5($Password))
{
$_SESSION['user'] = $row['Password'];
header("Location: home.php");
}
else
{
?>
<script>alert('wrong details');</script>
<?php
}
}
?>
Replace your query with below:
<?php
//define page title
$title = 'Sign In';
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['btn-login'])) {
$UserEmail = isset($_GET['UserEmail']) ? $_GET['UserEmail'] : '';
$Password = isset($_GET['Password']) ? $_GET['Password'] : '';
$result = mysql_query("SELECT * FROM tbl_user WHERE UserEmail='$UserEmail' AND Password='" . md5($Password) . "'");
$row = mysql_fetch_array($result);
if (count($row) > 0) {
$_SESSION['user'] = $row['Password'];
header("Location: home.php");
} else {
?>
<script>alert('wrong details');</script>
<?php
}
}
?>

Php Function Restricted area

Hey i have this function :
<?php
if(isset($_POST['login']) && $_POST['login'] == 'LOGARE') {
include('./inc/configurare.php');
mysql_select_db('account');
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$check = "SELECT * from account where login = '" . $user . "' and password = PASSWORD('$pass')";
$query = mysql_query($check);
$num = mysql_num_rows($query);
if($num > 0) {
$array = mysql_fetch_array($query);
// SESSION variable start //
$_SESSION['id'] = $array['login'];
$_SESSION['coins'] = $array['coins'];
$_SESSION['isadmin'] = $array['isadmin'];
$_SESSION['pscadmin'] = $array['pscadmin'];
$_SESSION['email'] = $array['email'];
$_SESSION['real_name'] = $array['real_name'];
$_SESSION['social_id'] = $array['social_id'];
$_SESSION['user_admin'] = $array['web_admin'];
$_SESSION['user_id'] = $array['id'];
$_SESSION['user_name'] = $array['login'];
$_SESSION['user_coins'] = $array['coins'];
$_SESSION['user_email'] = $array['email'];
echo "<meta http-equiv='refresh' content='0; URL=index.php?s=home'>";
} else {
echo "<meta http-equiv='refresh' content='0; URL=index.php?s=login_error'>";
}
}
?>
And i wanna restrict acces on some page , you must login to intro in that page somting like this:
<?php
if(isset($_SESSION['user']) && isset($_SESSION['pass']))
{
auto_unban();
$username = $_SESSION['user'];
$sql = mysql_query("Select * from account.account where login='".$_SESSION['user']."'") or die(mysql_error());
$accc=mysql_fetch_object($sql);
$charss = mysql_query("Select * from player.player where account_id='".$accc->id."'") or die(mysql_error());
$chars = mysql_num_rows($charss);
?>
<script type='text/javascript'>
function myFunction()
{
var jmsg = "<? echo "Blocked : ".$acc->unban_date." pentru ".$acc->motiv_ban.".mlock."; ?>";
if(jmsg){
alert(jmsg);
}
window.onload=myFunction;
}
</script>
Script , script
<?php } else { echo "Please login!";} ?>
That script when i don't login show me this echo : Please login!
and when i'm login also show me that echo : Plase login!
I don't know how to create and read function in php can anyone show me how to make function like this :
if(isset($_SESSION['user']) && isset($_SESSION['pass']))
Your variable $_SESSION['login'] is empty because you forgot to call session_start(); at the beginning of your php script.
Place session_start(); before printing any chars on your page.
ex:
<?php session_start();
$_SESSION['login'] = 'login';
...

login with cookies and sessions

how can i make cookies safe
i want make login by sessions and cookies i try to make this
this is my code
<?php
$my_username =IsSet($_POST['username']) ? make_it_safe($_POST['username']) :Null;
$my_userpass =IsSet($_POST['userpass']) ? make_it_safe($_POST['userpass']) :Null;
$saveinfo =IsSet($_POST['save_info']) ? make_it_safe($_POST['save_info']) :Null;
if(empty($my_username)){
echo "<div class='alert alert-error'>Insert Username</div>";
}else if(empty($my_userpass)){
echo "<div class='alert alert-error'>Insert Userpass</div>";
}else {
$my_userpass = sha1($my_userpass) ;
$select = $mysqli->query("SELECT * FROM members WHERE username='$my_username' AND userpass='$my_userpass' LIMIT 1");
$num = $select->num_rows;
if($num){
$rows = $select->fetch_array(MYSQL_ASSOC);
$id = $rows ['id'];
$username = $rows ['username'];
$userpass = $rows ['userpass'];
if($username == $my_username && $userpass == $my_userpass){
$_SESSION['id'] = $id ;
$_SESSION['username'] = $username ;
if ($saveinfo == 'on'){
setcookie("id",$_SESSION['id'],time()+2592000);
setcookie("username",$_SESSION['username'],time()+2592000);
}
header("Location: home.php");
}
}else{
echo "Error";
}
?>
Is this the right way in Login with cookies and Is it safe?

Categories