Undefined index: username when using sessions - php

I'm working on a forum software right now, and I'm doing very well so far, it all works, but I can't get this to get away, I'm not really sure how.
I get Undefined index: username whenever I call
$_SESSION['username']
I start the session in a seperate login file, but get this error whenever calling it, I only get it when someone isn't logged in, so like if I'm logged in, it doesn't show it, only when I'm not logged in, how can I get rid of it?
Here's my whole code for the page:
<?php
session_start();
include_once("connect.php");
$find = "SELECT id,name,description FROM forums";
$run_find = mysql_query("$find");
if ($_SESSION['username']) {
print "Welcome, " . $_SESSION['username']. "!<br/>";
}
while($is = mysql_fetch_assoc ($run_find))
{
$id = $is['id'];
$name = $is['name'];
$des = $is['description'];
print "<div style='width:500px;background-color:#FFCCFF;'>";
print "Forum : <a href='topics.php?t=$id'>". $name . "</a><br/>" .$des . "<br/><hr>";
print "</div>";
}
if (!$_SESSION['username']) {
echo "
<form action='loginnext.php' method='post'>
Username: <input type='text' name='username'><br/>
Password: <input type='password' name='password'><br/>
<input type='submit' name='submit' value='Login'><br/></form>";
}
if ($_SESSION['username']) {
echo "<a href='logout.php'>Logout</a>";
}
?>

If the user is not logged in, the session variable will not be set, thus the error message.
Use if(isset($_SESSION['username'])) instead of if($_SESSION['username'])

if (!empty($_SESSION['username'])) is the construct you wanted. isset and empty can not throw notices.

Related

not getting session variables on second page while hosting my website (On localhost, it works)

