instalar postgres 9 en debian | cookies in php | pass dynamic array values in insert query postgresql php
 


 

How to find whether a variable is a (positive) integer with PHP



PHP is_numeric() is useful to find whether a variable is a number or a numeric string. How you can check if a variable is an integer?

You may use the following simple function:

<?php
/**
 * Check if expression is positive integer
 *
 * @param $str
 * @return bool
 */
function is_positive_integer($str) {
	return (is_numeric($str) && $str > 0 && $str == round($str));
}
?>

Example

With this function you can check user input, as following:

<?php

$customer_id = $_GET['customer_id'];

if(!is_positive_integer($customer_id)) {
	echo 'Given value for Customer ID is not acceptable';
	exit;
}
?>

Never trust user input to avoid SQL Injection attacks. You may use Prepared Statements when you insert user data in the database, but the first step is to sanitize user input.

Remarks

Do not confuse this function with PHP is_integer() (alias of is_int()). is_integer() finds whether the type of the given variable is integer, not the variable itself.

Hope to find it helpful. Your comments are welcomed!

Εγγραφή!
Sign-up for our free email newsletter. Get updates when new tutorials and tips are published. You can unsubscribe anytime with a click.

Your comments are welcomed!

This site actively encourages commenting on any post. Comments are not pre-moderated, but this community does not tolerate direct or indirect attacks, name-calling or insults. Please, read terms of use and Comment Policy at privacy policy.

More tips