How can I get the field id for a session? - php

I am new at php and I followed some youtube video's to build a littel project.
I have a table of users:
id
username
email
password
and I'm trying to build a private message system. I want to get the id of the user that is now logged in. But when I write my_id = $_Session[ 'id' ] I get an error : "Undefined index: id" but when I write $my_id = $_SESSION['username'] I get the username with no error and it echo's me the username. What is the difference?
That is all the code:
<?php
session_start();
$db = mysqli_connect( "localhost", "root", "", "travelersdb" );
if( #$_SESSION[ "username" ] )
{
?>
<html>
<head>
<title>Home Page</title>
</head>
<?php
include( "header.php" );
echo "<center><h1>Private Message System</h1>";
include( "message_title_bar.php" );
if( isset( $_GET[ "user" ] ) && !empty( $_GET[ "user" ] ) )
{
?>
<form method = 'post' >
<?php
if( isset( $_POST[ "message"] ) && !empty( $_POST[ "message" ] ) )
{
$user=$_GET['user'];
$my_id = $_SESSION['username']; // ------> Doesn't work when changed to 'id'
$random_number = rand();
$sql_m = "SELECT 'hash'
FROM message_group
WHERE ( user_one = '" . $my_id . "' AND user_two = '" . $user . "' )
OR ( user_one = '" . $user . "' AND user_two = '" . $my_id . "' )";
$check_con = mysqli_query( $db, $sql_m );
$rows = mysqli_num_rows( $check_con );
if( $rows == 1 )
{
echo "<p>Conversation already started!</p>";
}
else
{
echo $user . "</br>";
echo $my_id; -------> Wanted to echo the $my_id to check...
echo $random_number;
// $sql_In = "INSERT INTO message_group( user_one, user_two, hash )
// VALUES( '1111', '2222', '2222' )";
// mysqli_query( $db, $sql_In );
echo "<p>Conversation Started</p>";
}
}
?>
Enter Message : </br>
<textarea name = 'message' rows = '7' cols = '60'>
</textarea>
<br></br>
<input type='submit' value="Send Message" />
</form>
<?php
}
else
{
echo "<b>select user</b>";
$sql = "Select id,username from users";
$check = mysqli_query($db,$sql);
while ( $run_user = mysqli_fetch_array( $check ) )
{
$user = $run_user[ 'id' ];
$username = $run_user[ 'username' ];
echo "<p><a href = 'send.php?user=$user'>$username</a></p>";
}
}
?>
</html>
<?php
}
else
{
echo "You must be logged in.";
}
?>
Update: done this but still is doesn't work. doesn't identify the id. this is the login.php:
<?php
session_start();
//connect to database
$db=mysqli_connect("localhost","root","","travelersdb");
if(isset($_POST['login_btn']))
{
//$username=mysql_real_escape_string($_POST['username']);
//$password=mysql_real_escape_string($_POST['password']);
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
$password=md5($password); //Remember we hashed password before storing last time
$sql="SELECT * FROM users WHERE username='$username' AND password='$password'";
$result=mysqli_query($db,$sql);
if(mysqli_num_rows($result)==1)
{
$_SESSION['message']="You are now Loggged In";
$_SESSION['username']=$username;
$sql_t = "select id from users where username='$username' AND password='$password'";
$id = mysqli_query($db, $sql_t);
$_SESSION['id']=$id;
header("location:index.php");
}
else
{
$_SESSION['message']="Username and Password combiation incorrect";
}
}
?>

You may haven't set it to the session.
Use print_r($_SESSION); and check whether your index -> id is there or not.

$_SESSION index is like a variable name for your session value. If you haven't created this session/variable before, you can not retrieve its value because it is undefined

Related

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.

Action script for login form not working

having problems understanding why my script to login will not work, so its a simple login script that checks the users and fields as expected yet when it does the logic it does not seem to be loggin in the users :S
action script:
<?php
if ( $SERVER[ 'REQUEST_METHOD' ] == 'POST' )
{
require ( 'connect_db.php' );
require ( 'login_tools.php' );
list ( $check , $data ) =
validate ( $dbc , $_POST[ 'email' ] , $_POST [ 'pass' ] ) ;
if ( $check )
{
session_start() ;
$_SESSION[ 'user_id' ] = $data [ 'user_id' ] ;
$_SESSION[ 'first_name' ] = $data [ 'first_name' ] ;
$_SESSION[ 'last_name' ] = $data [ 'last_name' ] ;
load ('home.php');
}
else { $errors = $data ; }
mysqli_close( $dbc );
}
?>
An action script to process the login:
<?php
function load( $page = 'login.php')
{
$url = 'http://' . $SERVER['HTTP_HOST'] .
dirname( $_SERVER ['PHP_SELF'] );
$url = rtrim( $url , '/\\' );
$url = '/' . $page ;
header ( "location: $url" );
exit();
}
function validate( $dbc , $email = ',$pwd = ')
{
$errors = array();
if (empty($email))
{ $errors[] = 'Enter your email address.' ; }
else
{ $e = mysqli_real_escape_string( $dbc , trim( $email ) ) ; }
if (empty($pwd))
{ $errors[] = 'Enter your password.' ; }
else
{ $e = mysqli_real_escape_string( $dbc , trim( $pwd ) ) ; }
if ( empty( $errors ) )
{
$q = "SELECT user_id, first_name, last_name FROM users WHERE enail = '$e' AND pass = SHA1( '$p' )";
$r = mysqli_query ( $dbc , $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
$row = mysqli_fetch_array ( $r , MYSQLI_ASSOC );
return array (true , $row );
}
else
{
$errors[] = 'Email address and password not found.' ;
}
return array( false , $errors) ; }
}
?>
And it will land here...
<?php
session_start();
if ( !isset( $_SESSION[ 'user_id' ] ) )
{
require ( 'login_tools.php' ) ;
load() ;
}
$page_title = 'Home' ;
echo'<p>
logout
</p> ';
?>
The login script tried to execute login_action.php but dosnt move from there...I have no syntax errors though?
You misspelled $_SERVER variable - there is not such thing like $SERVER
EDIT
login_tools.php
function validate($dbc, $email = ',$pwd = ')
should be:
function validate($dbc, $email = '' , $pwd = '')
next:
$e = mysqli_real_escape_string($dbc, trim($pwd));
should be:
$p = mysqli_real_escape_string($dbc, trim($pwd));
and return statement move after if statement:
if (empty($errors)) {
...
}
return array(false, $errors);
I hope that you're playing around with PHP or something, beacuse this is really bad code. But you know that, right?
Ok so I found a new script to see if I can see if it its a problem with the database, table or the script - Heres the new script:
Login.php
<h1>Login</h1>
<form action="login_action.php" method="POST">
<p>
Email Address: <input type="text" name="email" />
</p><p>
Password: <input type="password" name="pass" />
</p><p>
<input type="submit" value="login" />
</p>
</form>
checklogin.php
<?php
include ('connect_db.php');
$myemail=$_POST['email'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myemail = stripslashes($myemail);
$mypassword = stripslashes($mypassword);
$myemail = mysql_real_escape_string($myemail);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT user_id, email, first_name, last_name FROM users WHERE email='$myemail' and pass='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("email");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong email or Password";
}
?>
login_success.php
<?php
session_start();
if(!session_is_registered(email)){
header("location:login.php");
}
?>
<html>
<body>
Login Successful
</body>
</html>
The error I get now is the email or password is wrong? I know that it isnt...

Having trouble with php login page

I am newbie to php and I was just building simple login page with php here is my code:
<?php
$username=$_POST['uname'];
$password=$_POST['pass'];
$con=mysqli_connect("localhost","root","","myblog");
$sql="SELECT username,password FROM users WHERE username='$username' AND password='$password'";
if(mysqli_query($con,$sql)) {
echo "login successful";
} else {
echo "login failed";
}
?>
The problem is I am getting "login successful" message even with the wrong credentials(random inputs).
Please someone guide me.
you dont have to check if query was succesfull, but if result has some rows..
$answer = mysqli_query($con,$sql)
if( mysqli_num_rows($answer)>0 ) { ... there is such record... }
try this
<?php
include "connect.php";
if ($_SERVER['REQUEST_METHOD'] == "POST"){
$email = filter_var( $_POST['email'] , FILTER_SANITIZE_EMAIL) ;
$password = $_POST['password'] ;
$token = $_POST['token'] ;
$stmt = $con->prepare("SELECT * FROM users WHERE email = ? AND password = ?") ;
$stmt->execute(array($email , $password));
$user = $stmt->fetch() ;
$row = $stmt->rowcount() ;
if ($row > 0) {
$id = $user['id'] ;
$stmt2 = $con->prepare("UPDATE users SET token = ? WHERE id = ? ") ;
$stmt2->execute(array($token , $id )) ;
$ username = $user['username'] ;
$email = $user['email'] ;
$password = $user['password'] ;
echo json_encode(array('id' => $id , 'username' => $username ,'email' =>
$email ,'password' => $password , 'status' => "success"));
}else {
echo json_encode (array('status' => "faild" , 'email' => $email ,
'password' => $password) );
}
}
?>
try this
you have to check whether result produced or not ... Instead of query correct or not..
<?php
$username=$_POST['uname'];
$password=$_POST['pass'];
$con=mysqli_connect("localhost","root","","myblog");
$sql="SELECT username,password FROM users WHERE username='$username' AND password='$password'";
$result =mysqli_query($con,$sql);
$count = mysqli_num_rows($result);
if($count>0)
{
echo "login successful";
}
else
{
echo "login failed";
}
?>
Try to do it like this. use mysqli_num_rows()
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) >0){
echo "login successful";
}else {
echo "login failed";
}
try this
<?php
$username=$_POST['uname'];
$password=$_POST['pass'];
$username = mysql_real_escape_string(stripslashes($username));
$password = mysql_real_escape_string(stripslashes($password));
$con=mysqli_connect("localhost","root","","myblog");
$sql="SELECT username,password FROM users WHERE username='$username' AND password='$password' LIMIT 1 ";
$result = mysqli_query($con,$sql);
if($row = mysqli_fetch_assoc($result))
{
echo "login successful";
}
else
{
echo "login failed";
}
?>
Your Condition is not proper, also use LIMIT 1 whenever you trying to fetch exact one result.
You should pass your post variable through mysql_real_escape_string and stripslashes to prevent from sql injections

