PHP content of session variable - php

I'm trying to pass a value between 2 pages through a $_SESSION variable then empty it as follows:
I'm assigning the session variable with a value on one PHP page:
$_SESSION["elementName"]="a_373";
And trying to store it in a variable on another page as follows:
if (!empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
The value of $elemName is always empty when I print it out. However, I get the correct printout when I remove the $_SESSION["elementName"]=""; line from the above code.
Edit: I'm printing $elemName and not $_SESSION["elementName"] - print($elemName);
I'm on a shared hosting account with PHP 5.3.2 and register_globals set to off (as per phpinfo();).
I need to reset/empty the session variable once I get the value it has, but it's not working and this has been baffling me for the last couple of days. Any ideas why? Thanks!
EDIT:
Additional clues: I tested with the session's var_dump before the if statement and set another value for $elemName in the else section as follows:
var_dump($_SESSION["elementName"]);
$elemName="x";
if (isset($_SESSION["elementName"]) && !empty($_SESSION["elementName"])) {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="None";
}
print("<br />".$elemName);
I got this result:
string(5) "a_373"
None

Try using isset($_SESSION["elementName"]) and unset($_SESSION["elementName"]) instead.

Check the Below code and test it
if (isset($_SESSION["elementName"]) && $_SESSION["elementName"]!="") {
$elemName=$_SESSION["elementName"];
$_SESSION["elementName"]="";
} else {
$elemName="";
}
Empty only check value is empty or not, But by isset we can check varaible exit and does not content empty value

Are you printing out $elemName? If yes than there shouldn't be any blank output unless and until your else condition returns true, but if you are printing $_SESSION["elementName"] than you'll get no output as you are making it blank
$_SESSION["elementName"]="";
Correct way to remove a session var completely is to use unset($_SESSION["elementName"])
Though if you want to make it empty, == '' is enough
Also be cautious while using unset() because after you unset the session and later use that index to print, it will show you undefined index error.
Update(As #nvanesch Commented)
I guess your else condition is getting satisfied, because you are
using $elemName=""; in your else, thus you are not returned with any
output
Also if (!empty($_SESSION["elementName"])) { will return false if you are not using session_start() at the very top of your page

I once created this class in order to be able to have this ability, and it works wonderfully:
<?php
class Flash {
public function set($key, $message) {
$_SESSION["flash_$key"] = $message;
}
public function get($key) {
$message = $_SESSION["flash_$key"];
unset($_SESSION["flash_$key"]);
return $message;
}
public function has($key) {
return isset($_SESSION["flash_$key"]);
}
}
It's pretty similar to what you're trying to do, so I'm not sure why it's not working for you, but you may want to give it a try. You obviously need to have the session already started.

Related

Correct Way to determine if function is set

i cant seem to find a solution to my issue. im trying to check if the value of a function has been set and if it has do some stuff however when i run the below codes the bottom one throws a error the code at the bottom is the code i wish to use
seems pointless calling the function into a variable just to see if its set
//working check if set
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset))
{
echo"do some stuff";
}
//NOT working check if set
if(isset( WA_FN_Validate_Post($_POST['wa_passwordreset']) ))
{
echo"do some other stuff";
}
As per PHP manual:
isset — Determine if a variable is set and is not NULL
isset actually test if a variable is set, not if a function returns any value. That is why your code doesn't work.
im trying to check if the value of a function has been set
Functions do not have values. Functions may return values. You can't check if a function has a value and if it's set.
Moreover,
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset))
{
echo "do some stuff";
}
this portion of code will always return true. The reason for that is that even if WA_FN_Validate_Post would return an empty string, the variable $wa_passwordreset will be considered set and isset check will always return true. To avoid this, you should either check your $_POST like this:
if(isset($_POST['wa_passwordreset']))
{
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
echo "do some stuff";
}
Or if it's vital for you to maintain the order and check after WA_FN_Validate_Post, use empty:
$wa_passwordreset = WA_FN_Validate_Post($_POST['wa_passwordreset']);
if(isset($wa_passwordreset) && !empty($wa_passwordreset)) // be extra paranoid!
{
echo "do some stuff";
}

Why this if else condition is not not working properly

