If variable is set, show $_SESSION data - php

I have a hard time with isset() function. Exactly how do I tell php that only if the data was assigned to my, lets say $_SESSION['msg']; variable, only then activate it and use it... So far I am getting a lot of notices: undefined index and this code doesn't do it also:
if (isset($_SESSION['monster']) &
isset($_SESSION['spol']) &
isset($_SESSION['combat']) &
isset($_SESSION['turns']) &
isset($_SESSION['zmaga']) &
isset($_SESSION['zguba']) &
isset($_SESSION['cekini']) &
isset($_SESSION['post']) )
{
$monster = $_SESSION['monster'];
$spol = $_SESSION['spol'];
$combat = $_SESSION['combat'];
$turns = $_SESSION['turns'];
$zmaga = $_SESSION['zmaga'];
$zguba = $_SESSION['zguba'];
$cekini = $_SESSION['cekini'];
$_POST = $_SESSION['post'];
}
Data was supposed to be asigned to it from a redirecting previous site but that site doesn't always activate so I need an alternative. That's why I am asking this.
EDIT with full code:
session_start();
include 'razno.php';
include 'save.php';
include 'stats.php';
$igralec_ime = $_SESSION['username'];
$monster = prikazi_borba($igralec_ime);
$poskodbe = prikazi_stat('curhp', $igralec_ime);
if (prikazi_stat('curhp', $igralec_ime) == 0)
{
$moznost = 'Tvoje zdravje je resno ogroženo, vrni se domov!';
}
else if (isset($_SESSION['monster']) &&
isset($_SESSION['spol']) &&
isset($_SESSION['combat']) &&
isset($_SESSION['turns']) &&
isset($_SESSION['zmaga']) &&
isset($_SESSION['zguba']) &&
isset($_SESSION['cekini']) &&
isset($_SESSION['post']) )
{
$monster = $_SESSION['monster'];
$spol = $_SESSION['spol'];
$combat = $_SESSION['combat'];
$turns = $_SESSION['turns'];
$zmaga = $_SESSION['zmaga'];
$zguba = $_SESSION['zguba'];
$cekini = $_SESSION['cekini'];
$_POST = $_SESSION['post'];
}
update_save($igralec_ime, 'gozd', $monster);
include '../html/gozd.html';
?>

You'll want to replace & with and:
if (isset($_SESSION['monster']) and isset($_SESSION['spol']) and isset($_SESSION['combat']) and isset($_SESSION['turns']) and isset($_SESSION['zmaga']) and isset($_SESSION['zguba']) &
isset($_SESSION['cekini']) and isset($_SESSION['post']) )
{
$monster = $_SESSION['monster'];
$spol = $_SESSION['spol'];
$combat = $_SESSION['combat'];
$turns = $_SESSION['turns'];
$zmaga = $_SESSION['zmaga'];
$zguba = $_SESSION['zguba'];
$cekini = $_SESSION['cekini'];
$_POST = $_SESSION['post'];
}

You should take a look at logical operators in PHP. In many programming languages (PHP included) & is 'bitwise and' operator (not logical). Since you want logical operator you need to use && or and. Also take a look at other PHP operators, just to get familiar with them and to avoid problems like this.
Also if you are using those values outside the if/then block you should think about cases when your statement will be false and assign some default values to those variables.

Related

PHP compare is not working

$snumber = trim($_POST['sn']);
$site_name =strtoupper(trim($_POST['mn']));
$physical = trim($_POST['pp']);
$logical = trim($_POST['lp']);
$port_info =strtoupper(trim($_POST['ti']));
$srlt = mysql_query("select subscriber,terminationid from portinfo") or die(mysql_error());
while($wow = mysql_fetch_array($srlt)){
$suesno =trim($wow["subscriber"]);
$porting = trim($wow["terminationid"]);
if(($suesno == $snumber and $porting == $port_info )){
}
}
the comparison for $suesno and $snumber is working. $suesno is stored in the database as 6661235. but the comparison of $porting and $port_info is not working. and $porting is stored in the database as USER00301500030
try to use && instead of and in if condition

