PHP Logical Operators with 4 variables - php

I would like to set the disabled state of a form field based on the combination of 4 variables: processed, process started, process ended, user id
If it is not going to be processed, the form field should be disabled
If the process has started OR ended, it should be also disabled, except if the user id == 1. So User 1 can still fill the form field, even if the process has started OR ended. And it should be also disabled for User 1 also if it is not going to be processed.
I was trying this way, but doesn't work as I expect, so there must be a flaw in my logic or understanding how PHP works:
'disabled' => !$proc || (($proc_started || $proc_ended) && !$user_id == 1)
This way other users see the form field also enabled, which I don't want. Is it the hierarchy of the Logical Operators ?
Can you please point me to the right direction? Thanks.

!$user_id == 1 is (!$user_id) == 1
$foo = 42;
!$foo == false;
You want to write !($user_id == 1) or $user_id != 1

Should work.
if($user_id === 1) {
if($state != "processed") {
$state = "Enabled" // or anything else of your choice
}
} else {
$state = "Disabled";
}

Related

Why aren't my PHP error messages working correctly?

I'm creating a basic form to purchase adult & child tickets from. With the way the form is set up, the user must purchase an adult ticket, but they don't need to purchase a child ticket. I've added some error messages/validations to enforce rules within the form. All of the adult ticket error messages work correctly, but the child ones aren't working right.
I want the child ticket rules to check the following: that a valid number (aka not a letter) has been entered, the quantity is greater than 0, and a whole number has been entered. I thought I had the rules set so they only start validating if the child ticket input is not empty, but instead they're still trying to validate when it is empty, which I don't want it to do considering no child tickets need to be purchased. How do I get this to work correctly?
Here is my PHP code with the error messages.
<?php
$adult=$_POST['adult'];
$child=$_POST['child'];
$date=date('m/d/Y');
function isInteger($input) {
return(ctype_digit(strval($input)));
}
if (empty($adult)) {
$error_message='You must purchase at least 1 Adult ticket!';
}
else if (!is_numeric($adult)) {
$error_message="You must enter a valid number!";
}
else if ($adult <= 0) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!isInteger($adult)) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if (!empty(!is_numeric($child))) {
$error_message="You must enter a valid number!";
}
else if (!empty($child <= 0)) {
$error_message="You must enter a quantity greater than zero!";
}
else if (!empty(!isInteger($child))) {
$error_message="You must enter a whole number for the quantity! (i.e. 1, 2, etc...)";
}
else if ($adult + $child > 5) {
$error_message="Sorry, there is a limit of 5 total tickets per customer!";
}
else {
$error_message='';
}
if($error_message !=""){
include('index.php');
exit();
}
?>
If $child = 1
if(!empty($child <= 0) ) is equivalent to if(!empty(false)) which makes no sense.
Same with (!empty(!is_numeric($child)))
Use if(isset($child) && $child <= 0) {} instead
You can also use $child = isset($_POST['child']) ? $_POST['child'] : 0
Not looking for an accepted answer, just wanted to suggest a more practical approach.
PHP has some very powerful built-in functions for validation. Two you can use are filter_var and filter_input, which can easily validate numeric values as integers, without needing to check each variation of an integer.
Additionally instead of chaining several elseif conditions, I suggest using throw to immediately raise an Exception that needs to be handled, otherwise halting execution at that point. Accompanied within a try/catch block to handle the exception as desired.
Example https://3v4l.org/PJfLv
$adult = filter_var($_POST['adult'] ?? null, FILTER_VALIDATE_INT);
$child = filter_var($_POST['child'] ?? null, FILTER_VALIDATE_INT);
try {
if (false === $adult || false === $child) {
throw new \InvalidArgumentException('You must enter a whole number (1, 2, etc...)');
}
if (0 >= $child || 0 >= $adult) {
throw new \InvalidArgumentException('You must enter a quantity greater than zero!');
}
// at this point child and adult must be >= 1
// ensure total is at least 1 and at most 5
$total_options = ['options' => ['min_range' => 1, 'max_range' => 5]];
$total = filter_var($adult + $child, FILTER_VALIDATE_INT, $total_options);
if (false === $total) {
throw new \InvalidArgumentException('Sorry, there is a limit of 5 total tickets per customer!');
}
// what should happen next...
} catch(\InvalidArgumentException $e) {
$error_message = $e->getMessage();
require __DIR__ . '/index.php';
## always use absolute paths to prevent include_path overrides/overhead
} finally {
// do something else no regardless of success or Exception...
}
For PHP < 7.0 replace
$_POST['child']) ?? null
with
isset($_POST['child']) ? $_POST['child'] : null

