Better way of doing isset($variable) and check variable value - php

I was wondering if there's a better way than what I always do to check the value of a variable that might not be set? For example :
if(isset($_SESSION['super_user']) && $_SESSION['super_user'] == true) {
echo 'hi super user';
}
It would much simpler to just do this :
if($_SESSION['super_user']) {
echo 'hi super user';
}
But I would end up with a notice of undefined index. Is there another way of doing such kind of simple validation or I must stick with my actual way of doing it?
Thanks

if (!empty($_SESSION['super_user'])) {
// ...
}

You could initially set $_SESSION['super_user'] to false and only set it to true if the user is a super user. Then you can always use if ($_SESSION['super_user']) {}.

For the particular example your current code could be shortened to
if(!empty($_SESSION['super_user']))
however, the right way would be
if ($_SESSION['role'] == 'super_user')
I was wondering if there's a better way than what I always do to check the value of a variable that might not be set?
Yes. Always define all your variables. Like one I posted above. Always have a role element for all your users and there will be no need to check if it ever exists.

Related

Efficient way to check multiple variables declarations?

In a project of mine I am working with a sequence of pages that each give information that is used in the next, with POST and session variables. Simple example:
Page 1: enter name -> page 2 display name; ask birth date -> page 3 display name and birth date.
If a user goes directly to page 3 I want to display a message that s/he has not entered a name and/or birth date and should try again. Currently I am still doing it like so. On page 2:
if (isset($_POST['name'])) $_SESSION['name'] = $_POST['name'];
and page 3:
if (isset($_SESSION['name'])) $name = $_SESSION['name'];
if (isset($_POST['bday'])) $_SESSION['bday'] = $_POST['bday'];
as declarations and in the body an if-clause like
if (isset($name) && isset($_SESSION['bday'])) {
// do main stuff
else {
// display error message
}
The example is simple enough, but in the real world my code has a lot more variables and data from the forms, and putting all this first in variable assignments and then in an if-clause is tiring and seems not efficient to me. Is there a better, more straightforward way to check things like this? Or is what I posted the best, most-used way to go?
You can use one call to isset to check several variables.
isset($_SESSION['name'], $_SESSION['bday'], ...)
Or you can write your own function like
if (variablesFilled(['name', 'bday', ...])) { }
function variablesFilled($array) {
foreach ($array as $entry) {
if (!isset($_SESSION[$entry])) {
return false;
}
}
return true;
}
I believe you just need to write some helper methods. One to rewrite $_POST data to $_SESSION, dumb as this:
function copyPostToSession(array $fields) {
foreach($fields as $field) {
if(isset($_POST[$field])) {
$_SESSION[$field] = $_POST[$field];
}
}
}
so instead of if forest, you do:
copyPostToSession(array('name','bday'));
(additionally you can count how many fields were present and return true or false if there's mismatch) and the other (pretty similar) to check if you got all the required data in $_SESSION.
PHP's isset() function is a variadric function.
You can put as many arguments as you want:
isset($a, $b, $c)
...which translates to:
isset($a) && isset($b) && isset($c)
Hope it helped!
Seperate functions tend to differ a bit on a per server case. You could try calculating the time to perform a function a large number of times and compare which is faster.
But, yeah, that looks like fairly fast code there.
Might be worth trying a switch case statement as an alternative perhaps?

Even if array for foreach is empty, run it

I've came across a little problem. Well I'm getting from wordpress database some user_meta data, which is stored as array, by declaring variable $all_meta_for_user = get_user_meta($user_id, 'meta_key', false). Then, I'd like to check if some specific data is present, and if so, do something, if not, do something else. I've got somewhere here at stackoverflow a hint, that I can achieve it in that way:
foreach($all_meta_for_user as $key=>$val) :
if (array_key_exists ('some_key', $val) && array_key_exists ('some_other', $val)) { do something } else {do something else }
endforeach;
And that works good, as long as associated 'meta_key' is present in database (which is obvious :)). But what, if it's not? Then, again obviously, foreach is false and it doesn't run.
Basically, I'd like to show content after else even if the array is empty. How I can alter my code, to achieve that? I think I could get it working, if I first check if array is empty, if no - do code with foreach, if yes - do my else. But the problem is, in my else there's a lot of code, so I'd like to avoid duplicating it.
So, simply, the question is, how to make that in a nice way, that will not double my code :)
Thanks!
PS I really couldn't find appropriate topic name. If someone have a better idea how to name it, please leave a comment so I can change it! Thanks!
You can create your "else" function, and combine that with the if/else idea. That way you won't have any repetition, just function calls:
function elseFunction() {
//do something else
}
if (!empty($all_meta_for_user)) {
foreach($all_meta_for_user as $key=>$val){
if (array_key_exists ('some_key', $val) && array_key_exists ('some_other',$val)){
// do something
}
else {
elseFunction(); // this is changed
}
}
}
else {
elseFunction();
}

