can this this strlen argument be used for validation? - php

I am new to PHP. My problem is I need the input to validate to a minimum 20 character input and return the last nine. Can anybody tell me if my argument is close to working and if not what do I need to do?
if (!empty($_POST['usen']) ||
strlen($usen['usen'] >= 20 )) {
$switch = substr($usen, -9, 9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}

You have several syntax problems and variable-naming problems. Your code should be:
if (!empty($_POST['usen']) && // || should be &&; the || doesn't make sense here
strlen($_POST['usen']) >= 20 ) { // You had $usen['usen'] and an incorrectly placed )
$switch = substr($_POST['usen'], -9); // again, this should be $_POST['usen'], not $usen. The third parameter is unnecessary here.
$output_form = false;
} else {
$error_text .= "<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form = true;
}
The key points:
You're using the wrong boolean operator. !empty($x) || strlen($x) >= 20 doesn't make sense. It should be &&, not ||. If you have a non-empty value for $_POST['usen'], then !empty($_POST['usen']) is true. But because you had a || in your if conditional, this meant the if block always executed for non-empty values, never the else block. You only want the if to execute if the value is non-empty and at least 20 characters.
Your variable is $_POST['usen'], but your code referred to $usen['usen'] and $usen, which are incorrect.
You had strlen($usen['usen'] >= 20) where you should have strlen($_POST['usen']) >= 20. Both the variable name and the ) placement were incorrect.

To get the last 9 characters of $usen['usen'] use
$switch = substr($usen, -9);