how to compare array for single result using if statement

i was doing validation for user form after each validation i used to store "valid" in a array index and at last comparing them like this:
if(isset($fullname)){
if ($valid["name"]=="valid"&&$valid["username"]=="valid"&&$valid["password"]=="valid"&&$valid["email"]=="valid") {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}
Well i will check validation and then make session .
My question is there any short way to check the whole array across a single value like "valid"?
I hope you have understand my question.Comment it if it is not asked well.
Do not rate as negative.Please ignore my grammar mistakes.I hate those who edit my question's grammar.
You can just count the number of unique values and check if it's equal to 1, then check one value if it is "valid".
if (count(array_unique($valid)) === 1 && $valid["name"] === "valid") {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}
Or just simply check if a "notvalid" value is found in the array:
if (!in_array("notvalid", $valid)) {
session_start();
$_SESSION["reg_name"] = $fullname1;
$_SESSION["reg_username"] = $username1;
$_SESSION["reg_email"] = $email1;
$_SESSION["reg_password"] = $password1;
$_SESSION["reg_gender"] = $_REQUEST['gender'];
header("location:validation&insertion.php");
}

php loop display result if isset and matches the given value

I am sorry to ask such a question but am bit confused about this.
I am having simple variables defined.
$a =1;
$b=2;
$c=3;
$d="";
for($i=0;$i<10;$i++)
{
$testa = 1;
$testb = 4;
$testc = 3;
$testd = 7;
if($a!="" || $b!="" || $c!="" || $d!="") {
if($a==$testa && $b==$testb && $c==$testc && $d==$testd) {
echo $testa;
echo $testb;
echo $testc;
echo $testd;
}
}
}
This is sample php code.
what I need is that I have variables defined at top. SO in my loop i want to display result if user has any 1 variable but in below loop display result based on "and" parameter.
I actually want to skip the empty variable. SO in this case, I want as $d is empty, so it should be prevented somehow from if($a==$testa && $b==$testb && $c==$testc && $d==$testd) from here.
Any help is really appreciated.
To skip the empty values from the check, use ||
if ( ... && (empty($d) || $d == $testd)) {
Then if you also want to skip it in your echos :
echo !empty($d) ? $testd : '';

isset variables created using extract function

$array = explode('/', $_SERVER['REQUEST_URI']);
$count = count($array);
extract($array, EXTR_PREFIX_ALL, 'var');
can the variables (created using extract function) be isseted automatically? to avoid "Notice: Undefined variable:" errors when error_reporting(E_ALL); is enabled.
thank you
I tried doing something of this sort, still needed to isset() whenever, the variables are used next in the code (when error_reporting(E_ALL); is enabled).
if(isset($var_0))
{
$var_0 = filter_var($var_0, FILTER_SANITIZE_STRING);
}
if(isset($var_1))
{
$var_1 = filter_var($var_1, FILTER_SANITIZE_STRING);
}
if(isset($var_2))
{
$var_2 = filter_var($var_2, FILTER_SANITIZE_STRING);
}
if(isset($var_3))
{
$var_3 = filter_var($var_3, FILTER_SANITIZE_STRING);
}
==========================
Alternatively, tried the one line if condition,
$var_0 = isset($var_0) ? filter_var($var_0, FILTER_SANITIZE_STRING) : '';
$var_1 = isset($var_1) ? filter_var($var_1, FILTER_SANITIZE_STRING) : '';
$var_2 = isset($var_2) ? filter_var($var_2, FILTER_SANITIZE_STRING) : '';
$var_3 = isset($var_3) ? filter_var($var_3, FILTER_SANITIZE_STRING) : '';
while the error got subsided, but, a new problem arises i.e., variables (which are not created by extract function are getting isseted because of this one line if condition approach).
I am posting two of the routing rules (of two urls) in the website.
$pagename = "not-found.php";
//Different Routing Engine Rules follows
if ((isset($var_1)) && (($var_1 == "") || ($var_1 == "index.php"))) {
if((isset($var_2)) || (isset($var_3)) || (isset($var_4)) || (isset($var_5)) || (isset($var_6)) || (isset($var_7)))
{
$pagename = "not-found.php";
}
else
{
$pagename = "default-home.php";
}
}
if (($var_1 == "login"))
{
//echo "Login Page URL\n";
if((isset($var_2)) || (isset($var_3)) || (isset($var_4)) || (isset($var_5)) || (isset($var_6)) || (isset($var_7)))
{
$pagename = "not-found.php";
}
else
{
$pagename = "login.php";
}
}
include "code/" . $pagename;
any help will be appreciated, thank you
If I understand your question correctly then, no. It's still your responsibility to know what variables are available and act accordingly. You can simply disable these notices via error_reporting(E_ALL & ~E_NOTICE) for the portion of code in question.
Edit
Looking at your updated question, I think it would be helpful if you could explain what you're trying to achieve. Personally, I see the use of extract as a bit of a code smell and there may be a better way :)

How can I rewrite this code to improve its clarity?

Could you write this 'cleaner' ? Just a simple question from a beginner:)
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
I would do it like this:
$tid = isset( $_GET['tid'] ) ? trim( $_GET['tid'] ) : '';
$fid = isset( $_GET['fid'] ) ? trim( $_GET['fid'] ) : '';
$mid = isset( $_GET['mid'] ) ? trim( $_GET['mid'] ) : '';
$act = isset( $_GET['act'] ) ? trim( $_GET['act'] ) : '';
if ( empty( $act ) ) // act not set, construct the act from the other GET vars
{
if ( !empty( $tid ) )
$act = 'tid';
else if ( !empty( $fid ) )
$act = 'fid';
else if ( !empty( $mid ) )
$act = 'mid';
}
edit: Of course you could make this even shorter, but the question was how it could be written to “improve its clarity”. And I understand clarity as something that makes it more easy to understand, what happens in a part of code. And I think the actual logic behind the original code gets quite clear with my solution.
I see nothing bad in your code apart from lack of indentation:
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
Although perhaps you could benefit from a function like this
function get_non_empty($field){
return isset($_GET[$field]) && trim($_GET[$field])!='' ? $_GET[$field] : NULL;
}
Definitely not the 'cleanest' solution, but a lot shorter:
$act = '';
foreach(array('tid', 'fid', 'mid', 'act') as $a) {
if(isset($_GET[$a]) && strlen(trim($_GET[$a])) > 0) {
$$a = trim($_GET[$act = $a]);
break;
}
}
This is nearly identical logically to what poke did (+1 for poke for beating me to it), but since we're talking about clarity I thought I'd show my take on it. I like to use FALSE instead of empty strings when it means something isn't being used. It feels like a more explicit way of saying "no". Also, I rarely use the non-bracketed version of if/else but for really short assignment statements I find it way easier to read.
$tid = isset($_GET['tid']) ? trim($_GET['tid']) : FALSE;
$fid = isset($_GET['fid']) ? trim($_GET['fid']) : FALSE;
$mid = isset($_GET['mid']) ? trim($_GET['mid']) : FALSE;
$act = isset($_GET['act']) ? trim($_GET['act']) : FALSE;
if ($act){ // act not set, construct the act from the other GET vars
if ($tid) $act = 'tid';
else if ($fid) $act = 'fid';
else if ($mid) $act = 'mid';
}
Careful with those raw GET values. You should clean those values up before processing them to make sure you are getting exactly what you want, especially if this is about to insert values to a database.
Here is one way. I would however probably do something differently with the tid,fid,mid stuff if I knew what they was intended for.
list($act,$val) = firstValidGETIn('tid','fid','mid','act');
switch($act) {
case 'act': $act = $val; break;
case null : $act = ""; break;
default : $$act = $val;
}
function firstValidGETIn()
{
foreach(func_get_args() as $key)
{
if(array_key_exists($key,$_GET) && trim($_GET[$key]))
return array($key, trim($_GET[$key]));
}
return array(null,null);
}

Categories