sql issue with registration form

I have created a registration form ( see code below ). There are two fields for the password, the second serving as a check and upon form submission I check if the input in the fields matches. If they don't a message is successfully sent that the passwords do not match but the new user record is still inserted into the database. How can I prevent record insertion if the password fields do no match?
Here is the code:
<?php
$username = isset( $_POST["username"] ) ? $_POST["username"] : "";
$password = isset( $_POST["password"] ) ? $_POST["password"] : "";
$confirm = isset( $_POST["confirm"] ) ? $_POST["confirm"] : "";
if( !empty( $username ) && !empty( $password ) ) {
if( $password != $confirm )
header( "location:registration.php?msg = Password does not be match." );
$host = "localhost";
$user = "i have put my username here";
$pass = "i have put my pass here";
$link = mysql_connect( $host,$user,$pass ) or die( mysql_error() );
mysql_select_db( "web_db",$link );
$query = "SELECT * FROM users WHERE username = '".mysql_escape_string( $username )."'";
$result = mysql_query( $query );
$count = mysql_num_rows( $result );
if( $count = = 1 ) {
header( "location:registration.php?msg = username already exists" );
} else {
$qry = "INSERT INTO users( username,password )VALUES( '".mysql_escape_string( $username )."', '".mysql_escape_string( $password )."' )";
mysql_query( $qry );
echo "You are successfully registered.";
}
mysql_close( $link );
} else {
header( "location:registration.php?msg = Username or password cannot be blank." );
}
Try this:
if($password != $confirm){
header("location:registration.php?msg=Password does not be match.");
exit;
}
else {
// rest of the code goes here
}
if ($password != $confirm) {
header("location:registration.php?msg=Password does not be match.");
exit();
}
Try using the above code it might help.

