I would like to determine whether or not a variable has any text at all.
For instance, my current code is this:
if (is_numeric ($id))
{
//do stuff
}
else
{
// do other stuff
}
However, there is a problem if my variable contains both a string and a number
such as "you are 93 years old",
because it sees that number 93 is present and considers the variable numeric.
I want the if statement to only "do stuff" if there is absolutely no text in the variable at all.
Thanks
Try casting the value to int (or float) then compare it back to the unaltered version. They should match values (but not type)
if((int)$id == $id) {
} else {
}
another option would be to use preg_match("/^([\d.\-]+)$/", $id). This would allow you to be very specific about what characters you let $id contain. However using regexp should be considered as the final choice (for performance reasons)
if(empty($var) && $var !== "0" && $var !== 0) {
// it's really empty, not a string "0" and not a numeric 0
}
You could also check if it's not a boolean false for the sake of completeness.
Related
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've moved from HTML to PHP coding, so when I wanted to make a link for my news page I used HREF to take the id for the row as a link and make the title of the piece the viewable/clickable link:
echo "<a href=news.php?id=".$row{'id'};
echo ">";
echo ucwords(strtolower($row{'newstitle'}));
echo "</a>";
So when someone clicks on the title it redirects to the article and the address bar becomes (obviously this is an example):
http://site.com/news.php?id=1
How can I validate that the information after the ? is id=int (it will always be a number) and not some user code or other input that could damage the site? I've looked at ways of Sanitizing/Validating the code, but all the examples I've found have been to do with entering information into forms that are then used in the address rather than simply ensuring the address is valid, hence turning to here for assistance.
Thanks
You should use the filter module:
$id = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($id === false) {
// not an integer
}
Or you can use ctype_digit() to check if a variable is composed only of decimal digits:
if (ctype_digit($_GET['id'])) {
// it's an integer
} else {
// not an integer
}
Or shorter:
ctype_digit($_GET['id']) or die("oops that's not an integer!");
But die or exit would make your code less testable.
is_numeric would work too, but it would return true for any string representation of a number, not only integers.
Try this
<?php
if (is_int($_GET["id"])) {
echo "is integer\n";
} else {
echo "is not an integer\n";
}
?>
If you have excluded 0 as a valid number for your integer id, you can simply do the following:
$id = (int) $_GET['id'];
if (!$id) {
# no number -or- 0 given
} else {
# regardless what have been given, it has been converted at least to some integer.
}
That's by casting. Now $id is always an integer so more safe to use.
However, most often you need to check as well that the number is non-negative:
$id = max(0, $_GET['id']);
The max function does take care of casting $_GET['id'] into an integer. It ensures that the id is 0 or higher in case the provided value was greater than 0. If it was 0 or lower, 0 is the maximum number.
If you then need to actually validate the input more strictly, you can turn it back into a string for comparison reasons:
if ("$id" === $_GET['id'])
{
# Input was done as a string representation of the integer value.
}
How do I write an if condition that will evaluate a zero as not empty? I'm writing a validation script and if the field is blank, I throw an error. In the case of a select with numerical values that start with 0 (zero), that should not considered to be empty. The manual states that a string 0 is considered to be empty and returns false. If I change empty to !isset, the zero works but the other textboxes that are truly empty pass validation. How do I write this to handle my case?
if (strlen($x)) {
// win \o/ (not empty)
}
Happy coding.
(All text box / form input content is inherently just text. Any meaning as a numerical value comes later and each representation can be validated. 0 is coerced back to "0" in strlen.)
Have you considered using is_null()?
if (is_null($value) || $value === "") {}
if (empty($value) && $value !== 0)
if(!is_numeric($var) && empty($var))
{
// empty
}
else
{
// not empty
}
$alerter2="false";
for ( $counter = 0; $counter <= count($filter); $counter++) {
$questionsubmitted=strtolower($_POST[question]);
$currentcheck =$filter[$counter];
$foundvalue=stripos((string)$questionsubmitted,(string)$currentcheck);
echo $foundvalue;
if ($foundvalue==0) {
$alerter2="true";
} else { }
}
if (!($alerter2=="true")) {
$sql="INSERT INTO Persons (Name, Email, Question)
VALUES
('$_POST[name]','$_POST[email]','$_POST[question]')";
} else {
echo "Please only post appropriate questions";
}
For some reason, whenever I run this, stripos returns 0 every time for every iteration. It's supposed to be a filter, and using echo I found that stripos is 0 every time that it appears. However, when I use 0 in the if, it returns true for even those that don't have the word in them.
Where should I use mysql_real_escape_string? After the query? Note, I am making this a piece of code where I want user input to be saved to a database.
stripos return false if the value is not found, or 0 if it is the first character. Problem is, php automatically cast boolean to the 0 integer or the 0 integer to false. So I think a cast is happening here and thus the condition don't do what you want.
You can use === to also check the type of the variable :
if ($foundvalue === 0) {
$alerter2="true";
}
There's more details about this problem in the linked documentation for stripos.
You should also remove the empty else clause for a cleaner code and use mysql_real_escape_string to sanitize the values before putting them in your database.
You need to change
if ($foundvalue==0)
to
if ($foundvalue===0) // three equals signs
or something equivalent, depending on your logic (I didn't quite understand what's going on).
But as everyone says, THIS CODE IS OPEN TO SQL INJECTION ATTACKS (among other problems).
Also,
$questionsubmitted=strtolower($_POST[question]);
should probably be:
$questionsubmitted=strtolower($_POST['question']);
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)) {