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');
}
Related
I'm trying to check if the first $_COOKIE['one'] exists OR the second $_COOKIE['two'] exists and if none exists to redirect the user.
Only one of those two cookies are going to exist when this script is running.
if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
header('Location: ./');
} else {
...
}
I tried many things but every time I get into this if altough one of those cookies always exist.
This is a simple case of inverted logic. As Mark pointed out, you need to be using the boolean && (AND) operator. You are trying to see if both don't exist, then send the header. Currently, if either exists, you send the header anyway.
Just change if (!isset($_COOKIE['one']) || !isset($_COOKIE['two'])) {
to
if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
Or (||) returns true if either the left or right of the statement is true. And (&&) returns true only if both parts of the statement are true. The Not(!) operator reverses true->false and false-> true.
isset tells you if the cookie exists. If the cookie exists, it returns true. You are correct in using not on this, as you want it to tell you if the cookie doesn't exist (opposite). However, you only want to send the header if BOTH cookies don't exist. Or will send it if one doesn't exist.
You wrote an opposite logic to what you really want.
You said that
You're trying to check if
That's an if conditional.
the first $_COOKIE['one'] exists
For that you use isset, which you did and it's right.
OR the second $_COOKIE['two'] exists
So you'd use the OR operator ( || )
and if none exists to redirect the user.
That's an else, and then use header to redirect.
Converting your words to literal code, you'd have this:
if (isset($_COOKIE['one']) || isset($_COOKIE['two'])) {
//... Do your thing
} else {
header('Location: ./');
}
Your code also works with the fix provided by Mark in the comments, but might confuse you in the future...
You can also do this to avoid nesting:
if (!(isset($_COOKIE['one']) || isset($_COOKIE['two']))) {
{
header('Location: ./'); exit;
}
//... Do your thing
If only one of the cookies will ever be set then then your if condition will always be true so the redirect will happen.
Change || for &&,
if (!isset($_COOKIE['one']) && !isset($_COOKIE['two'])) {
header('Location: ./');
} else {
//
}
More elegantly, isset() can handle muliple arguments and negating its return value will give you exactly what you want.
Code: (Demo)
var_export(!isset($cookie1, $cookie2)); // Are either missing? Yes, both are missing.
echo "\n";
$cookie1 = 'declared';
var_export(!isset($cookie1, $cookie2)); // Are either missing? Yes, one is missing.
echo "\n";
$cookie2 = 'declared';
var_export(!isset($cookie1, $cookie2)); // Are either missing? No, neither are missing.
Output:
true
true
false
When checking if multiple $_POST variables have been set, would the following:
if(isset($_POST['year']) && isset($_POST['month']) && isset($_POST['day'])){
}
be the same as:
if(isset($_POST)){
}
or would isset($_POST) return true if only one $_POST variable has been set?
use empty
if(empty($_POST['year']) and empty($_POST['month']) and empty($_POST['day'])){
// Empty
}
else
{
//Not empty
}
but best way to check(my Opinion use OR )
if(empty($_POST['year']) || empty($_POST['month']) || empty($_POST['day'])){
// Empty
}
else
{
//Not empty
}
Usage of isset()
The isset () function is used to check whether a variable is set or not. If a variable is already unset with unset() function, it will no longer be set. The isset() function return false if testing variable contains a NULL value.
Usage of empty()
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.
if You use empty() it will act both of these if(isset($_POST) && $_POST!=""){
if(isset($_POST) && $_POST!=""){
}
Write this code i hope this is Work
I want to check if $_POST['submit'] is posted.
My original code was:
if ($_POST['submit']) { }
But I have a PHP notice with this code - "Undefined index: submit in..."
So to remove the notice I have to write this:
if (isset($_POST['submit'])) { }
But this is pointless because $_POST array is global and it return always true.
Also if I want to check if $_POST['submit'] is not 0 without PHP notice I have to write this:
if (isset($_POST['submit']) && $_POST['submit'] != 0) { }
In this particular case I prefer:
if ($_POST['submit']) {}
But here I get the PHP notice.
So which way is the most proper/accepted?
Thank you
isset($_POST['submit']) checks if the submit key is set in the $_POST array. It doesn't just check whether the $_POST array exists and is therefore not "pointless". If you want to check whether the value is not falsey (== false), which includes 0, without triggering an error, that's what empty is for:
if (!empty($_POST['submit']))
which is the same thing as
if ($_POST['submit'])
but without triggering a notice should the value not exist.
See The Definitive Guide To PHP's isset And empty for an exhaustive explanation.
Try
if ($_SERVER['REQUEST_METHOD']=='POST')
{
//do
}
As of PHP version 7 there is a new method available called "Null Coalesce Operator". This method saves you time and space in your code.
$submit = $_POST['submit'] ?? '';
If submit key does not exist or is NULL the value of the $submit variable will be an empty string.
This method is not limited to $_POST. It will work for any variable. For example:
echo $my_message ?? 'No message found';
If message was not initialized or is NULL, the statement above will output No message found
There's even more that you can do with a null coalesce operator, documentation link below.
Documentation here
$_POST[] checks to see if a variable is submitted and not the form name.
if ( isset($_POST['name']) ) {
// work here
}
As per my understanding, It should be like below:
if (isset($_SERVER) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD']=='POST'){
# if method is post, code goes here.
}
and if you are sure that your method is POST for sure. and you have data post in $_POST you can use code like below:
if (isset($_POST['submit']) && $_POST['submit'] != '') {# I think, '' instead of 0
# if data is posted, code goes here.
}
I usually prefer $_POST.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
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
}