How to check if two PHP sessions is set or not - php

I need to check if this $_SESSION['1'] || $_SESSION['2'] isset or not
I tried this
ob_start();
session_start();
if (!isset($_SESSION['log']) && $_SESSION['log'] !== 1) {
if (!isset($_SESSION['insAdmin']) && $_SESSION['insAdmin'] !== 1) {
header("Location:sessionManager/login.php");
}
}
but if $_SESSION['insAdmin'] isset
I get a notes
( ! ) Notice: Undefined index: log in
C:\wamp\www\mysite\en\admin\headers.php on line 13

You're contradicting yourself:
!isset($_SESSION['log']) & $_SESSION['log'] !== 1
You're basically saying if $_SESSION['log'] is not set and $_SESSION['log'] is not 1 which doesn't make sense.
If $_SESSION['log'] is not set then trying to access it's value through $_SESSION['log'] (with the 2nd expression after &&) will result in an undefined index of course.
You should remove the !:
if (isset($_SESSION['log']) && $_SESSION['log'] !== 1) {
if (isset($_SESSION['insAdmin']) && $_SESSION['insAdmin'] !== 1) {
header("Location:sessionManager/login.php");
}
}

You normally use isset to test if a variable contains a value before checking it's actual value.
But you check if the variable is NOT set !isset($_SESSION['log'] and then check it's value which of course will always cause the notice if log is not set.

You're checking if it's not set, check if it's set instead.
if (isset($_SESSION['insAdmin']) && $_SESSION['insAdmin'] !== 1) {
header("Location:sessionManager/login.php");
}

Related

PHP empty() not working for me

I have a URL like: https://website.org/withdraw.php?valid_addr=1333mwKE7EcwLaR9ztdtEt7pPEfafpW4nn&amount=0.0002&_unique=1
and A line of code that reads:
if (empty($_GET['amount']) || empty($_GET['valid_addr']) || empty($_GET['_unique']))==0) exit();
If I remove the line then the code runs successfully. Can anyone tell me what I've done wrong.
The line is supposed to stop the code from running if any of the three fields are left empty.
Thanks.
I think you want to utilize array_key_exists rather than empty.
if (!array_key_exists('amount', $_GET) ||
!array_key_exists('valid_addr', $_GET) ||
!array_key_exists('_unique', $_GET))
exit();
From PHP empty() docs
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
See Array Key Exists docs
if (($_GET['amount'] == 0) OR ($_GET['valid_addr'] == 0) OR ($_GET['_unique'] == 0)) { exit(); }
Syntax Error. Remove the ==0) part:
if(empty($_GET['amount']) || empty($_GET['valid_addr']) || empty($_GET['_unique'])) {
exit();
}
Left parenthesis missing,
if ((empty($_GET['amount']) || empty($_GET['valid_addr']) || empty($_GET['_unique']))==0) exit();
Try it...
You're code should be something like this:
if (empty($_GET['amount']) || empty($_GET['valid_addr']) || empty($_GET['_unique']))
{
exit();
}
Above your code has syntax error. I think you want to validate unique with 0 and 1. So you should have to try this code
if (empty($_GET['amount']) || empty($_GET['valid_addr']) || $_GET['_unique'])==0) exit();

Undefined index while checking for COOKIE in PHP

