Undefined index in deleting $_SESSION - php

I have this code to delete any idea from a cart... I need to delete two$_SESSION.
1) $_SESSION["cart_array"]
2 $_SESSION["minicart"]
Without me adding $_SESSION["minicart"] it does delete the $_SESSION["cart_array"] but when i added it i got the minicart part i got an undefined index: minicart. So I
tried
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) && !isset($_SESSION["minicart"]) || count($_SESSION["minicart"]) < 1) {
the code above checks // If the cart session variable is not set or cart array is empty*
to the orginal if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
So
<?php
// if user wants to remove an item from cart
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
// Access the array and run code to remove that array index
$key_to_remove = $_POST['index_to_remove'];
if (count($_SESSION["cart_array"]["minicart"]) <= 1) {
unset($_SESSION["cart_array"]["minicart"]);
} else {
unset($_SESSION["cart_array"]["minicart"] ["$key_to_remove"]);
sort($_SESSION["cart_array"]["minicart"]);
}
}
?>
My quesion
Looking at the tried what I am i doing wrong in the if statement and also what am I doing wrong in the statement to delete the ($_SESSION["cart_array"]) AND ($_SESSION["minicart"])
If this is still unclear please leave a comment and I will do my best to explain it again.

Try changing
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
to
if (isset($_POST['index_to_remove']) && ($_POST['index_to_remove'])) {
or !empty instead of isset

if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"])
&& !isset($_SESSION["minicart"]) || count($_SESSION["minicart"]) < 1) {
You have a boolean logic problem here. This is not preventing $_SESSION['minicart'], or $_SESSION['cart_array'] for that matter, from being accessed if it is not set. That accessing when not set is what is giving you your error. Check your negations (!), and whether you really want || there.
I don't understand what all you need to check before unsetting those $_SESSION values, I don't have enough information and context. As such, I can't give you code to copy in paste into yours. All I can do is tell you why you're getting undefined index errors. Your if statement, which is supposed to keep $_SESSION['cart_array'] and $_SESSION['minicart'] from being accessed if they aren't set, is not doing what you intended. Trace through it and check your logic. If you can't make it work, then simplify it by breaking that into multiple, nested if statements.
If you want copy and pastable code, you will need to clarify what your doing a bit more. What are you checking with the count() parts, under what circumstances do you want to unset variables, and which variables do you want to unset.

Related

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] ...

!is_null() not working as expected