$taskid=$this->privacy();
if($taskid){I returning something in one function and then by reference to this return,I am fetching data from another table in second function using if condition in such a way that if data(return) found in first table then execute else leave empty
But I data found in first table then every thing is fine,hower data not found in first table then it shows as Notice: Undefined variable: task in....
I think error is in if else condition.Please help or suggest any alternative approach.
Plz also note that that I am working on pricacy table
first function returning rows
function privacy()
{
$session=new session();
$sql2=mysqli_query($this->db->connection,"SELECT * from privacy where viewerid='$session->userid'");
while($row2=mysqli_fetch_array($sql2)){
$task[]=$row2['task'];
}
return $task;
}
function 2.. if found something then do something else do nothing(but error appears as undefined variable)
function showactivityo4apply()
{
$session=new session();
$taskid=$this->privacy();
if($taskid){
foreach($taskid as $fvid){
$sql=mysqli_query($this->db->connection,"SELECT * FROM activity where id='$fvid'");
while($row=mysqli_fetch_array($sql)){
$name_id=$row['sub_id'];
echo $name;
}
}
}
else{}
}
if($taskid=$this->privacy()) is assigning a value of $this->privacy() to $taskid
I think you mean
if($taskid == $this->privacy())
If condition have == sign not = sign
if($taskid==$this->privacy()){
}
else
{
}
= means assign value to another
== check the value to other variable
it is showing notice because php is not getting value in array on key "task" use isset() function to check whether data is available or not
use like this
$task[] = (isset($row2['task'])?$row2['task']:'';
if value is not set in $row2['task'] then it will assign blank value in $task[] array.
and one more change you have to do
instead of if($taskid) condition use
if( count($taskid) > 0){
}
so that if record not found in array it will not inter in to the loop
please change this line of your code like:
$sql2=mysqli_query($this->db->connection,"SELECT * from privacy where
viewerid='$session->userid'");
=========================================
to
=============================
$sql2=mysqli_query($this->db->connection,"SELECT * from privacy where
viewerid='" . $session->userid . "'");
=======================
conclution: Here $session->userid is not found thats why you not get result.

What is the best way to know is $_GET['example']=="somevalue"?

if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }

Invalid argument foreach()

I have the follow code, but, i get an error in my code.
I cant find the problem but, I think it comes from:
UserManagement::findByUsername($username);
$a_allSections = UserManagement::findByUsername($username);
if($a_allSections)
{
foreach($a_allSections as $a_section)
{
echo $a_section['name'];?>
}
}
else
{
echo 'There's nothing found.' . "\n";
}
Evidently $a_allSections is not an array, so foreach complains. Use var_dump($a_allSections) to find out what exactly it is, and fix your code accordingly.
Check this way
UserManagement::findByUsername($username);
1.the function findByUsername($username) should return some values
2.the class should be included in current document.
3.Check whether your return result as array. if array means check is_array();
4.if above 3 ok in your question then you will not get the error.
$a_allSections may be empty
change condition to
if(is_array($a_allSections)){
...
}
to prevent such error on empty arrays

Help with an if and else statement logic

The code below is just a sample of the format I have
isset($_GET['ids'])?$ids=$_GET['ids']:null;
isset($_POST['idc'])?$idc=$_POST['idc']:null;
function ShowCart()
{
$que = "SELECT
FROM
cart
LEFT OUTER JOIN ...
ON ...
LEFT OUTER JOIN... ON...
WHERE ";
$result = mysql_query($que);
while(){
if (isset($ids)) {
display something
for (){
if(){
} // end of if inside the for loop
}// end of for loop
}
elseif($idc && $ids=null) {
display something different
}
else{
display nothing has passed
}
}//end of while loop
}//end of showcart(); function
that's the formatting above I wonder why the if and elseif are not getting the isset() as the if and elseif argument.
I have debug the through the whole code and the print_r of GET and POST has values through the whole code.
print_r($_POST);
print_r($_GET);
Jona, if you'd ever bother to properly format your code, you'd see that the 'else' in question is WITHIN A FUNCTION, and you're defining $ids and $idc OUTSIDE THE FUNCTION. Remember, in PHP, global variables (except the super-globals, such as $_GET, $_POST, etc...) are not visible within functions unless you explicity define them as globals within the function.
Add global $idc, $idc; as the first line in the function definition and your if() will start working correctly.
Followup:
Your code is still hideously formatted, and very wonky. Take this:
isset($_GET['ids'])?$ids=$_GET['ids']:null;
You're using a trinary operator, but not assigning its results anywhere, and using the 'true' condition to do an assignment. This is an ugly hack. It should be written like this:
$ids = isset($_GET['ids']) ? $_GET['ids'] : null;
This way $ids will be set to null if there is no $_GET['ids']. Which brings up the fact that you're assigning a null instead of some other default value. If there really was no $_GET['ids'], then this:
$idx = $_GET['ids'];
would work identically, as PHP will automatically assign a null in situations where the right-hand-side doesn't exist. Of course, you still have to sanitize this value, since you're using it in an SQL query later on. Leaving it like this will just invite SQL injection attacks and all kinds of other abuses.
Beyond that, you're still creating $ids and $idc OUTSIDE of your ShowCart() function. As such, $ids and $idc within the function will be automatically be created with null values, since you've not declared them to be global. I think by now it's obvious you have no idea what this means, so try out this piece of code:
<?php
$var = 'Here I am!';
function showVar() {
echo "Within showVar(), var is set to: $var\n";
}
function workingShowVar() {
global $var;
echo "Within workingShowVar(), var is equal to: $var\n";
}
showVar();
workingShowVar();
If you copy/paste this code, run it, you'll see the following output:
Within showVar(), var is set to:
Within workingShowVar(), var is set to: Here I am!
Notice that both functions are identical, except for the global declaration. If you can figure out the difference, then you'll realize you need to re-write your ShowCart() function as follows:
function ShowCart() {
global $ids, $idc;
// rest of your code here
}
Well the code you've posted is sound, so it's probably a problem with the variables getting to that script in the first place. Are you sure those variables are defined in the GET string?
Dump out the contents of it to make sure:
print_r($_GET);
Try this:
$ids= isset($_GET['ids'])?intval($_GET['ids']):null;
$idc= isset($_GET['idc'])?intval($_GET['idc']):null;
if (isset($ids)) {
//display something
}
elseif(isset($idc)) {
//display something different
}
else
{
//display nothing has passed
}
I tested your script above,it works as expected.Maybe you should check whether the link is correct or not.

Categories