on $_GET set $_SESSION wont work - php

I need to get the last non-empty value that $_GET['id_item'] had
session_start();
if(!isset($_SESSION['id_item']) || $_SESSION['id_item']==='' || ( isset($_GET['id_item']) && !$_GET['id_item'] === '' )){
$_SESSION['id_item'] = $_GET['id_item'];
}else{
/*no need to update*/
}
echo $_SESSION['id_item'] /* Allways in blank :S */
And var_dump($_GET) outputs:
array(1) { ["id_item"]=> string(2) "50" }
Any idea why the $_SESSION is not saved?

fix this:
$_SESSION['id_item']=='' to $_SESSION['id_item']===''
or you can use:
empty($_SESSION['id_item'])

unless you expect a (valid) ID to be 0 you can reduce !isset($_SESSION['id_item']) || $_SESSION['id_item']==='' to empty($_SESSION['id_item']). !$_GET['id_item'] === '' is always false, as this translates to false === ''. You were probably looking for $_GET['id_item'] !== ''. Again, if 0 is not a valid value, you can go for !empty($_GET['id_item']) here.
That said, the whole !isset($_SESSION['id_item']) || $_SESSION['id_item']==='' part of the condition doesn't make much sense. The second part "if _GET id_item present" is always necessary for the condition's body ($_SESSION['id_item'] = $_GET['id_item'];) to work. So you can reduce your condition to
<?php
if (!empty($_GET['id_item'])) {
// import new id_item
$_SESSION['id_item'] = $_GET['id_item'];
} elseif (!isset($_SESSION['id_item'])) {
// make sure we don't run into an undefined array index notice
$_SESSION['id_item'] = null;
}
var_dump($_SESSION['id_item]);

Have you output anything before the start_session. If so it will be unable to send the cookie. This is probably why it is not working.

Related

The Below IF condition is not working properly

I have an if statement which is the below one. But its not working i dont know the reason.
if ((($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) && $posted['pref_sal_prd'] != -1) || $posted['pref_sal_optn'] != -1){
// Success code
} else {
// Else Part
}
What's wrong in my code?
Here I need either one in first two, and if either one is not empty than the third one should be compulsory.
if these three should be true or the fourth one is true like this.
EDIT :
array(4) { ["pref_sal_brn"]=> string(3) "234" ["pref_sal_end"]=> string(3) "500" ["pref_sal_prd"]=> string(2) "47" ["pref_sal_optn"]=> string(2) "51" }
this is the output, first two parameters are salary begin and end, thrid one is period option like day, month, weekly,
and the fourth one is some options like , negotiable, minimum wage, like that. so first two are integers, third fourth are drop down lists for the items.
Just tested your code in phpfiddle.org and it is working properly. it will print success as it is supposed to
`
$posted['pref_sal_brn'] = "234";
$posted['pref_sal_prd'] = "47";
$posted['pref_sal_end'] = "500";
$posted['pref_sal_optn'] = "51";
if (( ($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) && $posted['pref_sal_prd'] != -1) || $posted['pref_sal_optn'] != -1) {
echo 'success';
} else {
echo 'failure';
}
?>
This answer is based on what i understand while reading and analyzing your question, Your question is kinda hard to understand but this is what i grasp so far. Correct me if im wrong
Based on my understanding you cannot have it with one liner condition. you might want to break them into separate ifs
You said:
I need either one in first two(pref_sal_brn and pref_sal_end), and if either one is not empty
then the third one should be compulsory. (do this if above is true)
if these three should be true (I understand this that 1 and 2 above should be true)
or the fourth one is true like this. (or if the fourth one is true then whole process is true)
Breaking them and turning them into code:
// CHECK FIRST IF THE pref_sal_optn is TRUE, IF IT IS TRUE THEN DISREGARD OTHER CONDITION
if ($posted['pref_sal_optn'] != -1) {
// success
}
// NOW CHECK IF pref_sal_brn OR pref_sal_end IS NOT NULL
elseif ($posted['pref_sal_brn'] != null || $posted['pref_sal_end'] != null) {
// YOU DISCOVERED THAT EITHER ONE OF pref_sal_brn OR pref_sal_end IS NOT NULL THEN CHECK IF pref_sal_prd IS != -1 IF TRUE THEN DO SUCCESS AGAIN
if ($posted['pref_sal_prd'] != -1) {
// success
} else {
// error
}
} else {
// error
}

PHP - refactoring this if statement to avoid duplication

In this snippet of code we type $inputs['user_id'] 3 times.
if (isset($inputs['user_id']) && $inputs['user_id']) { // The consumer is passing a user_id
doSomethingWith($inputs['user_id']);
}
What's the most readable and robust refactoring I can do to avoid the duplication and avoid any notice that the index user_id doesn't exist?
Thanks.
Here nothing is wrong with the duplication. You cannot assign $inputs['user_id'] to a variable before checking if it is set, otherwise this will produce a Notice undefined index ....
The only thing here could be done is to omit the isset call and use !empty instead, like this:
if(!empty($inputs['user_id'])) {
doSomething($inputs['user_id']);
}
Now You are only typing it twice and the check
!empty($inputs['user_id'])
equals to
isset($inputs['user_id']) && $inputs['user_id']
EDIT: based on a comments, here is a quote from documentation:
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
So either empty(0) or empty('0') will return true, that means
if(!empty('0') || !empty(0)) { echo "SCREW YOU!"; }
will echo nothing... Or, in polite way, I will repeat the statement above:
!empty($inputs['user_id']) === (isset($inputs['user_id']) && $inputs['user_id'])
EDIT 2:
By omitting the isset and replacing by !empty the variable is still checked, whether the index is already set, please read the documentation, which says:
No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.
What about this:
// put validation check to the function body
function doSomethingWith($userId) {
if($userId === -1) {
// if this is not a valid user id -> return
return;
}
// do something ...
}
// initalize $user with proper default values.
// doing so you can be sure that the index exists
$user = array(
'id' => -1,
'name' => '',
...
);
// merge inputs with default values:
$user = array_merge($user, $request);
// now you can just pass the value:
doSomethingWith($user['id']);
Below might not be the best way for every situation, but definitely cuts down on the repetition.
Your example code would turn into:
doSomethingWith($inputs['user_id']);
and your function would look like this (notice the argument supplied by reference, to avoid the undefined variable warning):
function doSomethingWith(&$userID) {
if (empty($userID)) return;
// ... actual code here ...
}
Assuming that 0 and "" and null are not valid user_ids:
if ($id = $inputs['user_id']) {
doer($id);
}
YOu can also do with evil # to avoid notice in your logs, (I don't like this way):
if ($id = #$inputs['user_id']) {
doer($id);
}

Why do I have to check "IF" ($_GET["$view"]) && $_GET("$view")! . What does "!" mean? Why does it equal = ""

I can't understand that if sentence. Why can't I just check if $view is set? 2 more questions -What does "$_GET("$view")!" "!" sign mean there? What does ! change? Moreover, why does it equal = " "?
<?php
$myurl=htmlspecialchars($_SERVER["PHP_SELF"]);
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
include(head.html);
switch($view] {
case "" :
include(main.html);
break;
case "people" :
include(people.html);
break;
case:"contact":
include(contact.html);
break;
default :
include(404.html);
break;
};
include_once(foot.html;
?>
Thanks for all the help
I think you messed up your code. This will not execute, due to numerous errors. The if statement is probably
if(isset($_GET[$view]) && $_GET[$view] != "")
Ie, first check that the $view key exists, then check that key it is not empty. Note the difference between a key that does not exist, and a key that exist but is empty, and why you check for both in this case.
Why can't I just check if $view is set?
Because apparently the author of that code didn't want the empty string to be valid. This will be the case if, say, there is a field called $view and the user does not put anything in it.
Actually, you could do that, since $view is initialized to the empty string anyway! This code was probably copy/pasted or written by a novice.
What does ! change?
It's actually !=, written in a confusing way. These two are the same:
&& $_GET("$view")! = "")
&& $_GET("$view") != "")
Also, your code has a bug. $_GET("$view") is not valid, the () should be []. So, here is the corrected and readable code:
if (isset($_GET["$view"]) && $_GET["$view"] != "") {
$view = $_GET["$view"];
}
Also:
switch($view] // ...what is this?
include_once(foot.html; // and this?
case:"contact": // ummmm
$view="";
if(isset($_GET["$view"]) && $_GET("$view")! = "") { $view =$_GET["$view"];};
You actually set $view=""; as an empty parameter
There for isset($_GET["$view"] looks like this isset($_GET[""]
You whole if statement with the above code is ignored
Likewise your switch($view); also looks like switch("")
This means only your first case will be executed no matter what you have in your $_GET
Check this portion of your code too for errors. the colon after case needs to be removed
case:"contact":
include(contact.html);
break;
For first, use correctly [] and (). Then you have to learn about operators: http://www.w3schools.com/php/php_operators.asp
For now your code is non-sense.

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']))){}

Test for query variable exists AND ALSO is set to a particular value?

I want to check if a query variable exists or not. Then I would do something based on that query value. If it exists and is true, do something. If it doesn't exist or is false, do something else such as show a 404 page.
e.g If the url was domain.com?konami=true
if (condition) {
//something
} else {
//show404
}
OPs question is a bit unclear. If you assume that he wants to check that konami is a $_GET parameter and that it has the value of "true" do:
if (isset($_GET["konami"]) === true && $_GET["konami"] === "true") {
// something
} else {
// show 404
}
The problem with the current accepted answer (by Cameron) is that it's lacking the isset check (which is unforgivable, it is objectively wrong). The problem of the highest voted answer (by Jan Hancic) is that it lacks the === "true" check (which is debatable, it depends on how your interpret the question).
Note that && is a lazy-and, meaning that if the first part is false, the second part will never be evaluated, which prevents the "Undefined index" warning. So the order of the statements is important.
Also note that $a === true is not the same as $a === "true". The first compares a boolean whereas the second compares a string.
If you do weak comparison $a == true you are checking for truthy-ness.
Many values are truthy, like the string "true", the number 1, and the string "foo".
Examples of falsy values are: empty string "", the number 0 and null.
"true" == true; // true
"foo" == true; // true
1 == true; // true
"" == true; // false
0 == true; // false
null == true; // false
"true" === true; // false
"true" === false; // false
There is a little confusion around what value should be tested. Do you want to test the konami parameter for being true in the sense of boolean, i.e. you want to test konami parameter for being truthy, or do you want to test if it has string value equal to "true"? Or do you want to test konami parameter for any value in general?
I guess what is wanted here is to test konami for a given string value, "true" in this case, and for being set at the same time. In this case, this is perfectly enough:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
...
if ($_GET['konami'] == "true")
...
This is enough, because if the $_GET['konami'] is unset, it cannot be equal to any string value except for "". Using === is not neccessary since you know that $_GET['konami'] is string.
Note that I turn off the E_NOTICE which someone may not like - but these type of "notices" are normally fine in many programming languages and you won't miss anything if you disable them. If you don't, you have to make your code unecessarily complex like this:
if (isset($_GET['konami']) && $_GET['konami'] == "true")
Do you really want to complicate your code with this, or rather make it simple and ignore the notices like Undefinex index? It's up to you.
Problems with other answers as you mentioned:
#Jan Hancic answer: it tests for true, not "true".
#Cameron answer: might be simplified and he didn't mention the necessity of disabling E_NOTICE.
#Frits van Campen's answer: too complex to my taste, unnecessary test for === true
Umm this?
if (isset($_GET['konami']) === true) {
// something
} else {
//show 404
}
Easy:
if(isset($_GET['konami']) && $_GET['konami'] != 'false') {
//something
} else {
// 404
}
quick and simple.
$konami = filter_input(INPUT_GET, 'konami', FILTER_VALIDATE_BOOLEAN) or die();
ref:
filter flags
filter_input
You may try this code. In this code checked two conditions by one if condition that is $konami contains value and $konami contains 'true'.
$konami = $_GET['konami'];
if( ($konami) && ($konami == "true")){
/*enter you true statement code */
}else {
/* enter your false statement code */
}
You can do it like this:
$konami = false;
if(isset($_GET['konami'])){
$konami = $_GET['konami'];
}
if($konami == "true"){
echo 'Hello World!';
}
else{
header('HTTP/1.0 404 Not Found');
}
In this case you'll always have $konami defined and - if set - filled with the value of your GET-parameter.
if(!$variable) {
//the variable is null
die("error, $variable is null");
}else{
//the variable is set, your code here.
$db->query("....");
}
This works best:
$konami = $_GET['konami'];
if($konami == "true")
{
echo 'Hello World!';
}
else
{
header('HTTP/1.0 404 Not Found');
}
Easiest and shortest way of doing it:
if($konami != null){ echo $konami; } else { header('HTTP/1.0 404 Not Found'); }

Categories