Undefine index: session error - php

Whenever someone login $_SESSION['semail']; and $_SESSION['username2'] are set. Whenever I go to profile page then I set session into a variable like $email = $_SESSION['semail'];
Then in error log an error is recorded as:
Undefined index: semail in /home/twekr/public_html/profile.php on line 11
My session start like this at top of page:
session_name('twekr');
session_start();
ob_start();
Here is the small part of script which is creating error:
<?php
session_name('twekr');
session_start();
ob_start();
if(!isset($_SESSION['semail']))
{
header("Location:https://www.twekr.com/");
}
if(isset($_GET['user']))
{
$id = $_GET['user'];
$user = $_SESSION['semail'];
$userid1 = $_SESSION['username2'];
include_once('config/db.php');
include_once('frnds/functions.php');
require('config/dbsettings.php');
$userquery= "SELECT * FROM users WHERE email='$user'";
$userquery=$sp->query($userquery) or die($sp->error);
$info=$userquery->fetch_object();
$userr = $info->username;
This is the small part of login script where I set session:
$_SESSION['username2'] = $get['username'];
$_SESSION['semail'] = $uemail;
$get is performed here below:
$check_login = mysqli_query($con, "SELECT username FROM users WHERE
email ='$uemail' AND password ='$upass'");
if(mysqli_num_rows($check_login) ==1) {
$get = mysqli_fetch_array($check_login);
$_SESSION['username2'] = $get['username'];

Related

Notice: Undefined index: SESS_NAME in student_vote.php on line 9

<?php
include "connection.php";
if(!isset($_SESSION))
{
session_start();
}
$cand1 = $_POST['cand1'];
$cand2 = $_POST['vice1'];
$sess = $_SESSION['SESS_NAME'];
if(!$cand1){
$error="<center><h4><font color='#FF0000'>Please fill empty fields</h4></center></font>";
include"student.php";
exit();
}
$cand1 = addslashes($cand1);
$cand1 = mysqli_real_escape_string($con,$cand1);
$sql = 'SELECT * FROM student WHERE username="'.$_SESSION['SESS_NAME'].'" AND status="VOTED"';
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result)==1){
$msg="<center><h4><font color='#FF0000'>You have already been voted, No need to vote again</h4></center></font>";
include 'student.php';
exit();
}
else{
$sql = 'UPDATE candidate SET votecount = votecount + 1 WHERE cand_id = "'.$_POST['cand1'].'" OR cand_id = "'.$_POST['vice1'].'"';
$sql2 = 'UPDATE student SET status="VOTED" WHERE username="'.$_SESSION['SESS_NAME'].'"';
$result = mysqli_query($con,$sql);
$result2 = mysqli_query($con,$sql2);
if(!$result && !$result2){
die("Error on mysql query".mysqli_error());
}
else{
$msg="<center><h4><font color='#FF0000'>Congratulation, you have made your vote.</h4></center></font>";
include 'student.php';
exit();
}
}
?>
the errors are at code including
$sess= $_SESSION['SESS_NAME']; and at username="'.$_SESSION['SESS_NAME'].'"
i have tried every possibility so can you check my code?
mainly the error is undefined index at $session[session_name]?
Are you sure the session 'SESS_NAME' is getting set? In the code above you are only trying to access its value. Undefined index is the error thrown when there is no session with that name.
Looks like to me you haven't declared the variable $_SESSION['SESS_NAME']. Try doing the following
var_dump($_SESSION);
This will show you all the defined variables in the session, if SESS_NAME isn't there then it hasn't been defined. Maybe you have failed to define it somewhere else?

Unable to get session variable to save into my database

Can anyone help me in getting the group_id from a session and save into the database, it seems not to working, been working on it for a while now. The error i am getting is Notice: Undefined index: group_name
This is my script
include('db.php')
//Get User Info
if(isset($_SESSION['username'])){
$LoggedUser = $_SESSION['username'];
if($GetUser = $mysqli->query("SELECT * FROM users WHERE username='$LoggedUser'")){
$UserInfo = mysqli_fetch_array($GetUser);
$LoggedUsername = strtolower($UserInfo['username']);
$LoggedUserLink = preg_replace("![^a-z0-9]+!i", "-", $LoggedUsername);
$LoggedUserLink = strtolower($LoggedUserLink);
$UserId = $UserInfo['user_id'];
$GetUser->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
}
//Get Group info
if(isset($_SESSION['group_name'])){
$LoggedGroup = $_SESSION['group_name'];
if($GetGroup = $mysqli->query("SELECT * FROM groups WHERE group_name='$LoggedGroup'")){
$GroupInfo = mysqli_fetch_array($GetGroup);
$LoggedGroupname = strtolower($GroupInfo['group_name']);
$LoggedGroupLink = preg_replace("![^a-z0-9]+!i", "-", $LoggedGroupname);
$LoggedGroupLink = strtolower($LoggedGroupLink);
$GroupId = $GroupInfo['group_id'];
$GetGroup->close();
}else{
printf("Error: %s\n", $mysqli->error);
}
}
//getting variables and inserting into a database
if($_POST)
{
$User = $UserId;
$Group = $GroupId;
$mysqli->query("INSERT INTO tb_name(group_id_fk, user_id_fk) VALUES ('$Group', '$User')");
die('<div class="alert alert-success" role="alert">You have been added successfully to the group.</div>');
}else{
die (mysqli_error());
}
?>
Thanks
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
<?php
// Start the session
session_start();
// Set session variables
if(isset($_SESSION['username'])) {
---- Your Statements -----
}
?>
you need to start a session first by session_start(); before using $_SESSION global

update table when finish session login in php [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
This is the other code statement in php, the opposite of my other question, it's about time to finish updating the log after finishing the session login
<?php
include ('connect.php');/*to connect to database with oracle 11g*/
session_start();
$_SESSION = array();
$email = $_SESSION["EMAIL_USER"];
$passw = $_SESSION["PASS_USER"];
$query = "UPDATE LOGIN SET OUT_TIME_LOGIN = LOCALTIMESTAMP WHERE EMAIL_USER = '$email' AND PASS_USER = '$passw';";
$sid = oci_parse($conn, $query);
$result = oci_execute($sid);
$dbarray = oci_fetch_array($sid);
unset ($_SESSION);
if(ini_get("session.use_cookies")){
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 50000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]);
}
session_destroy();
session_commit();
/**/
header("location: ../menu.html");
?>
when I finish the logon session, was supposed to update the table with the login time to exit to exemples: LOCALTIMESTAMP where email_user = '$email';
and when I try log out, I received error
Undefined index: EMAIL_USER AND PASS_USER
and in my other question, PHP - Parse error: syntax error, unexpected end of file, I re-edited the codes
and I made this
$query = "SELECT * FROM login WHERE user_email = '$email' AND user_pass= '$passw'";
$sid = oci_parse($conn, $query);
$result = oci_execute($sid);
$dbarray = oci_fetch_array($sid);
if (($dbarray["user_email"] == $email) && ($dbarray["user_pass"] == $passw)) {
session_start();
$_SESSION["user_email"] = $email;
$_SESSION["user_pass"] = $passw;
switch ($dbarray["type_user_id"]) {
case 1:
header("Location: admin.php");
break;
default:
echo "<script> alert('ERROR:'); history.back() </script>";
exit;
break;
}
}
and now I intend to do the opposite to get the email and password of the online session
any suggestion?
By looking at both of the codes, I see following errors
In First code $_SESSION variables are
$email = $_SESSION["EMAIL_USER"];
$passw = $_SESSION["PASS_USER"];
But in 2nd code when you are fetching data from database and loading variables to Session
$_SESSION["user_email"] = $email;
$_SESSION["user_pass"] = $passw;
So change these
$email = $_SESSION["EMAIL_USER"];
$passw = $_SESSION["PASS_USER"];
To this
$email = $_SESSION["user_email"];
$passw = $_SESSION["user_pass"];
This will resolve your following error
Undefined index: EMAIL_USER AND PASS_USER
and in your first code you don't need $_SESSION = array();
In your 2nd code you are fetching data with following query
$query = "SELECT * FROM login WHERE user_email = '$email' AND user_pass= '$passw'";
and in your first code you are updating data with following query
$query = "UPDATE LOGIN SET OUT_TIME_LOGIN = LOCALTIMESTAMP WHERE EMAIL_USER = '$email' AND PASS_USER = '$passw';";
change you update query because you are referring to right table but wrong table and col names
$query = "UPDATE login SET OUT_TIME_LOGIN = LOCALTIMESTAMP WHERE user_email = '$email' AND user_pass = '$passw';";
//you need to check `OUT_TIME_LOGIN` col name in your database too i m sure its wrong too
Also you have to change this
LOCALTIMESTAMP
To this, first define $datetime
$datetime = date('Y-m-d H:i:s');
so final update query will be like
$query = "UPDATE login SET out_time_login = '$datetime' WHERE user_email = '$email' AND user_pass = '$passw';";
and you asked "get the email and password of the online session"
In your PHP code you can
echo $_SESSION["user_email"];
echo $_SESSION["user_pass"];
Or in HTML
<input type="text" name="email" value="<?php echo $_SESSION["user_email"];?>">
<input type="text" name="pass" value="<?php echo $_SESSION["user_pass"];?>">

Undefined property: stdClass

I'm getting the following error on these lines
Notice: Undefined property: stdClass::$id on line 36
Notice: Undefined property: stdClass::$id on line 40
Notice: Undefined property: stdClass::$screen_name on line 40
Line 36:
$vOAuth1 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // searching for user in database
Line 40:
mysql_query("INSERT INTO `atwitter_oauth_users` (`oauth_provider`, `oauth_uid`, `username`, `oauth_token`, `oauth_secret`) VALUES ('twitter', {$oUserInfo->id}, '{$oUserInfo->screen_name}', '{$aAccessToken['oauth_token']}', '{$aAccessToken['oauth_token_secret']}')");
This is the whole code:
<?php
ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);
require_once('inc/header.php');
require_once('inc/twitteroauth.php');
global $sConsumerKey, $sConsumerSecret;
session_start();
if (! empty($_GET['oauth_verifier']) && ! empty($_SESSION['oauth_token']) && ! empty($_SESSION['oauth_token_secret'])) {
} else { // some params missed, back to login page
header('Location: http://www.domain.com/livetweeter/tw_login.php');
echo "parameters missed";
}
$oTwitterOauth = new TwitterOAuth($sConsumerKey, $sConsumerSecret, $_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$aAccessToken = $oTwitterOauth->getAccessToken($_GET['oauth_verifier']); // get access tokens
$_SESSION['access_token'] = $aAccessToken; // saving access token to sessions
$oUserInfo = $oTwitterOauth->get('account/verify_credentials'); // get account details
if(isset($oUserInfo->error)){
header('Location: http://www.domain.com/livetweeter/tw_login.php'); // in case of any errors - back to login page
echo "error";
} else {
global $sDbName, $sDbUserName, $sDbUserPass;
$vLink = mysql_connect($sDbHost, $sDbUserName, $sDbUserPass);
mysql_select_db($sDbName);
$vOAuth1 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // searching for user in database
$aOauthUserInfo = mysql_fetch_array($vOAuth1);
if (empty($aOauthUserInfo)) { // if user info not present - add them into database
mysql_query("INSERT INTO `atwitter_oauth_users` (`oauth_provider`, `oauth_uid`, `username`, `oauth_token`, `oauth_secret`) VALUES ('twitter', {$oUserInfo->id}, '{$oUserInfo->screen_name}', '{$aAccessToken['oauth_token']}', '{$aAccessToken['oauth_token_secret']}')");
$vOAuth2 = mysql_query("SELECT * FROM `atwitter_oauth_users` WHERE `id` = '" . mysql_insert_id() . "'");
$aOauthUserInfo = mysql_fetch_array($vOAuth2);
} else {
mysql_query("UPDATE `atwitter_oauth_users` SET `oauth_token` = '{$aAccessToken['oauth_token']}', `oauth_secret` = '{$aAccessToken['oauth_token_secret']}' WHERE `oauth_provider` = 'twitter' AND `oauth_uid` = '{$oUserInfo->id}'"); // update tokens
}
$_SESSION['oauth_id'] = $aOauthUserInfo['id'];
$_SESSION['oauth_username'] = $aOauthUserInfo['username'];
$_SESSION['oauth_uid'] = $aOauthUserInfo['oauth_uid'];
$_SESSION['oauth_provider'] = $aOauthUserInfo['oauth_provider'];
$_SESSION['oauth_token'] = $aOauthUserInfo['oauth_token'];
$_SESSION['oauth_secret'] = $aOauthUserInfo['oauth_secret'];
mysql_close($vLink);
header('Location: http://www.domain.com/livetweeter/index.php');
echo "we've got an error";
}
if(!empty($_SESSION['oauth_username'])){
header('Location: http://www.domain.com/livetweeter/index.php'); // already logged, back to our main page
echo "this is an error";
}
?>
Note: I know I shouldn't be using mysql_query - I'll sort that once I have to script working.

How to save table data in session

I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */

Categories