Var.$logged defined in global.php, not picked up by index.php - php

I was attempting to follow along with the tutorial at the YouTube channel Helping Develop
when I came across a few issues. The first being his logout code in tutorial #5 doesn't work anymore due to the changed
if(session_is_registered()
I think I have replaced that properly with
if( isset($_SESSION[$username])){
But now I am getting an error that says
"Notice: Undefined variable: logged in C:\xampp\htdocs\membership\index.php on line 2"
When I check line 2 of index it shows that i am including global.php first
<?php include_once('scripts/global.php');
if($logged==1){
header("Location:home.php");
exit();
}
?>
So then I check global.php which has $logged=1 so it should be defined...unless I am missing something. I am really trying to learn more here, so any help would be appreciated in explaining what is wrong, and why.... Thank you.
<?php
session_start();
include_once('scripts/connect.php');
//checking if the sessions are set
if(isset($_SESSION['username'])){
$session_username=$_SESSION['username'];
$session_pass=$_SESSION['pass'];
$session_id=$_SESSION['id'];
//checking the member data
$query=mysql_query("SELECT * FROM members WHERE
id='id' AND password='pass' LIMIT 1")or die("Could not check member");
$count_count=mysql_num_rows($query);
if(count_count>0){
//logged in stuff here
$logged=1;
}else{
header('Location:logout.php');
exit();
}
}elseif(isset($_COOKIE['id_cookie'])){
$session_id=$_COOKIE['id_cookie'];
$session_pass=$_COOKIE['pass_cookie'];
//checking the member data
$query=mysql_query("SELECT * FROM members WHERE
id='$session_id' AND password='$session_pass' LIMIT 1")or die("Could not check member");
$count_count=mysql_num_rows($query);
if(count_count>0){
while($row=mysql_fetch_array($query)){
$session_username=$row['username'];
}
//create sessions
$_SESSION['username']=$session_username;
$_SESSION['id']=$session_id;
$_SESSION['pass']=$session_pass;
//logged in stuff here
$logged=1;
}else{
header('Location:logout.php');
exit();
}
}
?>

$logged is set inside a conditional, so trace back through to understand how you might not hit a random redirect (reminds me of the crazy "goto" days which I through we progressed past) and end up with $logged not being set. Or initialize $logged at the beginning of the included script.

Related

How to fix PHP errors while trying to create a login.php that displays username at a new page on successful login?

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!

Session variable not stored on other pages

i am using session variable to send details of user from login page to welcome page .
here is my code :
<?php
if(isset($_POST['login']))
{
$email=$_POST['email'];
$pass=md5($_POST['password']);
$a="SELECT * FROM users WHERE email='$email'AND password='$pass'";
$log=mysqli_query($con,$a);
$row=mysqli_fetch_array($log);
if(mysqli_num_rows($log)>0){
$_SESSION['firstname']=$row['first_name'];
$_SESSION['lastname']=$row['last_name'];
header("location:welcome.php");
exit;
}
else{
$er="login failed!";
}
}
on Welcome.php
<h2>WELCOME : <?php echo $_SESSION['firstname'];?></h2> <--- line 63-->
but i am getting this error :
Notice: Undefined index: firstname in
C:\xampp\htdocs\website\welcome.php on line 63
PS : kindly dont mark it as duplicate I tried many solutions but not helping. I used session_start(); on every page .
A session is started with the session_start() function.
in 1st page:
if(mysqli_num_rows($log)>0){
$row=mysqli_fetch_array($log);
session_start();
$_SESSION['firstname']=$row['first_name'];
$_SESSION['lastname']=$row['last_name'];
if(isset($_SESSION['firstname']))
header("location:welcome.php");
exit;
}
on page 2:you might have write this line at 1st line:
<?PHP
session_start();
?>
<h2>WELCOME : <?php if(isset($_SESSION['firstname'])) {echo $_SESSION['firstname'];}?></h2>
Edit: this answer is not correct and I will remove it when the comment-discussion has ended.
You fetch the first row of $log and then AFTER that check if the number of rows in $log is bigger than 0. Although you had one row initially, you fetched it! so at the time you check mysqli_num_rows($log) it will be 0, therefore never setting $_SESSION['firstname'] and $_SESSION['lastname'].
Try checking for number-of-entries before fetching the row like this:
$a="SELECT * FROM users WHERE email='$email'AND password='$pass'";
$log=mysqli_query($con,$a);
if(mysqli_num_rows($log)>0){
$row=mysqli_fetch_array($log);
$_SESSION['firstname']=$row['first_name'];
$_SESSION['lastname']=$row['last_name'];
header("location:welcome.php");
exit;
}

Remove variable from URL

This is for a simple login system, any time a user receives an error I redirect them to a another page (using header(Location:...)) and put the error ID in the URL so that I know which error to display.
login.php
<?php
if(isset($_GET[ 'status'])){
if($_GET[ 'status']=='error' ){
?>
<p style='color:red;'>Incorrect Username/Password combination!</p>
<?php
} }
?>
Checklog.php
<?php
include('../dbconnect.php');
$username =$_POST['form-username'];
$pwd =$_POST['form-password'];
$result = mysql_query("SELECT * FROM member WHERE email='$username' and password='$pwd'") or die ('Query failed:'.mysql_error());
//$admin=mysql_query("SELECT * FROM admin where user='$username' and code='$pwd'") or die ('Query failed:'.mysql_error());
if (mysql_num_rows($result)>0){
session_start();
$_SESSION['user']=$username;
//echo "hello $username";
header("Location:../homepage.html");
}
/*else if (mysql_num_rows($admin)>0){
session_start();
$_SESSION['admin']=007;
header("Location:add1.php");
}*/
else
{
header("Location:login.php?status=error");
}
mysql_free_result($result);
mysql_close($con);
?>
On refresh the error message is still here, is there a solution how i can redirect the user to the original login.php without the error message if he refresh
You can use javascript window.history.pushState to alter the URL after the document has fully loaded. This will change the URL in the address bar and affects the address they are taken to on refresh.
Alternatively you can store messages in the $_SESSION and clear the message after it has been displayed.
I agree with henrys answer. Personally id use $_SESSIONS but as as your question was to remove url parameters the only way would be js.
For example
history.pushState(null,null, window.location.href.split('?')[0]);
This is untested but should do what you want in a single line of code.

Updating user information

I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>

Pass the login details to another page using session PHP

I need the login details in another page for retrieving the data from the database. Basically, I need to display the editable form with the details of the user logged in. I tried session_register() for storing the username in login.php page. But for some reason I am not able to display the username using $_SESSION[] in my edit.php page. I am doing this after the function session_start() as well.
I am new to php, so don't know whether I misunderstood session! Or is there any other way to pass the login details?
Thanks in advance
My code:
**Login.php**
<?php
$userName = $_POST['username'];
$password = $_POST['password'];
//Connect to the database
//query the database
if($rows==1)
{
session_start();
$_SESSION['user']=$userName;
header("location:edit_user.php");
}
else
{
echo 'Data Does Not Match <br /> Re-Enter UserName and Password';
}
?>
**In edit.php**
<?php
session_start();
if(!isset($_SESSION['user']))
{
header("location:login_form.php");
}
else
{
echo $_SESSION['user'];
}
?>
First of all make sure that you place session_start() at the very beginning of any script you use it in. There can be no output to the browser before you call session_start() and that includes spaces or new-lines before the opening <?php tag.
So:
<?php
session_start();
...
Second, make sure you terminate your script after a redirect, for example:
header("location:edit_user.php");
exit();
That makes sure that no code after the redirect gets executed, so sessions won't get unset or session variables changed by accident.
session_register() is a deprecated function. Just use $_SESSION["bar"] = "foo" to store something.
for future references, please post parts of your code when you are asking questions. It helps everyone to give you an answer in more specific cases.
<?php
session_start();
if(!isset($_SESSION['Foo']))
{
$_SESSION['Foo'] = "Bar";
}
?>
Source : http://php.net/manual/en/features.sessions.php
you can retrive data from the database like this
//start connection
$connect = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD);
if(!$connect){
die("Database connection Error".mysql_error());
}
//select database
$db = mysql_select_db(DB_NAME);
if(!$db){
die("Database selection Error".mysql_error());
}
//get data
$login = mysql_query("SELECT * FROM TABLENAME where user_id={$_SESSION['user_id']}");
$login_data = mysql_fetch_array($login);
now $login_data array has the user details which you can point to form text field values..
the $_session['user_id']=$login_data['user_id'] value has to be assigned earlier which stays in the $_SESSION global variable through out the session

Categories