if (!empty($_POST['usen']) ||
strlen($_POST['usen']) >= 20 ) { // changed condition
$switch = substr($usen, -9, 9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
The if-condition has two issues in second part
You use $usen['usen'] but i think it schould be $_POST['usen'] (see also comment by #Ed Cottrell)
The closing bracker from method-call strlen has to be after the param

if (!empty($_POST['usen']) &&
strlen($_POST['usen'] )>= 20 ) { //condition change
$switch = substr($_POST['usen'] ,-9); // returns last nine of sentence
$output_form=false;
} else {
$error_text .="<p><span class='error'>*<strong>A Sentence of 20 char is required .</strong></span></p>";
$output_form=true;
}
To get last 9 charcters , you can use substr(string, -9);

Related

Regex function not giving expected result

I'm trying to validate the username according to the following rule:
No space at beginning or end, at least 2 characters, must not have the following characters: \ " ' % ; ( )
The expression that I've written in PHP is :
if (preg_match('#[<>"\'%;()&\\\\]|\\.\\./#', $this->username) || StringHelper::strlen($this->username) < 2
|| $filterInput->clean($this->username, 'TRIM') !== $this->username || StringHelper::strlen($this->username) > 150)
{
return false; //false will display an error message
}
But on trying the following usernames :
userName<test : accepted as userName.
userName<>test: accepted as userNametest
userName>test :not accepted
So it should be matching on the < and > characters and they should be in the error message
But other parts of the validation are breaking that I think. Please let me know what is wrong in the regex expression.
Try this expression
^ +|[ )"'%;()]$
reg
Or this one:
$test=array("test>string"," test<string","abc;def","a(bc)d");
foreach($test as $t)
echo "$t: ".preg_match("/^[^\\\"'%;()]+$/",trim($t))."\n";
result:
test>string: 1
test<string: 1
abc;def: 0
a(bc)d: 0
Instead of testing for spaces at the beginning and the end I would simply trim them away!
wouldn't it be better with a
function isValidUsername(string $name, string &$failReason=null): bool {
if($name!==ltrim($name)){
$failReason = "username cannot start with spaces";
return false;
}
if($name!==rtrim($name)){
$failReason = "username cannot end with spaces";
return false;
}
$len = strlen($name);
if($len < 2){
$failReason = "username must be minimum 2 characters long";
return false;
}
if($len !== ($illegalPos = strcspn($name , '\\"\'%;()'))){
$failReason = "illegal character on position {$illegalPos}";
return false;
}
$failReason = "";
return true;
}
then you could also explain exactly what is wrong with the username... btw are you really intending to allow NULL bytes in your username? eg "a\x00b" is a valid username? i'd add \x00 to illegal characters and also do a if(!mb_check_encoding($name,'UTF-8')){$failReason="username must be UTF-8";return false;}
check out this article, it will direct and enlighten you on how to use regex
https://support.kobotoolbox.org/restrict_responses.html

Too many Ifs to check variable really contains a valid, 4 digit year

The following if statement works but it's ugly and I have a feeling the same could be achieved with a preg_match REGEX. How?
Basically I don't know how to limit the amount of digits to 4 in regex yet. And once the 4 numerical digit criteria is met, I would like to limit the return of true to between 2019 and 2025.
Sample regex:
/* digits only, no dots */
function is_digits($element) {
return !preg_match ("/[^0-9]/", $element);
}
Sample PHP
// SET $TARGET_YEAR TO current year in [yyyy] format.
// Is set, Is not empty, Is numeric, Is 4 digits long?
if(isset($_GET["year"]) && !empty($_GET["year"]) && is_numeric($_GET["year"]) && strlen($_GET["year"]) == 4) {
// WE HAVE A REAL YEAR.
// SET $TARGET_YEAR TO target year in [yyyy] format.
self::$TARGET_YEAR = $_GET["year"];
} else {
// WE DON'T HAVE A REAL YEAR.
// SET $TARGET_YEAR TO current year in [yyyy] format.
self::$TARGET_YEAR = date('Y');
}
Regular expressions are unnecessary for such a simple check. Your existing code could be reduced to this:
$year = (int)$_GET["year"] ?? 0;
if ($year >= 2019 && $year <= 2025) {
// do stuff
}
Just cast the string as an integer and then check the range. If the string is not a valid number the cast will turn it to 0. If the value isn't set, the null coalesce will also turn it to zero.
This should do the trick. When you put in curly braces number 4 it will allow only 4 numbers if you use 0,4 it will allow 0 to 4 digits.
/* digits only, no dots */
function is_digits($element) {
$element = preg_match ("/^[0-9]{4}$/", $element);
if($element > 2019 && $element < 2025) {
return true; //Or $element
} else {
return false; //Or something else you want
}
}
You can use a built-in validate filter:
$opts = ['options' => ['min_range' => 2019, 'max_range' => 2025]];
if($date = filter_input(INPUT_GET, 'year', FILTER_VALIDATE_INT, $opts)) {
//yes
}

Add multiple condition in if statement [duplicate]

This question already has answers here:
Checking string length with strlen
(3 answers)
Closed 9 years ago.
I want to add 2 numbers in the strlen command. here is my php code:
$name = mysql_real_escape_string($_POST['dgt']);
if(strlen($name) != "32") {
print "This is not a name.";
} else {
It checks if the length is 32. I want it to check if the length is 32 OR 40. how can I do that?
First of all, don't use mysql_real_escape_string(); the old mysql_ API is deprecated, so consider switching to PDO or mysqli instead.
Second, you should consider using input filtering; $_POST['dgt'] may not exist at all, so use filter_input().
Third, you should use numeric values to compare against the output of strlen(); although PHP will treat "32" as a number, it's better to be explicit.
Lastly, if a name must be either 32 or 40 long, you can simply add the condition:
$name = filter_input(INPUT_POST, 'dgt', FILTER_UNSAFE_RAW);
if (empty($name) || (strlen($name) != 32 && strlen($name) != 40)) {
print "This is not a name.";
}
Alternatively, use in_array():
if (empty($name) || !in_array(strlen($name), array(32, 40))) {
print "This is not a name.";
}
Use the and operator "&&" in your conditional, like the code below.
if(strlen($name) != 32 && strlen($name) != 40)
If you would like it to check if name is length 32 or 40 then use the or operator "||" like the code below.
if(strlen($name) == 32 || strlen($name) == 40)
user2910265 has a good point, assign the return value of strlen() to a variable so that only one call is made, like so.
$length = strlen($name);
if(!($length == 32 || $length == 40))
print "this is not a name.";
} else {
From the PHP: Logical Operators - Manual, you want to use either
or
|| (this form has higher precedence)
$a or $b Or TRUE if either $a or $b is TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
So, you could use something like this
$len = strlen($name); // just get the length once and then
// use it to compare however many times....
if (!($len == 32 or $len == 40))

greater or = to a post value

Hi all i have a post value which i am checking to see if its been posted it has atleast 4 numbers (digits) this works perfect.
if (isset($_POST['year']) &&
!preg_match('/([0-9]{4})/i', stripslashes(trim($_POST['year']))) ) {
now i want to check that the value is greater or = to a vairable and not sure how to achive what i need
i tried the below with no luck
$yearOff = date("Y")-150;
echo $yearOff;
if (isset($_POST['year']) &&
!preg_match('/([0-9]{4})/i', stripslashes(trim($_POST['year'])))
&& $_POST['year'] > $yearOff ) {
$ageerrors[] = '<span class="error">
You forgot enter your birth YEAR</span>';
}
Rather than an && you need an || OR condition to switch between the three possible invalid states (empty, not 4+ digits, or <= $yearOff:
if (!isset($_POST['year'])
// Lose the stripslashes()...
|| !preg_match('/([0-9]{4})/i',trim($_POST['year']))
|| $_POST['year'] > $yearOff
) {
// Invalid...
}
Note: It isn't clear from your description whether you want the value to be >= $yearOff or you want it to be < $yearOff. In other words, the code above is testing for the invalid state. Use whichever operator is appropriate for the invalid state.
Note 2: To test for at least 4 consecutive digits in the regex, a better pattern is something like:
/\d{4,}/
// If it must be *only* digits and no other characters, anchor with ^$
/^\d{4,}$/
There's no need for the overhead of a () capture group.
$yearOff = date("Y")-150;
echo $yearOff;
$input = #$_POST['year'];
if (!$input || strlen($input) !== 4 || $input < $yearoff) {
### MEEEP, ERROR ###
}
Explanation:
Input is set (not null which would be false), then it must have a string-length of four and finally it's numerical value must be higher or equal $yearOff.
I assigned the value of the input to it's own variable as well, because you only need to take it once out of $_POST.
As all these conditions are negated, I used the or || operator. Naturally the same can be expressed non-negated and with and:
if ($input && strlen($input) === 4 && $input >= $yearoff) {
### THIS IS CALL OKAY ###
}
To better debug this, the next step is to assign the validity to a variable as well:
$inputValid = $input && strlen($input) === 4 && $input >= $yearoff;
if (false === $inputValid) [
### MEEP, ERROR ####
}
Hope this is helpful.

php if-else failing

What is wrong with this if-else statement.
if((strlen($objectData['pss'] >= 8))AND(strlen($objectData['pss'] <= 20)))
{
//do my bidding
}
else
{
echo "String to short or to long";
}
Ultimately I am trying to find if the variable is greater than or equal to 8 chars while being under or equal to 20 chars. My test string is 11 char, and I am seeing string to short/to long. I've done similar to this in the past, so I dunno what I mucked up at the moment (maybe Im just to tired to realize it)
if (strlen($objectData['pss']) >= 8 && strlen($objectData['pss']) <= 20)
if ((strlen($objectData['pss']) >= 8) and (strlen($objectData['pss']) <= 20))
{
//do my bidding
}
else
{
echo "String to short or to long";
}
I have corrected you brackets
Yes you are indeed "to tired".. You are basically counting the length of an expression instead of the string itself:
if((strlen($objectData['pss']) >= 8)AND(strlen($objectData['pss']) <= 20))

Categories