Strugling with if, empty, and, or, - php

The following script should create an error when date_enabled is 2 and one of the three variables is empty. When day is empty for example, the script still doesn't echo the sentence.
Does anybody sees the problem?
$year = $_POST['date-year'];
$month = $_POST['date-month'];
$day = $_POST['date-day'];
$date_enabled = 2;
if ((($date_enabled ==2)) && ((empty($year) || empty($day) || empty($month)))){
echo "You didn't enter a valid date";
}
UPDATE - When I perform the following script it echos: its empty its empty (function). Which means that empty and the function isEmpty, which I created because of the advice of #Expert System , also works.
if (empty($day)){
echo "its empty";
}
if (!isset($day)){
echo "its not set";
}
if (isEmpty($day)){
echo "its empty (function)";
}
UPDATE AGAIN - The script above works indeed correctly. The problem lays with my form. It works fine now and thanks for your help.

I believe the definition of "empty" in your question is unclear. If empty in your question means zero-length string, then empty function is not the right one for you.
empty() definition from PHP doucment
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.
Maybe this custom function will work in your context
function isEmpty($var) {
return !isset($var) || ($var == '');
}
Then
if (($date_enabled == 2) &&
(isEmpty($year) || isEmpty($day) || isEmpty($month))){
echo "You didn't enter a valid date";
}

Try this code instead:
$year = isSet($_POST["date-year"]) ? $_POST["date-year"] : "";
$month = isSet($_POST["date-month"]) ? $_POST["date-month"] : "";
$day = isSet($_POST["date-day"]) ? $_POST["date-day"] : "";
$date_enabled = 2;
if ((($date_enabled ==2)) && ((empty($year) || empty($day) || empty($month)))){
echo "You didn't enter a valid date";
}
The problem might be the error of level E_NOTICE raised when you try to access an undefined index in $_POST array.
This shoukd notcause a problem (i.e. stop execution) with theususl/default configuration options, but with yours it might (just guessing).

Related

multiple !isset() with OR conditions in php