IF ELSE in OOP PHP

I am writing an if else statement in OOP;
The conditions are:
1. Get all requests from BSC from 789789 or 987897
2. If RNB is starting 17 and are 15 characters long
3. Those values with cost as 15 send to URL 1
4. Else send to URL 2
If it matches the statement it is sent to a specific URL, if it does not it sent to another URL. I have rewritten the conditional statement below:
if($request->BSC = 789789 or 987897 && $request->RNB = 17 && $request->BRN strlen = 15 && $request->Cost = 11){
send to URL 1
} else{
..Send to URL 2
}
My question is conditional statement correct?
Your question is a little unclear,
I try to fix your if statement just to show you the correct syntax!:
if( ($request->BSC == 789789 || $request->BSC == 987897) && strpos($request->RNB,'7') == 0 && $request->BRN == 15&& $request->Cost == 11){
//send to URL 1
} else{
//send to URL 2
}
This line :
strpos($request->RNB,'7') == 0
Means: RNB should start with 7, for example : 765433 or 789998 or 712342 . ..

WP-Polls set IP limit at 2

I'm using wp-polls and need to limit the number of votes per IP. Although this is usually set at 1 by default, I need to limit the number of votes per IP to 2.
I've been reading documentation, playing with the plugin code, and looking around on google and SO and can't seem to find the proper method.
I've considered using cookies, but these are harder to catch since I could just as well empty my cookies and voilĂ , it's done.
I need a limit because I don't want people to vote endlessly
Looking at the database, I imagine this has something to do with the pollip_ip field (from the (prefix)_pollsip) table, but not being familiar with editing WP Plugins, this is as far I as I got to go.
As a reference, here is some failed code
wp-polls.php, line 1323
// original code
// if($check_voted == 0) {
// proposed by #birgire
if( $check_voted == 0 || ( is_array( $check_voted ) && 2 >= count( $check_voted ) ) ) {
wp-polls.php, line 1323
// original code
// if($check_voted == 0) {
// alternative of code proposed by #birgire
if( ($check_voted == 0) || count($check_voted) <= 2)
I couldn't see any available filters for this, when I skimmed through the plugin source.
I wonder if it would work, if you replace line #1323 of the wp-polls.php file:
if($check_voted == 0) {
with:
if( $check_voted == 0
|| ( is_array( $check_voted ) && 2 >= count( $check_voted ) ) ) {
to limit the number of votes per IP to 2.
Additionally:
Replace line #140 with:
if( !is_array($check_voted) && intval($check_voted) > 0
|| (is_array($check_voted) && sizeof($check_voted) > 1)
|| ($poll_active == 0 && $poll_close == 1)) {
But I don't recommend in general to modify plugin files, since it will be restored in the next plugin update.
Sidenote: The plugin is not using the recommended $wpdb->prepare() when preparing the SQL for $wpdb->query().

Page wont load and server crashes during PHP while loop

I am trying to run a php script that says basically, whilst two cells in my MySQL database are empty (t_trailerarrival and t_endsort), do something.
My code is as follows:
<?php
// Start Session, include authentication and dBConnection script
session_start();
include 'dbcon.php';
include 'sql_actuals.php';
$current_time = date("G");
while($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort'] == NULL) {
echo "Trailer Arrival";
}
The $queryx_row['abc'] are all in the sql_actuals script that is included into this script.
For some reason, every time i run this script - my browser wont load the result (just loads for ever) and then my website at windows azure seems to crash and take a few minutes to restart.
Could someone please advise if there is a massively obvious error with my script? or point me at what the possible issue could be.
Many thanks in advance.
FYI, i have tried adding a line sleep(1); so that it gave the server it runs off a delay before having to run the program again but no luck.
You are never closing the while loop.
while($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort'] == NULL) {
echo "Trailer Arrival";
}
Without modifying the while conditions during a while statement, once you start, you'll never stop. Therefore hanging the script and server.
You are not actually doing anything in your while statement except echoing a line.
Therefore
$query9_row['a_trailerarrival'] == NULL
and
$query10_row['a_endsort'] == NULL
are always true and never changing, and it will never exit the while loop. You need to put exit criteria in the while loop, such as:
$i=0;
while(($query9_row['a_trailerarrival'] == NULL
&& $query10_row['a_endsort'] == NULL )
|| $i==10) {
$i++;
echo "Trailer Arrival";
}
Although, logically speaking, you still need to run the query data.
** Edit **
Based upon your feedback, this doesn't sound like a while loop at all, but rather an if statement you need (with multiple elseif s).
if ($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort'] == NULL){
echo "Trailer Arrival";
} elseif ($query9_row['a_trailerarrival'] == NULL && $query10_row['a_endsort']){
echo "End Sort";
} elseif ($query9_row['a_trailerarrival'] && $query10_row['a_endsort']){
echo "First Van";
}else {
// fourth condition:
// $query9_row['a_trailerarrival'] != NULL && $query10_row['a_endsort'] == NULL
}
I included a fourth condition when $query9_row isn't null, and $query10_row is null.

Why does my localization cookie seem to not want to change?

Why cant I change cookie?
If you chose a language you cant change. You have to empty your cookies if you want to change language. Why is that?
if (isset($_GET['setLang']) && $_GET['setLang'] == 'en'
|| isset($_COOKIE['setLang']) && $_COOKIE['setLang'] == 'en') {
setcookie("setLang", 'en', time()+(3600*12)); //expires in 12 hours
include('language/en/common.php');
}
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'se'
|| isset($_COOKIE['setLang']) && $_COOKIE['setLang'] == 'se') {
setcookie("setLang", 'se', time()+(3600*12)); //expires in 12 hours
include('language/se/common.php');
}
else if (isset($_GET['setLang']) && $_GET['setLang'] == 'fr'
|| isset($_COOKIE['setLang']) && $_COOKIE['setLang'] == 'fr') {
setcookie("setLang", 'fr', time()+(3600*12)); //expires in 12 hours
include('language/fr/common.php');
}
// default language is english
else {
include('language/en/common.php');
}
You certainly can change cookies. You can't change languages using the logic you have there because the way you've written it, an existing setting in $_COOKIE will always override a setting in $_GET (except for en, where $_GET will be checked first, so right now you should be able to switch to en if you started with another language). You need to do all checks against $_GET first, then all checks against $_COOKIE, if you want to be able to change languages.
The logic hurt my brain, too.
$language = $_GET['setLang'] || $_COOKIE['setLang']) || 'en';
setcookie("setLang", $language, time()+(3600*12));
include('language/' . $language . '/common.php');
Should achieve the same effect and fix your cookie issues (untested, though).
setcookie() defines a cookie to be
sent along with the rest of the HTTP
headers. Like other headers, cookies
must be sent before any output from
your script (this is a protocol
restriction). This requires that you
place calls to this function prior to
any output, including and
tags as well as any whitespace.
http://in3.php.net/setcookie

Categories