Using $_SESSION variables on a function - php

I have a function on my page to login it works like this:
function entrarSistema($email,$senha){
if(isset($email) and (autentica($email,$senha)!=false)){
$mysqli = connect_db();
$result = mysqli_query($mysqli,"SELECT ID FROM px_user WHERE email = '$email'");
$id = mysqli_fetch_array($result);
$_SESSION['nome'] = autentica($email,$senha);
$_SESSION['email'] = $email;
$_SESSION['password'] = $senha;
$_SESSION['ID'] = $id[0];
$_SESSION['logado'] = true;
}
else{
if(check_double($email)==1){
setCodeAlerta(1);
echo $_SESSION['status'];
}
else {
setCodeAlerta(2);
}
}
}
This function works fine, and the Session variables are set when i call the function setCodeAlerta(), the Session variable i've declared wont work. Notice that this 2 functions are on the SAME file Here is the function:
function setCodeAlerta($numeroCodigo){
$_SESSION['status'] = $numeroCodigo;
}
My index.php has all the pages included, and i use url_rewrite to add the piece of codes that i need, and has this on its very top:
if( !isset($_SESSION) ){ session_start(); }
Oddly enough, if i call directly a file named test.php with this code:
<?php
setCodeAlerta(2);
?>
The variable is set fine, and everything works well.
Thanks in advance.

I'd add a comment, but my rep isn't high enough yet. Out of curiosity are the other session vars available at that point that you are setting? -- I ask because I'm running your code (stripped down) and it's returning OK. I'm just thinking there's something more to this than just that. Are you calling session_start() twice anywhere in an include or anything?

I got that. Everything was absolutely fine with my code, i just did a conditional, where my code would never really go to wrong username/password, hence, not accessing my function (wich is working fine). After removing the second part (after the and) part of this conditional, my code worked just fine.
if (isset($_POST['submitLogin']) and autentica($_POST['emailLogin'],$_POST['passwordLogin']){
entrarSistema($_POST['emailLogin'],$_POST['passwordLogin']);
}
I normally ask questions and find my answer minutes after that, i think thats a bad habit of mine. Even so, i spent the last 5 hours debugging it.
Thanks!

Related

PHP Session Variable get lost and session id is changing on every request

i found many answers about that problem but nothing solved my problem - so i want to show you my code and hope that someone can find the mistake..
I have a standard HTML formular that gives some data with POST to the next .php file where i get it and save it into session-variables. I use the session variables about 2 reasons:
if someone reloads the page, it should show the same information as before.
I need the variables in upcoming php files.
Here is the code:
session_start();
// Handle Variables on post and reloaded-page
if(isset($_POST["locId"]) && isset($_POST["dateId"]) )
{
$locId = htmlspecialchars($_POST["locId"]);
$dateId = htmlspecialchars($_POST["dateId"]);
$_SESSION["locId"] = $locId;
$_SESSION["dateId"] = $dateId;
echo "Session variables are set: locId = " . $_SESSION["locId"] . " dateId = " . $_SESSION["dateId"];
} elseif(isset($_SESSION["locId"]) && isset($_SESSION["dateId"])) {
echo "get it from session";
$locId = $_SESSION["locId"];
$dateId = $_SESSIOn["dateId"];
} else {
$load_error = 1;
$status = "alert alert-danger";
$message = "shit, no variables here";
}
The frist call works fine - session variables are set and the echo gives the right values. After reloading the page i get the echo "get it from session" but my variables have no values.
i also checked my session_id() on first call and reload.. they are NOT the same.
I testet a simple test.php file where i start a session with a variable and ask for the variable in the next file. It works fine :-/
Its just a problem with my code above. I think my webserver is handling right. But what reasons are there for chaging a session id and losing session-variable values?
Damn! To write correct is everything ...
I found my mistake.
Look at the code in my question. The second session-variable is $_SESSIOn["dateId"].. the n is lowercase! If i write it correctly and complete in UPPERCASE it is working.
Also the session_id is not chaging anymore and i can output the session_id() as much as is want.. but one mistake in $_SESSIOn changes everything. New session_id on every call, ... strange.
Learned something again :-) Thanks to everybody for the answers and your time! I hope i can help you in the future
Well, your mistake is quite easy to find. In fact, your code works perfectly. But look at this part:
echo "get it from session";
$locId = $_SESSION["locId"];
$dateId = $_SESSIOn["dateId"];
Well, you asign the session values to two variables, but in fact, you simply missed to output them anywhere. Thats why you get "get it from session" but then is displays nothing, you need to echo them.
Simply add an echo and it will display your vars perfectly :)
echo "get it from session";
$locId = $_SESSION["locId"];
$dateId = $_SESSIOn["dateId"];
echo $locId;
echo $dateId;
Try this:
session_id();
session_start();

Session variable not set within functions

I'm trying to set a session variable to record when people have voted but PHP is flat out refusing to set it. The code is as follows:
elseif (isset($_GET['group']) && isset($_GET['vote']))
{
include_once(_INC.'otherheader.php');
groupVotePage($group, $vote);
$_SESSION[$group] = '1';
echo $_SESSION[$group];
}
Nothing. The function groupVotePage adds the vote to the database and echoes a thanks message. $group is the name of the group being voted for. I have session_start(); at the top of the page and have tried to declare the variable inside the function called as well, putting session_start(); everywhere. Session variables are used elsewhere on the site so I know it's not a server issue, and it's the same on all browsers I tried.
Declaring the session var inside the function works but only within the function - it doesn't go global.
if(!isset($_SESSION[$group])) {
$totalVote=$totalVote+$vote;
$totalNumVotes=$totalNumVotes+1;
$totalRating=round($totalVote/$totalNumVotes);
$totalScore=$totalVote*$totalNumVotes;
...db stuff...
$mysqli->query($query);
echo'Thanks for voting!';
}
else {
echo'You have already voted for this group!';
}
Maybe you can use PHP error reporting code to figure out where you going wrong
// Report all errors
error_reporting(E_ALL);
Okay fixed it, the < !DOCTYPE HTML> section was before the session_start();, when I put it after the code worked.

