Checking PHP Strlen of multiple strings - php

I have 4 fields from a previous page using an html form in the post method. Everything works fine except I am trying to check to make sure the strlens of each field are below 200. The following code always says that they are too long even though I am making sure they are way below 200.
PHP:
$hsname = trim($_POST['hsname']);
$hsstate = trim($_POST['hsstate']);
$hsemail = trim($_POST['hsemail']);
$hspassword = trim($_POST['hspassword']);
if (strlen($hsname) || strlen($hsstate) || strlen($hsemail) || strlen($hspassword) > 200){
die("Each field can only contain 200 characters"); //this is always returned even though the fields are below 200.
}
else {
echo "fields have good characters";
}

I will translate Your if condition:
if (strlen($hsname) || strlen($hsstate) || strlen($hsemail) || strlen($hspassword) > 200)
It`s like:
if(strlen($hasname)!='' || strlen($hsstate)!='' || strlen($hsemail)!='' || strlen($hspassword) > 200)
So You should know why it`s wrong now ;)
Compare every strlen or try that:
$maximumValue = max(strlen($hsname), strlen($hsstate), strlen($hsemail), strlen($hspassword));
// You got maximum value now, so:
if($maximumValue > 200){}

The reason your condition always returns true is because you're only checking if the last string has a length of greater than 200. The other strings are checked for whether they have a length of greater than 0, so your condition reads "if any of the first 4 strings are greater than 0 or the last string is greater than 200". Try this instead
foreach(array($hsname,$hsstate,$hsemail,$hspassword) as $string) {
if(strlen($string) > 200) {
die("Each field can only contain 200 characters");
}
}

You need to check that the fields are indeed there, and then check their length.
One way of doing it:
$fields = array('hsname', 'hsstate', 'hsemail', 'hspassword');
foreach ($fields as $field) {
if (!array_key_exists($field, $_POST)) {
die("Field {$field} is missing");
}
// Declare a variable whose name is in $field.
${$field} = trim($_POST[$field]);
if (strlen(${$field}) > 200) {
die("Field {$field} must be less or equal to 200 characters");
}
}
If you have international character support, you may also want to verify effective string length against database field length; a single UTF8 "character" may be more than one database field "character". The mb_* functions may help you, as well as utf8 encoding and decoding functions.

That wont work, when you evaluate
strlen($hsname)
It will satisfy the if condition when it has more than 0 characters
This is the same for the first 3 strings you check against
You need the ' > 200 ' for each of the strings you want to compare [assuming that you are passing the actual values in the post]:
$hsname = 'test';
$hsstate = 'test';
$hsemail = 'test';
$hspassword = 'test';
if (strlen($hsname) > 200 || strlen($hsstate) > 200 || strlen($hsemail) > 200 || strlen($hspassword) > 200){
die("Each field can only contain 200 characters"); //this is always returned even though the fields are below 200.
} else {
echo "fields have good characters";
}

Related

PHP Logical Operators with 4 variables

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";
}

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 . ..

How to check if a text box is not empty and the value is less than 500

I have a textbox that is an optional field for users to enter a number in to. If there is a number in there, I want to check to make sure it is less than 500 and then do something with it.
Here is what I am currently doing:
if($textbox!="" && <=500)
{
//action here
}
I tried replacing && with andif but still get an error Parse error: syntax error, unexpected T_IS_SMALLER_OR_EQUAL
What's the easiest way to do this?
You need to use the variable in both statements
preg_match('/\d/', $textbox ) == 1 will make sure it's an int
if($textbox!="" && $textbox <= 500 && preg_match('/\d/', $textbox ) == 1)
{
//action here
}
you are missing the left part of the lesser than
if($textbox!="" && $textbox <=500)
{
//action here
}

in php i need one line if condition for time compare

i have to value
$mo=strtotime($input_array['MondayOpen']);
$mc=strtotime($input_array['MondayClose']);
now i need a if condition to display an error on below conditions
if one of them($mo or $mc) are empty, null or blank.
if close time($mc) is less than open time($mo)
means if both are empty(null) or $mc>$mo then go further
please suggest optimized one line if condition for this
i know it seems very basic question, but i m facing problem when both are null
either i was using simple
if(($mo==NULL && $mc!=NULL) || ( $mo>=$mc && ($mo!=NULL && $mc!=NULL)) )
Keep in mind that 0, null, and blank all mean completely different things here. As indicated previously, strtotime will never return NULL. However, 0 is a valid unix timestamp, whereas false means that the strtotime function was unable to process the value provided.
Also, you've requested that a single-line solution; however, in my opinion, it is much better in this case to write out each condition and display a different error message for each condition. That way, the user knows what actually went wrong. Perhaps this is a better way:
// Only check for errors if we have at least one value set
if (!empty($input['MondayOpen']) || !empty($input['MondayClosed']) {
$mo = strtotime($input['MondayOpen']);
$mc = strtotime($input['MondayClosed']);
$invalid = false;
if (false === $mo) {
echo "Invalid Opening Time\n";
$invalid = true;
}
if (false === $mc) {
echo "Invalid Closing Time\n";
$invalid = true;
}
if (!$invalid && $mc <= $mo) {
echo "Closing time must be After Opening Time\n";
$invalid = true;
}
if ($invalid) {
exit(); // Or handle errors more gracefully
}
}
// Do something useful
All right. How about this.
It checks whether $mo and $mc are valid dates using is_numeric. Any NULL or false values will be caught by that.
I haven't tested it but it should work.
I spread it into a huge block of code. In the beginning, when learning the language, this is the best way to make sense out of the code. It is not the most elegant, nor by far the shortest solution. Later, you can shorten it by removing whitespace, or by introducing or and stuff.
I'm not 100% sure about the number comparison part, and I don't have the time to check it right now. You'll have to try out whether it works.
You need to decide how you want to handle errors and insert the code to where my comments are. A simple echo might already do.
// If $mo or $mc are false, show error.
// Else, proceed to checking whether $mo is larger
// than $mc.
if ((!is_numeric($mo)) and (is_numeric($mc)))
{
// Error: $mo is either NULL, or false, or something else, but not a number.
// While $mc IS a number.
}
elseif ((!is_numeric($mc)) and (is_numeric($mo)))
{
// Error: $mc is either NULL, or false, or something else, but not a number.
// While $mo IS a number.
}
else
{
if (($mc <= $mo) and ((is_numeric($mc) or (is_numeric($mo)))))
{
// Error: closing time is before opening time.
}
else
{
// Success!!
}
}
in php, strotime will return a integer or false. Checking for null in this case will never bear fruit, but otherwise...
if((!$mo xor !$mc) || ($mc && $mc<=$mo)){
print('error');
}else{
print('no_error');
}
oops, edited for correctness. I transposed $mc and $mo. XOR should be correct though.
You can try:
print ((empty($mo) && empty($mc)) || ($mc > $mo)) ? 'case_true_message' : 'case_false_message';
But you should also check the manual :) - for basic control structures

Categories