if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
My Other Tries:
(!isset($_GET['new_quiz'] || $_GET['view_quiz'] || $_GET['alter_quiz']))
( ! ) Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in
C:\wamp\www\jainvidhya\subdomains\teacher\quiz.php on line 94
(!isset($_GET['new_quiz'],$_GET['view_quiz'],$_GET['alter_quiz']))
NO
You may find than inverting the logic makes the code easier to read, I also like to have a more positive idea of conditions as it can read easier (rather than several nots means no).
So this says if anyone of the items isset() then the answer is Yes...
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo "Yes";
}
else{ echo "No"; }
Note that I've changed the Yes and No branches of the if around.
You are probably looking for
if(!isset($_GET['new_quiz']) && !isset($_GET['view_quiz']) && !isset($_GET['alter_quiz'])){
echo "No";
}
else {
echo "Yes";
}
which will print Yes if none of new_quiz, view_quiz and alter_quiz are present in the URL. If this is not your desired outcome, please elaborate on your problem.
#paran you need to set a value for view_quiz=yes for example
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
and the url
index.php?new_quiz=yes
index.php?view_quiz=yes
index.php?alter_quiz=yes
All Will return true
isset()allows multiple params. If at least 1 param does not exist (or is NULL), isset() returns false. If all params exist, isset() return true.
So try this:
if( !isset( $_GET['new_quiz'], $_GET['view_quiz'], $_GET['alter_quiz']) ) {
First, to answer your question:
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
This is becaue this
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
checks if either one of your parameter is not set, which will always be the case as long as you are not setting all three parameter simultaneously like this:
index.php?alter_quiz&view_quiz&new_quiz
As #nigel-ren stated, you may wan't to change that logic to
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo 'Yes';
which checks if at least one parameter is set.
If you wan't to check if there is only one of the three parameters set, you would have to work with XOR (which is slightly more complicated)
$a = isset($_GET['new_quiz']);
$b = isset($_GET['view_quiz']);
$c = isset($_GET['alter_quiz']);
if( ($a xor $b xor $c) && !($a && $b && $c) ){
echo 'Yes';
(based on this answer: XOR of three values)
which would return true if one and only one of the three parameters is set.
But - and this is just an assumption, please correct me if I'm wrong - I think what you are trying to achieve are three different pages (one for creating a quiz, one for viewing it and one for editing it). Therefore, you will likely run into a problem with your current setup. For example: What would happen if a user calls the page with multiple parameters, like
index.php?alter_quiz&view_quiz
Would you show both pages? Would you ignore one parameter? I would recommend to work with a single parameter to avoid this problem in the first place. For example site which can take the values alter_quiz, view_quiz or new_quiz. E.g.:
index.php?site=alter_quiz
Then you can work like this:
// check if site is set before getting its value
$site = array_key_exists( 'site', $_GET ) ? $_GET['site'] : NULL;
// if it's not set e.g. index.php without parameters is called
if( is_null($site) ){
// show the start page or something
}else{
$allowed_sites = ['new_quiz', 'view_quiz', 'alter_quiz'];
// never trust user input, check if
// site is an allowed value
if( !in_array($site, $allowed_sites, true) ){
die('404 - This site is no available');
}
// here you can do whatever your site should do
// e.g. include another php script which contains
// your site
include('path/to/your/site-' . $site . '.php');
// or echo yes
echo 'Yes';
}

Identical statement condition

Correct me if I'm wrong. I saw many people write condition header as this format.
if(isset($var) && $var!=""){}
Basically it just checking if $var isn't null value right? In my understanding this would be enough.
if($var){}
Am I missing something? Did my method unreliable? My colleague already pointed out that I should use the first one. Sometime I just lazy to write so I just want to make it simple.
They are not the same thing.
if (expr) is evaluated with these rules -> http://php.net/manual/en/types.comparisons.php#types.comparisons
<?php
$var = "0";
if (isset($var) && $var != "") {
echo "first block\n";
}
if ($var) {
echo "second block\n";
}
Example
Suppose $var is "0", then it is definitely isset, and not equal to an empty string, but fails the if ($var) test.
php
if($var){}
will check if $var is true. In this scenario, if $var is used for first time in condition, notice will be generated that you are trying to use undefined variable.
The isset () function is used to check whether a variable is set or not. If variable is not set, possibly it will enter to the else condition.
In your case if $var is not available, Possibly you will hit by this error Undefined variable: var. So checking isset is always good for your code.
Case 1:
if($var){
echo 'pass';
}else{
echo 'fail';
}
Output:Notice: Undefined variable: var in E:\siva\htdocs\test.php on line 48
fail
Case 2:
if(isset($var)){
echo 'pass';
}else{
echo 'fail';
}
Output : fail
Case 3:
$var = '';
if($var){
echo 'pass';
}else{
echo 'fail';
}
Output :Fail
In this case 3 is more interesting, If you failed to use isset, Defined the variable as null, So you will not get the error

Tricky verification code on a form

I have an implemented control check on a form coded this way:
public function checkCittaResidenza() {
if (is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45 || strlen($this->citta_residenza == 0))) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
}
In this version, it simply checks if it is a string and check its lenght that should be less than 45 chars. It puts the string in an array corretti() if positive, else it initialize an error message specified above in an abstract class parent of the checking class.
What i'd love it to do is:
1) make a check on the string to see if it's not null.
2) if it's not null, do the check (that could be even more particular than the simple one shown here, but i don't have problems on this), put it in corretti() if correct and initializing the error if it's not, as the code now says.
3) if the string is null, the program should skip the check and directly write the null value into the array corretti(), because the form is imagined to be completed in different steps over the time, so it always happen that it's not fully filled.
I'm having problem on coding the if cycle for this last condition, every cycle i tried and imagined puts the empty condition as a cause for initializing an error.
Thank you!
Try this,
public function checkCittaResidenza() {
if(isset($this->citta_residenza)){
if ((is_string($this->citta_residenza) && (strlen($this->citta_residenza) <= 45) || $this->citta_residenza == "")) {
$this->corretti['citta_residenza'] = htmlentities($this->citta_residenza, ENT_QUOTES);
} else {
$this->ErroriTrack('citta_residenza');
}
} else {
$this->corretti['citta_residenza'] = "null";
}
}

Newbie issue. How to check if input is empty in php, although the input could contain digit 0?

I'm new to PHP and usually I use these lines to check if the input is empty:
if(!isset($_SESSION['z']) || strlen(trim($_SESSION['z']) == 0))
{
echo "Unknown";
}
But if the user types digit 0, a script recognises input as empty. How to change these lines to recognise 0 as a string?
Your solution should have worked. As commentator deceze pointed out, your second condition is mistyped it should be strlen(trim($_SESSION['z'])) == 0.
But alternate solution is to use strict equal check === and !==.
if(!isset($arr['z']) || trim($arr['z']) === '')
{
echo "Unknown";
}
This will work with if value is NULL or empty string, resulting 'Unknown'. But any other value would not satisfy the condition, so value 0 or 0.0 should work.
But again, your initial solution is good. Just fix the typo.
if (!isset($_SESSION['z']) || strcmp(trim($_SESSION['z']), '') == 0)
{
echo "Unknown";
}
The function strcmp returns 0, if two strings are the same.
<?php
session_start();
if(isset($_POST["z"])){$_SESSION['z']=$_POST["z"];}
if(!isset($_SESSION['z']) OR $_SESSION['z']==""){
echo "Unknown";
}else{
echo $_SESSION['z'];
}
?>
<form method="post"><input type="text" name="z"><input type="submit"></form>
This should work as you want

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

Categories