I set a cookie on a visitor's PC to show a notice once every 24 hours. Recently I started getting the following error in my error log:
PHP: undefined index notice in **
I use the following code to check if the cookie exists with value and if not show notice:
if($_COOKIE['notice'] != 'yes')
echo 'notice';
}
I can use the following to avoid the PHP notice:
if((isset($_COOKIE['notice']) || !isset($_COOKIE['notice'])) && $_COOKIE['notice'] != 'yes')
Is there a way to do this check in one step only like I was doing or in a similar way?
Thanks
The index 'notice' in your source does not match the reported index 'test' in the error message. To avoid notices, you validate a variable or an index before reading it.
Here are two functions for the validation.
isset()
Is a positive check that the variable/index is set and not NULL
if (isset($_COOKIE['notice']) && $_COOKIE['notice'] === 'yes') {
// success
echo 'Cookie equals "yes".';
}
You can use && (and) for a second condition, that has to be TRUE, too.
empty()
Is a negative check that the index/variable does not exists or has a value that is considered empty (NULL, 0, '', array()).
if (empty($_COOKIE['notice']) || $_COOKIE['notice'] !== 'yes') {
// error
echo 'Cookie does not exists, is empty or does not equal "yes".';
}
You can use || (or) to combine that with additional conditions that need to be FALSE, too.
Or use the operator:
??
The operator assign a default value if the variable/index is not set or NULL:
$noticeCookie = (string)($_COOKIE['notice'] ?? 'no');
if ($noticeCookie === 'yes') {
// success
echo 'Cookie equals "yes".';
}
You always need to know if a variable is set before try to find what is inside, so yes.. you need to do the check. Also, your logic is wrong.. you are checking if notice is or isn't set (allways true) and checking if notice is "yes".
The code should be something like this:
if ( (!isset($_COOKIE['notice'])) || ( (isset($_COOKIE['notice'])) && ($_COOKIE['notice'] != 'yes') ) ) {
//Show the notice
}

PHP if status and !isset or !isset

