Check type of user input (PHP) - php

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

Related

StrPos always returns False?

I've been working on a very basic search engine. It basically operates by checking if the word exists. If it does, it returns the link. I know most of you would suggest to create a database from phpMyAdmin but I don't remember the password to make the mySql_Connect command work.
Anyway here is the code:
<?php
session_start();
$searchInput = $_POST['search'];
var_dump($inputPage1);
var_dump($searchİnput);
$inputPage1 = $_SESSION['pOneText'];
$inputPage2 = isset($_SESSION['pTwoText']) ? $_SESSION['pTwoText'] : "";
$inputPage3 = isset($_SESSION['pThreeText']) ? $_SESSION['pThreeText'] : "";
if (strpos($inputPage1, $searchInput)) {
echo "True";
} else {
echo "False";
}
?>
When I search a word, any word from any page, weather it exists or not, it always returns false. Does anyone know why?
From the PHP documentation:
Warning: This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
So the function returns the integer 0 since $searchInput starts at the first character of $inputPage1. Since it is inside an if condition, that expects a boolean, the integer is then converted to one. When converted to boolean, zero is equal to false so instead the else block is executed.
To fix it, you need to use the !== operator (the not equal equivalent of ===):
if (strpos($inputPage1, $searchInput) !== false) {
//...
Try stripos() to match case insensitive
First print all items in $_POST and $_SESSION using
echo "<pre>";
print_r($_POST);
print_r($_SESSION);
and ensure that the search string really exist in the bigger string .
Also make sure that your are using "false" to compare :
i.e
$pos = strpos($biggerString,$seachString);
if($pos !== false)
{
echo "Not found";
}

Validate Integer in Form Input Using is_numeric

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.

PHP: How to get type of variable from an input field

I need answer for this type of question. Please I need to get type of variable from HTML input field and to echo that type of $var.
From this form I need to check what type of data is entered. Is it string or integer, etc.
<form>
<input type="text" name="podatak" value="podatak" />
<input type="Submit" name="Submit">
</form>
Thanks in advance.
All form submimssions are strings to begin with as such. You can however use functions like is_numeric to see if the item is a number and is_array to see if the form element being passed is an array (ie, checkboxes, possibly files and the like).
Based on your comments, I would do something like the following:
function whatTypeAmI($var)
{
if(is_array($var)
{
// Request is likely a checkbox or multiple files.
echo "I am an Array! Yeeehaaa!";
}
else if(is_numeric($var))
{
// I look like a number, or someone
// typed in a number into a text field.
echo "I am a Fluffeh number!";
}
else
{
echo "Goodness, who knows what on earth happened?";
}
}
foreach($_POST as $val)
{
whatTypeAmI($val);
}
It's always a string or an array. If is_array($_POST['value']) returns true; it's an array. In any other case it's a string.
i guess you are trying to find form field type not the data type... like text, submit, button etc... if that is your scenario then i am afraid there is not such function. As far as i know form post will not send any form type information to the server... any way you can do it using associative array. ex: on your php side do some thing like.
<?php
function getType($elementName){
$formType = array('elementName1' => 'elementType1', 'elementName2' => 'elementType2'......);
if(array_key_exists($elementName, $formType))
return $formType[$elementName];
return 'Unknown';
}
foreach($_POST AS $elementName => $elementVal){
echo 'name = '.$elementName.' type = '. getType($elementName).' value ='.$elementVal;
}
You can use var_dump($variable).
you can make use of these functions : is_int , is_array , is_null, is_float , is_double , is_bool, etc.
function gettype_custom($var){
if(is_array($var)){
return 'array';
}elseif(is_numeric($var)){
return 'numeric';
}elseif(is_string($var)){
return 'string';
}else{
return 'unknown';
}
}

PHP: is_int return wrong result

I am posting numeric value by a form and in php file use var_dump(is_int($my_var)); but it return bool(false) though i am posting 1 and if I use var_dump(is_int(1)); it is fine and return bool(true)
what is wrong....?
Variables transmitted by a POST request are strings, so you're calling is_int() on a string which returns false.
You may use is_numeric() or filter_var() instead or simply cast your variable to an integer.
// First check if it's a numeric value as either a string or number
if(is_numeric($int) === TRUE){
// It's a number, but it has to be an integer
if((int)$int == $int){
return TRUE;
// It's a number, but not an integer, so we fail
}else{
return FALSE;
}
// Not a number
}else{
return FALSE;
}
Also, instead of getting the variable as
$my_var = $_POST["value"];
try this instead to see if the value is really passed.
$my_var = $_REQUEST["value"];

is_int() cannot check $_GET in PHP?

Here is my code:
<?php
$id = $_GET["id"];
if (is_int($id) === FALSE) {
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
?>
It always enters inside the if.
is_int checks that the data type is an integer, but everything in $_GET will be a string. Therefore, it will always return false.
In a pinch, you could cast to an integer and then check for != 0.
$id = isset($_GET['id']) ? (int) $_GET['id'] : null;
if (!$id) { // === 0 || === null
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
But a more robust solution would involve some type of input string validation / filtering, like PHP's built-in filter_input_array().
(Edited post on Oct/13 since it is still receiving upvotes and it was somewhat confusingly worded.)
User input in $_GET array (as well as the other superglobals) all take the form of strings.
is_int checks the type (i.e. string) of the value, not whether it contains integer-like values. For verification that the input is an integer string, I would suggest either something like ctype_digit or an integer filter (FILTER_VALIDATE_INT—this has the benefit of actually changing the value to type integer). Of course you could also typecast it with (int).
From the PHP documentation for is_int:
Note: To test if a variable is a
number or a numeric string (such as
form input, which is always a string),
you must use is_numeric().
Any user input comes in as a string, because PHP has no way to tell what data type you expect the data to be.
Cast it to an integer or use a regex if you want to make sure it's an integer.
<?php
$id = $_GET["id"];
if ((int) $id == 0) {
header('HTTP/1.1 404 Not Found');
exit('404, page not found');
}
?>
Try using is_numeric instead of is_int. is_numeric checks to see if it is given something that can be a number ($_GET returns strings I think). is_int checks to see if the variable is of type int
Use is_numeric() to evaluate the content and is_int() to evaluate the type.
Or, you could just use a regex match to check if the string is an integer.
if(preg_match('/^\d+$/',$_GET['id'])) {
// is an integer
}

Categories