Error-message for failed register, login etc. - Use $GLOBAL oder $_SESSION?

For example:
If anyone fails at the login function (for example: enters wrong password) on my webpage, i want to show an error-message at the webpage. My idea was like that:
if(doLogin()) {
//....
}else {
$GLOBAL['errorLogin'] = "Wrong Userdata";
}
and then echo the global-variable in the .html.
But i searched also for this topic and found only this method, but everyone had used the $_SESSION variable for this instead of $GLOBAL.
Is my variant with the $GLOBAL varible wrong or bad practise?
And why use $_SESSION for a error-message, if i only echo the message one time and don't need it in the next request?
I think you mean $GLOBALS (notice the s) which is a suber global variable and therefore can be accessed from anywhere in the PHP script (also from within functions or methods).
There is nothing wrong about that.
I don't think that you should use the $_SESSION variable for that, because the user needs to see the error message only one time. In your case, and in most cases, that's why it might make no sense to store it in a session.
Personally, I just would use a custom errorMessage-Array, like that:
//store all Error Messages in one array.
$errorMessages = array();
if(doLogin()) {
//....
}else {
$errorMessages["Login"] = "Wrong Userdata";
}
//...
foreach($errorMessages as $key=>$message){
echo $key.": ".$message."<br>";
}

Getting value from session PHP

I am not sure why the variable username is not being returned in the session. When the user logs in, I start the session:
$username = trim($_POST['username']);
if(!isset($_SESSION)){ session_start(); }
$_SESSION[$this->GetLoginSessionVar()] = $username;
On the user's welcome page, when I run the echo command, I see the proper variable being returned. But I'm not sure why the return statement isn't working. I have the following in my PHP file:
function UserName()
{
return isset($_SESSION['name_of_user']) ? $_SESSION['name_of_user'] : "Unknown User" ;
//echo $_SESSION['name_of_user'];
}
In my html, I have:
Welcome back <?PHP $fgmembersite->UserName(); ?>!
I also checked the session ID, and it's also being generated properly.
Can you please help me understand what I'm doing wrong?
Is fgmembersite an object and have it the function called UserName ?
If yes, you simply miss an echo
<?PHP echo $fgmembersite->UserName(); ?>
You must add echo or print so should look like this;
<?PHP echo $fgmembersite->UserName(); ?>
You need to print out your variable. Use
Echo or print
Possibly you should add output:
<?php print $fgmembersite->UserName(); ?>
If you are using the script I think you are using, you need to look through fg_membersite.php at the line that says:
function CheckLoginInDB($username,$password)
whithin that line you should have a MySQL statement:
$qry = "SELECT etc...
When I tried to add UserAvatar I was able to do that by adding it to that MySQL string.
On a side note, I too am having trouble with adding UserName, and for the life of me I can't figure out why it would work any different than my previous workaround, yet somehow it is, but I am still convinced something in that file will do the trick eventually.
Edited:
Ok i got it, just do this:
echo $fgmembersite->UserName($username);
The username will pop right out. I have no idea why, i don't know enough php to explain it, but i can only assume this will get you going.

PHP $_SESSION variables not storing values

I'm trying to use PHP session variables to carry data over multiple pages. I am using session variables on many parts of my site, but this is the first place where they don't work.
I'm setting it like this:
$_SESSION["savedRetailerName"] = $foo;
And calling it like this:
echo $_SESSION["savedRetailerName"];
The session id remains the same between these two pages, and I'm sure that I'm setting the variables right and that they are being called right. I start the session correctly, and even on that particular page, other session variables are being shown properly.
How can I begin to debug this odd behavior?
Edit:
There are two different pages I'm currently dealing with. Page 2 sets the session variables, and there is a button that will return the user to Page 1. The idea is to still have the fields in Page 1 filled in if the user wishes to return to Page 1.
It is not a cache problem, and I can return other session variables in the exact same spot in my code as where I am failing to return these variables.
The only other code that may be pertinent is the back button handler (jQuery):
$('#backButton').live('click',function() {
window.location.replace("page 1");
});
Edit 2:
I believe this isn't working because of something with variables here:
<?php
$retailerName = $_REQUEST["retailerName"];
$description = $_REQUEST["description"];
$savingsDetails = $_REQUEST["savingsDetails"];
$terms = $_REQUEST["terms"];
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$zone = $_REQUEST["zone"];
$dateExp = $_REQUEST["dateExp"];
$tag = $_REQUEST["tag"];
$_SESSION["rn"] = $retailerName;
$_SESSION["de"] = $description;
$_SESSION["sd"] = $savingsDetails;
$_SESSION["tm"] = $terms;
$_SESSION["ph"] = $phone;
$_SESSION["ad"] = $address;
$_SESSION["zo"] = $zone;
$_SESSION["ex"] = $dateExp;
$_SESSION["tg"] = $tag;
?>
I am able to set any session variable to a string, but it won't set to a variable.
You want to use session_start before you set or use any session variables. You only need to call it once.
If it's working in other places, odds are that this particular block of code is being executed before session_start is called.
remove all non printable characters before <?php
you may not see them..
You have spaces before your <php tag
You don't have session_start() anywhere
You are using the $_REQUEST variable which is sketchy (use $_GET or $_POST instead)
You would also need to register the session using
session_register # php.net

Categories