PHP Only Selecting First Row?

I have a quick login form that i made for school the only problem is that when i try and login everything worked perfectly when i want to log into the first user (Username: hbutler Password: password) However when i try to login to my other accounts i get the page refresh which i have set it do if it is incorrect here is my code :
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT * FROM User_info");
$row = mysqli_fetch_array($result);
$value = $row['username'];
if($value == "$username")
{
$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='$username'");
$row = mysqli_fetch_array($result);
$value = $row['password'];
if($value == "$password")
{
$sql=("UPDATE user_check SET user = '1', name = '$username'");
header( 'Location: feed.php' ) ;
}
else
{
header( 'Location: social.php' ) ;
}
}
else
{
header( 'Location: social.php' ) ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Which gets the form data from the previous page i do not know why this is happening and i have tryed changing the php to this :
$result = mysqli_query($con, "SELECT username FROM User_info");
$row = mysqli_fetch_array($result);
if($row == "$username")
Yet that doesnt work either any suggestions?
the problem is that, after your first query, to get the info from db, you are taking only the first row of the table,
$row = mysqli_fetch_array($result);
then comparing it with the submitted username, that's why you can't login with any other username, the solution is to add a WHERE clause to the first query,
$result = mysqli_query($con, "SELECT * FROM User_info WHERE username ='".$username."'");
then compare passwords that would be easier, but still, there are better ways to do the authentication. but for your example this should do.
Modify your code as below:
<?PHP
//Create the connection…
//("where the database is", 'Database login' , 'database password' , "Database name")
$con=mysqli_connect("", 'root', 'root', "Social");
//Check our connection…
if (mysqli_connect_errno($con))
{
echo " Sorry Mate";
}
$username = $_POST['username'];
$password = $_POST['pawd'];
$result = mysqli_query($con, "SELECT count(*) as count FROM User_info WHERE username ='$username' and password='$password'");
while( $rows = mysqli_fetch_array($con, $result) )
{ //Check for SQL INJECTION
if( $rows['count'] == 1 )
{
//$sql=("UPDATE user_check SET user = '1', name = '$username'");
//header( 'Location: feed.php' ) ;
//Other Operations
}
else
{
header( 'Location: social.php' ) ;
}
}
mysqli_close($con);
?>

Categories