I'm trying to match a condition where if the user status is 10 and ANY POST variables are not set it triggers an error:
if ($_SESSION['status']=='10' && !isset($_POST['a']) || !isset($_POST['B'])) {}
I can not use && conditions for any !isset as one variable may be set though another might not. I only want the condition to match if one or more variables are not set AND the status==10.
When testing if a $_POST variable !isset, I remove an input element from the page via a browser web tool (e.g. Firebug). When the form is submitted with the variable missing it's still passing validation incorrectly.
I am also seeking a PHP if grouping condition.
If you are looking for absolutely any PHP variables, I'd recommend this:
if (($_SESSION['status'] == 10) && (count($_POST) > 0)) {
You can then get the list of _POST var keys using array_keys($_POST).
If you are looking for a specific:
if (($_SESSION['status'] == 10) && (isset($_POST['A']) || isset($_POST['b']))) {
The order of the brackets is important. You can separate groups of logical statements with brackets.
Is that was what you were looking for?
$status = $_SESSION['status'];
if($status == '10'){
if(!isset($_POST['a']) or !isset($_POST['B'])){
//Triggers error.
}else{
//Another
}
}
Try making it a function:
function checkAllVars($dataVars, $requestVars) {
foreach($dataVars as $varname) {
if(!isset($requestVars[$varname])) {
return false;
}
}
return true;
}
$dataVars = array (
"varName1",
"varName2",
"varName3",
"varName4",
);
$allVarsSet = checkAllVars($dataVars, $_REQUEST);
you might be looking for
if($_SESSION['status']=='10' && (!isset($_POST['a']) || !isset($_POST['B']))){}
^ ^
which means if status = 10 and (if not set 'a' or not set 'B' or they can be both not set) do something
or you might be looking for
if(($_SESSION['status']=='10' && !isset($_POST['a'])) || ($_SESSION['status']=='10' && !isset($_POST['B']))){}

php: if($some_var != '') vs. isset / empty

So I am fairly new to php, but before I really had a solid understanding I picked up this habit. When checking for whether or not a $_SESSION / $_POST / $_GET variable was set I use this:
if($_SESSION['username'] != '' {
//allow access
header('Location: welcomefriend.php')
}
else {
//get out
header('Location: getoutofhereyournotwelcome.php')
}
I have used this in login scripts for checking if the session is set to allow access, etc. So now I know about isset / empty but I always seem to run into problems with those.
So my question is will I ever encounter a problem when using if($some_far != '') to check if a variable is set?
That would show notice if the variable doesnot exist, so do:
if( !empty($_SESSION["username"]) ) {
...
Yes - it'll throw a notice if the index doesn't exist in the array.
Yes, if a form is submitted, but not filled out, $_POST["value"]=="" will give you a different result from isset($_POST["value"]). Also, $_POST["value"]=="" will give you an error on some servers when it is not set.
Checking if $_SESSION['username'] is empty without checking whether there actually is a username entry in the $_SESSION array will throw notices. It's good practice to code around them. One way to do this is something like if (isset($_SESSION['username']) && $_SESSION['username'] != '')
As for empty() vs != "", that's personal preference. One problem you might run into is that empty() does not accept values, only references, so you cannot do empty(somefunction($_SESSION['username'])).
Use empty() if( !empty( $some_far ) ) { to check if a $_POST variable is set and not empty.
If the variable can also be empty but must be set use if( isset( $some_far ) ) {
With isset() the variable also must not be NULL to return true.
You also won't get a notice if the variable is not set as Martin already mentioned in his post.
I always do the following:
if (isset($_SESSION['username']) && $_SESSION['username'] != '') {
//allow access
header('Location: welcomefriend.php')
}
else {
//get out
header('Location: getoutofhereyournotwelcome.php')
}
Testing if the index 'username' exists in the $_SESSION variable first in the if statement will mean that if the index doesn't exist then we won't continue with $_SESSION['username'] != '' thus never causing an error.
Considering
An associative array containing session variables available to the current script
Why not use the predefined function available? array_key_exists
if(array_key_exists('username', $_SESSION) ) {
header('Location: welcomefriend.php');
} else {
header('Location: getoutofhereyournotwelcome.php');
}

Undefined offset And Array Comparison PHP

Hey everyone ive done my research and i find im still stuck many people said to put # sign before the variable but it does not seem to be working, so my code gives me this error
Notice: Undefined index: 2 in login.php on line 20
my code is
if( isset($_REQUEST['email']) || isset($_REQUEST['pwd']) || $_REQUEST['email'] != "" || $_REQUEST['pwd'] != "" )
{
$inputFile = fopen("members.txt", "r");
$found = false;
$i =0;
//read the read.txt until the end of file
while(!feof($inputFile) && $found == false)
{
$line = fgets($inputFile);
// replace the special charater within the lines by there proper entity code
$lineArray = preg_split("/\,/", (string)$line);
if ($_REQUEST['email'] === $lineArray['2'] && $_REQUEST['pwd'] === $lineArray['4'])
{
session_start();
$found = true;
$useremail=$_REQUEST['email'];
$password= $_REQUEST['pwd'];
//time to set sessions and stuff
$_SESSION['useremail'] = $useremail;
$_SESSION['password'] = $password;
//send the redirect header
header('Location: index.php');
exit();
}
}
fclose($inputFile);
}
so the line its referring to is
if ($_REQUEST['email'] === $lineArray['2'] && $_REQUEST['pwd'] === $lineArray['4'])
ive tried many other variation such as removing single quotes adding # in front of the $lineArray and doing both, can anyone help me out the values are there when i was printing them out but when it get to this if statement it doesn't turn to equal and it give me this error.
if also tried
if ($_REQUEST['email'] === $lineArray[2] && $_REQUEST['pwd'] === $lineArray[4])
and
if ($_REQUEST['email'] === #$lineArray[2] && $_REQUEST['pwd'] === #$lineArray[4])
You need $lineArray[2]. Indices of an array are integers, not strings. And also ensure if that same array has atleast 3 elements.
The line is the problem:
$lineArray = preg_split("/\,/", (string)$line);
It should be (since you seem to be splitting on ,):
$lineArray = preg_split("/,/", (string)$line);
PS: Consider using a simpler $array = explode(",",$yourString)
The error means there is a undefined var being used in your code. In your case, it's talking about $lineArray['2']. This isn't a serious error, so you can be lazy and alter your error settings to get rid of it:
error_reporting(E_ERROR | E_WARNING | E_PARSE);
But you really should just fix it instead.
As Devnate suggested, you need to use a int to specify the index key of the array, instead of a string (so this $lineArray[2] instead of this $lineArray['2']). Why? Because the key you was using before ('2') was never set, which resulted in the error.
You say the comparing fails when you attempt the above. I cannot help you with that until I see the result of print_r($lineArray);.
This is the code from your previous question. It's a shame you didn't take my advice and go with my code. You wouldn't be having this issue if you did. But that's a different matter. Post the print_r($lineArray); so I can see what the problem is with the comparing.
You'll want to use numbers (no quotes) for your array keys, but you'll also need to check that those array values exist with isset() before comparing them.
if (isset($lineArray[2]) && $_REQUEST['email'] === $lineArray[2] ...

Categories