In my form, a team's score is input, validated by the PHP script and then passed to the MySQL database. However, I want to make sure that a positive integer is being submitted, so there are no problems on the back-end when league standings are tabulated.
Research led me to the conclusion that using is_numeric would be the best way to go about this. However, it fails to recognize zero as an integer and that presents a problem for me. When I echo it in an array by itself, it shows as true, but something about the way I've written it in the script is not working.
I tried converting the $_POST with intval first and then processing the number with is_numeric, but that doesn't seem to help. Here's the code:
// Validate the away score:
if (empty($_POST['away_score'])) {
echo "You forgot to enter the away score.<br>";
$validate = 'false';
} elseif (!is_numeric($_POST['away_score'])) {
echo "You entered an invalid score for the away team.<br>";
$validate = 'false';
} else {
$away_score_value = mysqli_real_escape_string($db, trim($_POST['away_score']));
$validate = 'true';
}
Any thoughts?
The string '0' is not truthy. That means that anything that checks it in a boolean'ish manner will treat it as false. In particular, empty($_POST['away_score']) will evaluate to true, so is_numeric would never even get a chance to fail.
Short version: empty is too wishy-washy in this case. Check for null and '' explicitly.
if (!isset($_POST['away_score']) or $_POST['away_score'] == '') {
You could use built-in validation. Explore few examples from Validation examples. And read about filter_input.
For example.
var_dump(filter_input(INPUT_POST, 'score', FILTER_VALIDATE_INT, array(
'options' => array(
'min_range' => 1,
'max_range' => 5,
)
)));
P.S. use prepared statements.
ctype_digit( (string) $score);
preg_match('#^\d+$#', $score);
In b4 #EmilioGort
boolean false
int 0
<?php
try {
// Check if user submitted "away_score" with valid form.
// "away_score" can be UNDEFINED or STRING or ARRAY.
if (!isset($_POST['away_score']) || !is_string($away_score = $_POST['away_score'])) {
throw new RuntimeException('You cannot access without valid form submitting.');
}
// If "away_score" is not filled in, this will be EMPTY STRING.
if ($away_score === '') {
throw new RuntimeException('You forgot to enter the away score.');
}
// Check if trimmed "away_score" has only digits.
if (!ctype_digit($away_score = trim($away_score))) {
throw new RuntimeException('You entered an invalid score for the away team.');
}
// do something
} catch (Exception $e) {
printf("<p>%s</p>\n", $e->getMessage());
}
Using regex
if (preg_match('/\A\d++\z/', $variable)){//including 0
//do somthing
}else{
echo "This is not a Positive Integer"
}
is_numeric(4.2) return true with float
is_int(2) return false if the data are obtained using supergloblals like $_POST or $_GET
} elseif (!preg_match('/^([0-9]+)$/', $_POST['away_score'], $m)) {
$AwayScore = $m[1]; # $AwayScore to go to mysql
echo 'not numeric!';
$valid = false;
}
This just works!
preg_match() works for any type, including integer/long/float, anything!
But using is_numeric is the proper way of checking whether a given input is or not a number in PHP, and
var_dump(is_numeric(0));
should return bool(true). Have you tried is_int instead?
elseif (!is_numeric(POST[$_'$away_score']) && !is_null(POST[$_'$away_score']))
Because 0 (or null) is not a numeric value, you have to check if the score isn't null.
Related
Hi I am quite new in PHP and I wanna know how can I check what type of variable the user entered
For example if the user entered a string return an error.Or if the user entered an integer redirect him to the next html page.
I think you got what I mean.Please help me :-)
gettype
is_numeric
be aware:
var_dump(gettype('1')); // string
because
'1' !== 1
Take a look at filter_var. It allows you to test your input as you're describing.
Example assuming that you want to validate it's an int value:
<?php
$input = 'some string';
if (filter_var($input, FILTER_VALIDATE_INT) === false) {
// it's not an int value, return error
}
Try this
$type = gettype($input);
if($type == 'integer'){
// redirect
}
else{
echo "error";
}
The gettype() function is used to get the type of a variable. for more info read http://www.w3resource.com/php/function-reference/gettype.php
but i suggest use is_numeric() instead of gettype()
$type = is_numeric($input);
if($type){
// redirect
}
else{
echo "error";
}
because gettype treats variable in single quotes or double quotes as string so for gettype '1' is string not integer
Oh so ok i used the (is_numeric();)function and it worked thanks to all of you !! :DD
Little confused about how to code this. User inputs numbers, then the validation checks to make sure it is numeric and positive. The user can also leave this field blank.
This is what i have so far, it just checks to see that something was inserted.
$error_blue = check_blue($phone);
if($error_blue !=''){
print "<p>Blue: $error_blue";
}
Is where the item is validated at the top of the page.
function check_blue($blue){
if(! is_numeric($blue)){
return'Please Enter a valid number for Blue.';
}}
Is where the function is.
Any help on what to do here would be much appriciated.
Something like this?
function check_blue($blue) {
if (is_numeric($blue) && $blue > -1) {
return 1;
}
else {
return 0;
}
}
if(!check_blue($phone)) {
return'Please Enter a valid number for Blue.';
}
See the demo
Assuming it's an integer you expect,
if ((int)$blue==abs($blue) || empty($blue)) $error = false;
else $error = true;
Then you use $error to decide what to do.
Everyone here was using if else. It is not that this is wrong, but just to show you another idea, which might be useful for other type of validation, take a look at validate filters :
http://www.php.net/manual/en/filter.filters.validate.php
For this purpose you might use FILTER_VALIDATE_INT
You might want to use something simple as
function check_blue($phone) {
return (empty($phone) || (is_numeric($phone) && $phone >= 0));
}
First check if the field is blank, nothing to do if it is.
If it is not blank it will be checked for numericality and to being greater or equal zero.
I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}
I have a form that collects information, one piece of which is a phone number. The phone number data comes from three fields, one for an area code, for the first 3 digits, and for the last four, so that numbers are in this format: xxx-xxx-xxxx (basic U.S. format).
These three fields are not required, but I would like to do some basic error checking if someone decides to fill out any combination of the three field:
(let's say they only give me the area code - that means that they wanted to give me their number, so in essence, it becomes required, so the code should check to see that 1) all three data sets were sent, and 2) all three are only numbers)
Here is what I thought would work, but it does not:
if((isset($_POST['numArea'], $_POST['numFirst'], $_POST['numSecond']) && (!ctype_digit(trim($_POST['numArea'])) || !ctype_digit(trim($_POST['numFirst'])) || !ctype_digit(trim($_POST['numSecond'])) || strlen(trim($_POST['numArea'])) !== 3 || strlen(trim($_POST['numFirst'])) !== 3 || strlen(trim($_POST['numSecond'])) !== 4))
|| (isset($_POST['numArea']) XOR isset($_POST['numFirst']) XOR isset($_POST['numArea']))){
$errors[] = 'Please give us a valid Phone Number, or remove any numbers if you do not wish to use your phone number.';
}else{
$_POST['PhoneNumber'] = '+01'.$_POST['numArea'].'-'.$_POST['numFirst'].'-'.$_POST['numSecond']; }
Any suggestions?
The reason why your code isn't working is not because of your boolean logic, but because of your use of isset(). In the case of a <input type="text">, the $_POST['fieldName'] will always be set, regardless of if the value is empty or not.
Use $_POST['fieldName'] != '' instead to determine if the user has entered a value. DO NOT USE empty(), as this will return any falsy value as empty (0, 000, false, etc...).
Personally, I rather use one <input type="type"> for the phone number. This is less annoying than making the user switch boxes, and also makes validation simpler.
This example actually validates if the number follows NANP rules. I find it absolutely ridiculous that so many applications/websites oversees this validation step.
// Did the user post a number?
if($_POST['phone'] != '') {
// Get only the numbers, we don't care how the user formatted their number
$_POST['phone'] = preg_replace('/[^0-9]/', '', $_POST['phone']);
// Is it a valid NANP phone number?
if(preg_match('/^1?[2-9][0-8][0-9][2-9][0-9]{6}$/i', $_POST['phone']) === 1) {
echo "Valid NANP phone number";
// Trim the leading one
$_POST['phone'] = ltrim($_POST['phone'], '1');
// Format as wanted
$_POST['PhoneNumber'] = '+01'.substr($_POST['phone'],0,3).'-'.substr($_POST['phone'],3,3).'-'.substr($_POST['phone'],6,4);
} else {
echo "Invalid phone number";
}
} else {
echo "User didn't provide phone number";
}
First of all if those fields are inputs then isset() will always return true. What you probably want to check is if they are not empty. So you should use empty() function for that.
I will replace your form values with $a, $b and $c to make it simple.
$a = $_POST['numArea'];
$b = $_POST['numFirst'];
$c = $_POST['numSecond'];
if (!empty($a) || !empty($b) || !empty($b)) {
// we know now that at least field was filled in, lets check their values
$regex = '/^\d+$/';
if (!preg_match($regex, $a) || !preg_match($regex, $b) || !preg_match($regex, $c)) {
echo "Phone number invalid";
}
}
This is just an example. You could shorten it to just one if statement but I haven't done so to make it more readable.
Just check if one of the fields is not set;
if (!isset($_REQUEST['numFirst']) || !isset($_REQUEST['numSecond']) || !isset($_REQUEST['numArea'])) {
if (!isset($_REQUEST['numFirst'])) {
print 'Please fill out the FIrst area';
}
if (!isset($_REQUEST['numSecond'])) {
print 'Please fill out the Second area';
}
if (!isset($_REQUEST['numArea'])) {
print 'Please fill out the Area code';
}
}
Is that the kind of thing you wanted to do?
This is not solution for your problem , but it will solve it other-way , try imask
it's actually a JS script .
Well first off, if anyone is ever gonna be able to maintain your code, you'll have to break that up into method calls. I'd probably write it something like this:
public function phoneNumberWasProvided () {
return !(empty($_POST['numArea']) &&
empty($_POST['numFirst']) &&
empty($_POST['numSecond']));
}
public function phoneNumberIsValid () {
$this->_phoneErrors = array();
// The following three if statements can also be
// extracted into their own methods
if(!preg_match("/^\d{3}/$", $_POST['numArea']) {
$this->_phoneErrors['numArea'] = 'The area code you provided is invalid';
}
if(!preg_match("/^\d{3}/$", $_POST['numFirst']) {
$this->_phoneErrors['numFirst'] = 'The first part of the provided phone
number is invalid';
}
if(!preg_match("/^\d{4}/$",$_POST['numSecond']) {
$this->_phoneErrors['numArea'] = 'The first part of the provided phone
number is invalid';
}
return empty($this->_phoneErrors);
}
Now you can easily use these methods inside your main logic, making it more readable:
if($this->phoneNumberWasProvided()) {
if(!$this->phoneNumberIsValid()) {
$errors = $this->getPhoneNumberErrors();
// Print errors / do whatever is necessary
} else {
$phoneNumber =
"{$_POST['numArea']}-{$_POST['numFirst']}-{$_POST['numSecond']}";
}
}
Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty?
I want to ensure that:
null is considered an empty string
a white space only string is considered empty
that "0" is not considered empty
This is what I've got so far:
$question = trim($_POST['question']);
if ("" === "$question") {
// Handle error here
}
There must be a simpler way of doing this?
// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
return ($str === null || trim($str) === '');
}
Old post but someone might need it as I did ;)
if (strlen($str) == 0){
do what ever
}
replace $str with your variable.
NULL and "" both return 0 when using strlen.
Use PHP's empty() function. The following things are considered to be empty
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
For more details check empty function
I'll humbly accept if I'm wrong, but I tested on my own end and found that the following works for testing both string(0) "" and NULL valued variables:
if ( $question ) {
// Handle success here
}
Which could also be reversed to test for success as such:
if ( !$question ) {
// Handle error here
}
Beware false negatives from the trim() function — it performs a cast-to-string before trimming, and thus will return e.g. "Array" if you pass it an empty array. That may not be an issue, depending on how you process your data, but with the code you supply, a field named question[] could be supplied in the POST data and appear to be a non-empty string. Instead, I would suggest:
$question = $_POST['question'];
if (!is_string || ($question = trim($question))) {
// Handle error here
}
// If $question was a string, it will have been trimmed by this point
There is no better way but since it's an operation you usually do quite often, you'd better automatize the process.
Most frameworks offer a way to make arguments parsing an easy task. You can build you own object for that. Quick and dirty example :
class Request
{
// This is the spirit but you may want to make that cleaner :-)
function get($key, $default=null, $from=null)
{
if ($from) :
if (isset(${'_'.$from}[$key]));
return sanitize(${'_'.strtoupper($from)}[$key]); // didn't test that but it should work
else
if isset($_REQUEST[$key])
return sanitize($_REQUEST[$key]);
return $default;
}
// basics. Enforce it with filters according to your needs
function sanitize($data)
{
return addslashes(trim($data));
}
// your rules here
function isEmptyString($data)
{
return (trim($data) === "" or $data === null);
}
function exists($key) {}
function setFlash($name, $value) {}
[...]
}
$request = new Request();
$question= $request->get('question', '', 'post');
print $request->isEmptyString($question);
Symfony use that kind of sugar massively.
But you are talking about more than that, with your "// Handle error here
". You are mixing 2 jobs : getting the data and processing it. This is not the same at all.
There are other mechanisms you can use to validate data. Again, frameworks can show you best pratices.
Create objects that represent the data of your form, then attach processses and fall back to it. It sounds far more work that hacking a quick PHP script (and it is the first time), but it's reusable, flexible, and much less error prone since form validation with usual PHP tends to quickly become spaguetti code.
This one checks arrays and strings:
function is_set($val) {
if(is_array($val)) return !empty($val);
return strlen(trim($val)) ? true : false;
}
to be more robust (tabulation, return…), I define:
function is_not_empty_string($str) {
if (is_string($str) && trim($str, " \t\n\r\0") !== '')
return true;
else
return false;
}
// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
var_export($value);
if (is_not_empty_string($value))
print(" is a none empty string!\n");
else
print(" is not a string or is an empty string\n");
}
sources:
https://www.php.net/manual/en/function.is-string.php
https://www.php.net/manual/en/function.trim.php
When you want to check if a value is provided for a field, that field may be a string , an array, or undifined. So, the following is enough
function isSet($param)
{
return (is_array($param) && count($param)) || trim($param) !== '';
}
use this :
// check for null or empty
if (empty($var)) {
...
}
else {
...
}
empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:
if (is_object($theObject) && (count(get_object_vars($theObject)) > 0)) {