Error-message for failed register, login etc. - Use $GLOBAL oder $_SESSION?

For example:
If anyone fails at the login function (for example: enters wrong password) on my webpage, i want to show an error-message at the webpage. My idea was like that:
if(doLogin()) {
//....
}else {
$GLOBAL['errorLogin'] = "Wrong Userdata";
}
and then echo the global-variable in the .html.
But i searched also for this topic and found only this method, but everyone had used the $_SESSION variable for this instead of $GLOBAL.
Is my variant with the $GLOBAL varible wrong or bad practise?
And why use $_SESSION for a error-message, if i only echo the message one time and don't need it in the next request?
I think you mean $GLOBALS (notice the s) which is a suber global variable and therefore can be accessed from anywhere in the PHP script (also from within functions or methods).
There is nothing wrong about that.
I don't think that you should use the $_SESSION variable for that, because the user needs to see the error message only one time. In your case, and in most cases, that's why it might make no sense to store it in a session.
Personally, I just would use a custom errorMessage-Array, like that:
//store all Error Messages in one array.
$errorMessages = array();
if(doLogin()) {
//....
}else {
$errorMessages["Login"] = "Wrong Userdata";
}
//...
foreach($errorMessages as $key=>$message){
echo $key.": ".$message."<br>";
}

Multiple isset with OR possibility

I'm trying to display items a specific way...
First I want to check if $MYCAR_model exists (this is a session value). If not, do nothing.
Next I want to make sure that the URL variable cat is set to either 1 or 2. If not, also do nothing.
The URL would look like this...
http://www.mysite.com/?cat=1
My failed code...
if (isset($MYCAR_model) && ($cat=='1' || $cat=='2')) {
// show stuff
}
Thank you for any help you can provide.
Maybe
if (isset($_SESSION["MYCAR_model"]) ...
You can also use $_REQUEST["cat"] instead of $_GET["cat"] so that you don't need to worry about the parameter being passed via GET/POST/COOKIES.
if (isset($_SESSION['MYCAR_model']) && ($_GET['cat'] =='1' || $_GET['cat'] =='2')) {
// show stuff
}

PHP undefined index error when clicking a url and invoking a php script

I have a call to a PHP script from my home page which I do like this:
echo 'Delete';
So it is pretty standard.
Then in my PHP I have this code:
<?php
// delete_problem
include '../connect.php'; // Here I have db connection settings
error_log ( ".......in delete problem");
$problem_id = mysql_real_escape_string($_GET["problem_id"]);
?>
And the last line where I try to get the problem_id is throwing the undefined index error. Any idea why?
Thanks!
Have you got an actual connection inside connect.php? Or does it just store variables and the like?
mysql_real_escape_string may be causing a problem as if a connection is not available it will fail.
Beyond that, try echoing out the contents of the GET variable. You can also check whether it exists by using (isset($_GET["problem_id"])).
For values coming from the user, always make sure they are present and possibly validate their format.
Use:
if (isset($_GET['problem_id']) && trim($_GET['problem_id']) != '') {
$problem_id = $_GET['problem_id'];
// make sure it is a number
} else {
echo "No problem id given!";
}
That warning appears because the $_GET array doesn't contain a value problem_id, most likely because it was not passed with the URL.
Bleh, all you people with the mysql_real_escape string...
Always check if a variable is set before you try and assign the value of it to another variable.
Also use (int) to cast!!
if (isset($_GET["problem_id"])){
$problem_id = (int) $_GET["problem_id"];
}

Categories