dispatch_address_postcode
isn't mandatory and it will still run even if it's blank:
if (!is_null($_POST['personal_info_first_name']) &&
!is_null($_POST['personal_info_surname']) &&
!is_null($_POST['personal_info_email']) &&
!is_null($_POST['personal_info_telephone']) &&
!is_null($_POST['dispatch_address_country']) &&
!is_null($_POST['dispatch_address_first_name']) &&
!is_null($_POST['dispatch_address_surname']) &&
!is_null($_POST['dispatch_address_address']) &&
!is_null($_POST['dispatch_address_town']) &&
!is_null($_POST['dispatch_address_postcode']) &&
!is_null($_POST['dispatch_address_county']) &&
( ($_POST['payment_method'] == "Pay by credit card.") ||
(
($_POST['payment_method'] == "Pay by new credit card.") &&
!is_null($_POST['card_number']) &&
!is_null($_POST['expiration_date']) &&
!is_null($_POST['security_code'])
)
)
)
What gives?
"dispatch_address_postcode isn't mandatory and it will still run even if it's blankā€¦"
Just look at that sentence again. If the field is not mandatory, it is perfectly okay if the code runs if the field is blank. If a field isn't mandatory, don't test it as mandatory.
The real problem is though, is_null only tests if the variable is null. POSTed values will never be null, if they're empty they will be '' (an empty string). All your !is_null tests will always be true, and you will get a warning if the variable isn't set (something you don't want to happen). The more appropriate test would be !empty.
Even more appropriate tests would include a test if the value appears to be valid (does email look like an email address, does telephone have at least x digits in it?). You should also loop through the fields to make your code more readable, endless nested and chained if conditions are no joy to look at.
$mandatoryFields = array('foo' => 'email', 'bar' => 'telephone');
foreach ($mandatoryFields as $field => $rule) {
if (empty($_POST[$field]) || !validateByRule($_POST[$field], $rule)) {
raiseHell();
}
}
It looks like you're trying to make sure all post variables are submitted. Would you like help with that?
Using !empty() may not be the answer to your specific question, but it would definitely help with what it looks like you're trying to do.
empty() returns TRUE if the $_POST key isn't set, if its an empty array, or even if its an empty string, so using !empty() is a good way to make sure that the user has filled in the information.
Try writing your own is_valid function and use that rather than is_null.
For example (and this is by no means comprehensive):
function is_valid(&$array, $key, $required=false) {
if(!array_key_exists($array))
return false;
$value = trim($array[$key]);
if(empty($value) && $required)
return false;
return true;
}
Use like so:
if(is_valid($_POST, 'personal_info_first_name', true) && ...)
!is_null($_POST['personal_info_first_name']) && !isset($_POST['personal_info_first_name'])
use array_key_exists('card_number', $_POST) && !empty($_POST['card_number'])
Edit: Please consider this before a downvote. I'm leaving this here to serve as a "what not to do". I would delete it because it's bad, but then nobody would learn from my mistakes.
DO NOT DO THIS - read the comments for great info on why this is bad
My answer is going to be wildly different, but I am a wildly different guy...
I JUST found that this will work. Instead of all that isset and things, just assign the variables programmatically! I think I have some refactoring to do... y'know on all my code...
if (!is_array($_POST)){exit "$_POST isn't an array";}
foreach ($_POST as $param => $value){
${$param} = secure($value);
}
//now you have a set of variables that are named exactly as the posted param
//for example, $_POST['personal_info_first_name'] == $personal_info_first_name
if ($payment_method == "Pay by credit card."){
//do stuff that you were gonna do anyways
} else if ($payment_method == "Pay by new credit card.") {
if ($card_number && $expiration_date && $security_code){
//do stuff that you were gonna do anyways
} else {
exit("info missing for credit card transaction");
}
} else {
exit("unknown payment method")
}
function secure($input){
//sanitize user input
}
If you use this code, then it doesn't matter what is null and what isn't within the foreach because anything that's null just won't be made. Then you can use nicer looking code (and probably faster code) to check for anything that is required.

I need to check if multiple items are set and not empty in PHP

Below is a snippet of PHP that I need to get working, I need to make sure that 3 items are not set already and not === ''
I have the part to make it check if not set but when I try to see if the values are empty as well (I might not even be thinking clearly right now, I might not need to do all this) But I need to make sure that redirect, login_name, and password are all not already set to a value, if they are set to a value I need to make sure that the value is not empty.
Can someone help, when I add in check to see if values are empty, I get errors with my syntax, also not sure if I should have 5-6 checks like this in 1 if/else block like that, please help
I need to check the following:
- $_GET['redirect'] is not set
- $_REQUEST['login_name'] is not set
- $_REQUEST['login_name'] is not != to ''
- $_REQUEST['password'] is not set
- $_REQUEST['password'] is not != to ''
if (!isset($_GET['redirect']) && (!isset($_REQUEST['login_name'])) && (!isset($_REQUEST['password']))){
//do stuff
}
UPDATE
Sorry It is not very clear, I was a bit confused about this. Based on Hobodaves answer, I was able to modify it and get it working how I need it. Below is the code how I need it, it works great like this... So if that can be improved then that is the functionality that I need, I just tested this.
if (!isset($_GET['redirect'])
&& empty($_GET['redirect'])
&& isset($_REQUEST['login_name'])
&& !empty($_REQUEST['login_name'])
&& isset($_REQUEST['password'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
if this was loaded then it will run the login process
login.php?login_name=test&password=testing
If this is loaded then it will NOT run the login process
login.php?login_name=test&password=
if (!isset($_GET['redirect'])
&& !isset($_REQUEST['login_name'])
&& empty($_REQUEST['login_name'])
&& !isset($_REQUEST['password'])
&& empty($_REQUEST['password'])
) {
// do stuff
}
This is exactly what you describe, (not != empty === empty). I think you should edit your question though to explain what you're triyng to do, so we can suggest better alternatives.
Edit:
Your updated question can be simplified as:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
} {
// load user
}
A more maintainable solution would be storing each key in an array, and then foreach over it and check if isset or empty. You're not very DRY with your current solution.
The implementation would look someting like:
<?php
$keys = array('login_name', 'password');
foreach($keys as $key)
{
if(!isset($_REQUEST[$key]) || empty($_REQUEST['key'])
// Show error message, kill script etc.
}
// Dot stuff
?>
If a global variable is not set, that is the same as being empty. Thus:
!is_set(($_REQUEST['username'])) is the same as empty($_REQUEST['username'])
So based on your update, you can simplify to:
if (empty($_GET['redirect'])
&& !empty($_REQUEST['login_name'])
&& !empty($_REQUEST['password'])
) {
echo 'load user';
}
please read!
Sorry, the previous answer I gave will not give you what you want. Here is why:
If you use !_REQUEST['password'], it will return true if the password is empty or if it is not set. However if you use if($_REQUEST['password']) it will pass the conditional anytime that global variable is set, even if it is empty.
Therefore I recommend:
$no_redirect = (!$_GET['redirect']);
$login_name = (!$_REQUEST['login_name']) ? false : true;
$password = (!$_REQUEST['login_name']) ? false : true;
if($no_redirect && $login_name && $password) {
echo 'load user';
}
Sorry for the previously bad info.
You could create an array
$array = array(
$_GET['redirect'],
$_GET['redirect'],
$_REQUEST['login_name'],
$_REQUEST['login_name'],
$_REQUEST['password'],
$_REQUEST['password']
);
foreach($array as $stuf)
{
if(!empty($stuff) && $tuff !=0)
//do something
}

Categories