Down, in the second page i am not getting the session variable values. Actually sessions variables are not recieving in second file(index.php).
Error is Notice: Undefined index: userid in /storage/ssd5/520/5088520/public_html/index.php on line 150
1 - login.php //file 1
session_start();
if (isset($_POST['login'] ))
{
$_SESSION["userid"] = $_POST["userid"];
$_SESSION["user"] = $_POST["user"];
$userid=$_SESSION["userid"];
$user=$_SESSION["user"];
if ($userid=='' || $user=='')
{
//generate error
echo 'ERROR: Please fill in all required fields!';
renderForm();
}
else
{
//query
$result = mysql_query("SELECT user_id FROM users WHERE user_id='$userid'
AND user='$user'") or die(mysql_error());
$row = mysql_fetch_array($result);
if ($row['user_id'] == 1 || $row['user_id'] == 2)
{
$_SESSION['login_status'] = true;
echo "<script> window.open ('index.php','_self') </script>";
}
else
{
echo "Sorry, No account exist";
}
}
}
//if submit button not pressed yet. show form:
else
{
//now show form
renderForm();
}
//redenring form
<?php
//function starts
function renderForm()
{
?>
<form role="form" method="post">
<input placeholder="User ID" name="userid" type="text">
<input placeholder="User" name="user" type="text">
<button type="submit" name="login">Login</a>
</form>
<?php
} //function ends
?>
Second file where error comes
2-index.php //file 2
<?php
session_start();
if ($_SESSION['login_status']==false) {
header("Location:login.php"); } else { ?> <body> //somewhere inside here i am accessing the session variables <?php
if ($_SESSION['userid']==1) //line 150
{
echo "<a class='navbar-brand' href='index.php'>Admin</a>";
}
if ($_SESSION['userid']==2 )
{
echo "<a class='navbar-brand' href='index.php'>Clerk</a>";
} ?> </body>
on local host. this code runs . But i am now hosting it. but i am not understanding, what can be the issue?
Declare session_start(); on second page.
You need to add session_start(); at the top of the second file in order to access session variables in it.
Add session_start(); in every page you are accessing session variables from otherwise it doesn't work. It is a requirement to start the session in order to access the super global variable $_SESSION.
Edit:
You need to use if( !isset($_SESSION['userid']) ) instead of
if ($_SESSION['userid']==1) on the index.php page.
Otherwise, it will throw you undefined index error if you are
visiting the index.php before attempting to log in.
You may have noticed that your code doesn't throw error if you visit index.php after logging in.

How to use Google+ Login

I managed to get the user information using Google+ login.
if (isset($authUrl)) {
echo "<a href='" . $authUrl . "'><img src='img/google.png'></a>";
} else {
print "ID: {$id} <br>";
print "Name: {$name} <br>";
print "Email: {$email } <br>";
print "Image : {$profile_image_url} <br>";
print "Cover :{$cover_image_url} <br>";
print "Url: {$profile_url} <br><br>";
echo "<a class='logout' href='?logout'><button>Logout</button></a>";
}
This is in a login.php file where the user logs in. How can I pass this data to the header.php so I can remove the Login and Register buttons and add the user name and image?
To pass info via GET:
For redirecting in php, you use header('Location:file_name')
header('Location: header.php?var1=val1&var2=val2');
Session:
// index.php
session_start(); //start session
$_SESSION['varName'] = 'varVal'; //make a session variable
header('Location: header.php'); // redirect to header.php
// header.php
session_start(); //start session
$myVar = $_SESSION['varName']; //access your session here
Post: Take a look at this.
Another way is to include a hidden field in a form that submits to page two:
<form method="post" action="header.php">
<input type="hidden" name="varname" value="var_value">
<input type="submit">
</form>
And then on header.php:
//Using GET
$var_value = $_GET['varname'];
//Using POST
$var_value = $_POST['varname'];
//Using GET, POST or COOKIE.
$var_value = $_REQUEST['varname'];
Just change the method for the form to get if you want to do it via get.
Happy Coding! :)

How do I destroy a session by clicking a button?

This should be an easy one, if I explain it well.
I am trying to create a web page, where the session starts when the user enters a name, the name is displayed constantly, until the user presses the log out button; which should end the session. The closest I have gotten to is this:
<if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST["name"];
echo "<input type='submit' name='logout' method='logout' value='Log out'>";
echo "</form>";
echo "</h1>";
echo "</div>";
if(isset($_POST['logout']) && ($_POST['logout'] == "Log out")) {
session_destroy(); }
but it doesn't end the session and the name keeps being displayed constantly once entered. i.e. There is no way to end the session.
If you need any more explanation, or more of the code to understand, please let me know. Any help is much appreciated.
You can change session_destroy() by unset($_SESSION['name']) , like this:
if (isset($_POST['name'])) {
$_SESSION['name'] = $_POST["name"];
echo "<input type='submit' name='logout' method='logout' value='Log out'>";
echo "</form>";
echo "</h1>";
echo "</div>";
if(isset($_POST['logout']) && ($_POST['logout'] == "Log out")) {
unset($_SESSION['name']);
}
}
Use session_unset() to destroy all registered variables in the session and if you want unset a specific variable like name use unset($_SESSION['name'])
Do NOT unset the whole $_SESSION with unset($_SESSION) as this will disable the registering of session variables through the $_SESSION superglobal.
You can try to add a call to session_commit() just after session_destroy();
The code below handles the Logout hyperlink, so it creates the global variable logout and it unsets the session
Log out
<?php
if(isset($_GET['logout'])) {
session_unset();
}
?>

global a $_SESSION variable

I'm trying to make a login session on PHP, but it appears that the $_SESSION['username'] dies inside the IF sentence (I thought $_SESSION where globals by default), and I cant echo it out of the IF
heres My code
if($name=="admin" && $password=="admin")
{
session_start();
$_SESSION['username'],$_SESSION['sesion'];
$_SESSION['username']=$name;
$_SESSION['sesion']=1;
echo $_SESSION['username'];
echo "<br>";
echo $_SESSION['sesion'];
}
echo "<br>";
echo $_SESSION['username'];
The last echo doesnt print its VALUE, So when I redirect it to another page, the page doesnt take the username value
I'm kind of new in this matter
So dont be so harsh on me :P
How can I do this??
Move session_start() to the top of the file:
// foo.php
<?php
session_start();
//....
if($name=="admin" && $password=="admin")
{
// $_SESSION['username'],$_SESSION['sesion']; // Remove this line
$_SESSION['username']=$name;
$_SESSION['sesion']=1;
echo $_SESSION['username'];
echo "<br>";
echo $_SESSION['sesion'];
}
echo "<br>";
echo $_SESSION['username'];
When You are using sessions in php You must start it with session_start() in every file/page You want to get or set session values, so just add this line to this file and that file You're redirecting to.
session_start() should be above the if statment. best to put it right below the ?php

how to make session update the value in php?

I can't update my session value
this is the code
<CENTER>
<?PHP
session_start();
$_SESSION['value'] = 15;
if(isset($_POST['submit'])){
$plus = 10;
$_SESSION['value'] = ($_SESSION['value'] + $plus);
}
echo "<FORM METHOD=post ACTION=\"?page=try&". time(). "\" NAME=try>\n";
echo "<br>";
echo "Your value :" .$_SESSION['value'];
echo "<INPUT TYPE=submit NAME=submit VALUE=\"Submit\"></FORM>";
?>
</CENTER>
the problem is everytime I click that button, it always give me the same result.
that $_SESSION['value'] is always 15 and it never changes
so how to update the session value ? so I will get $_SESSION['value'] become 35 (the past result is 25 ) when I click the button again
thanks
you explicitly set the session value to 15, and then add 10 to it. It should never reach 35. try removing the assignment to 15 (or better yet, adding an if(!isset($_SESSION['value'])) check before it) and then try again
You should also take John Conde's advice and make sure that you start the PHP session before sending any output. Please read the manual
session_start() has to be before any output is sent to the browser (when using cookie based sessions).
<?php session_start(); ?>
<CENTER>
<?php
$_SESSION['value'] = 15;
if (isset($_POST['submit'])) {
$plus = 10;
$_SESSION['value'] = ($_SESSION['value'] + $plus);
}
echo $_SESSION['value'];
echo '<form method="post" action="try1.php" name="try">' . "\n";
echo '<br>';
echo 'Your value :' . $_SESSION['value'];
echo '<input type="submit" name="submit" value="submit"></form>';
?>
</CENTER>

Categories