ctype_xdigit to check hexadecimal characters

bool ctype_xdigit ( string $input_string )
$input_string : String to be checked.

ctype_xdigit() is a PHP filter function checks if all chars in the $input_string are hexadecimal or not. Any thing other than this if present then it return FALSE.

Hexadecimal is positional numeral system with base of 16. The chars it used are from 0 to 9 and from A to F.


This is a good function to check data coming from insecure sources like user input data. Before storing or processing such data we can use this function check to match our requirement.

Now let us try with some examples.
$var="10af4j4";
if(ctype_xdigit($var)){
echo " all are hexadecimal chars or digits ";
}else{ 
echo "All or some are not hexadecimal chars ";
}
You can change the value of the variable $var and see the result. Decimal points are not allowed ( False ) in ctype_xdigit.

We can check the form data input by users directly by using ctype_xdigit function. Here is one example.

if(ctype_xdigit($_POST['var'])){
echo " All are hexadecimal chars or digits ";
}else{ 
echo "All or some are not hexadecimal chars or digits";
}

Removing blank space before using

It is better to use string function trim to remove blank space present at starting and ending of the variable before using it. Users some time add blank space and this goes wrongly as not alphanumeric variable. Here is the modified script to remove blank space.
<?Php
$var=$_POST['var'];
$var=trim($var); // remove space at starting and ending of variable. 
if(ctype_xdigit($var)){
echo " all are hexadecimal chars or digits ";
}else{ echo "All or some are not hexadecimal chars or digits";}
echo "<br><br>";// 
if(!ctype_xdigit($var)){
echo " Inside if <br>";
}
?>
For easy understanding here is the form to submit data to above script
<form method=post action='ctype_alnck.php'>
<input type=text name=var>
<input type=submit value=submit>
</form>

DEMO


Here if you want to check only numeric numbers then better to use is_numeric() function.


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer