Written By:
iamabhishek
4 minute read
PHPHowToStringString Function

String Alphanumeric Check in PHP - ctype_alnum()

Posted in Programming   LAST UPDATED: JUNE 24, 2021

We can check if a string is alphanumeric or not in PHP using the ctype_alnum() function. We can also use a regular expression to check if a string is alphanumeric, but using the ctype_alnum() function in PHP makes it super easy because this is an in-built function in PHP.

If you are taking any input from the user, you must validate the user input because you can never trust user input and a user may try to break your application code by inputting some malicious code or script.

So if you want to validate some string in PHP to check if it contains just alphanumeric value or not, you can do it using the PHP ctype_alnum() function.

PHP String Alphanumeric Check

Here is a simple example for checking if a string is alphanumeric or not in PHP.

ctype_alnum($string);    // returns true if value is alphanumeric

We can use the ctype_alnum() function in an if-else condition too, like this:

<?php

if(ctype_alnum($string)){
    echo "Yes, It's an alphanumeric string/text";
}
else{
    echo "No, It's not an alphanumeric string/text";
}

?>

The above code will print different messages on the screen for alphanumeric string and otherwise.

How to Validate if the GET parameter value is Alphanumeric?

An important use case is when you are using any GET parameter from URL to change your webpage.

For example: The example.com/index.php?show=ques shows questions on the webpage, and the URL example.com/index.php?show=ans shows answers on the same webpage.

If you are using the value for any GET parameter like the show parameter in the above example, you should always validate the value for such parameters before using them, because a user can easily change these values in the URL and make your website malfunction.

To check if GET param contains only alphanumeric value, you can use the following code:

<?php

$param = $_GET['show'];

if(ctype_alnum($param)) {
    // valid value
}
else {
    // invalid value
}

?>

Conclusion:

Well, that's it. The ctype_alnum() is a simple function in PHP that can be used to check if a string has an alphanumeric value or not. Using the regular expressions for this is not a good approach now as we have the ctype_alnum() function in PHP for this.


IF YOU LIKE IT, THEN SHARE IT

RELATED POSTS