Miscellaneous in PHP

This tutorial will show you some validations we require in most of the cases. These are given below one by one.

1. Check if an email address is injected

//validate against any email injection attempts
function is_email_injected($email) {
    $injections = array('(\n+)',
        '(\r+)',
        '(\t+)',
        '(%0A+)',
        '(%0D+)',
        '(%08+)',
        '(%09+)'
    );
    $inject = join('|', $injections);
    $inject = "/$inject/i";
    if (preg_match($inject, $email)) {
        return true;
    } else {
        return false;
    }
}

2. Check if an email address is valid

//tests whether the email address is valid
function is_email_valid($email) {
    $pattern = "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i";
    if (preg_match($pattern, $email)) {
        return true;
    } else {
        return false;
    }
}

3. Check if a decimal number takes upto two decimal places

//validate two decimal places of a number in PHP
function are_two_decimal_places($number) {
    if (preg_match('/^[0-9]+\.[0-9]{2}$/', $number)) {
        return true;
    } else {
        return false;
    }
}

4. Check the value is numeric

// numeric, decimal passes
function is_numeric_val($variable) {
    return is_numeric($variable);
}

5. Check if value is integer

// digits only, no dots
function are_digits($element) {
    if (ctype_digit($element)) {
        return true;
    }
    return false;
}

6. Clean input value

//clean input
function clean($text) {
    $text = strip_tags($text);
    $text = htmlspecialchars($text, ENT_QUOTES);
    return ($text); //output clean text
}

7. Remove HTML from a string value

//remove html tags
function remove_HTML($str) {
    return strip_tags($str);
}

8. Insert new line

//insert new line
function insert_new_line($string) {
 return nl2br($string);
}

9. Remove misinterpreted HTML from a string value

//remove misinterpreted HTML
function entity_quote($string) {
    return htmlentities($string);
}

10. Escape terminating character

//escape character which causes an argument to be terminated
function escape_char($arg) {
    return escapeshellarg($arg);
}

11. Remove slash from the string value

//remove slash
function escape_string($input) {
    return mysql_real_escape_string($input);
}

12. Remove white spaces from both side of the string value

//remove whitespace from both sides from a string
function remove_space($value) {
    return trim($value);
}

13. Remove slashes from the string value

//remove slashes from the string
function remove_slashes($string) {
    return (preg_replace('/\\\\+/i', '', $string));
}

14. Remove all white spaces from the string value

//Remove all white spaces from a string
function remove_all_spaces($string) {
    return preg_replace('/\s+/', '', $string);
}

15. Calculate length of a string

//return string length
function string_length($string) {
    return strlen($string);
}

16. Encrypt a value using md5 algorithm

//md5 encryption
function encrypt($str) {
    return md5($str);
}

17. Validate web URL

// Web address validation
function is_web_address_valid($web) {
    return preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $web);
}

18. Zip or Pin code validation

//Zip code/pin code validation
function is_zip_code_valid($zipcode) {
    return preg_match("/^(\d{5}|\d{6}|)$/", $zipcode);
}

19. Validate name should contain letters

//Name Validation: contains only letters
function is_name_valid($name) {
    if (ctype_alpha($name)) {
        return true;
    }
    return false;
}

20. Retrieve extension from file name

//Get file extension
function file_extension($str) {
    $i = strrpos($str, ".");
    if (!$i) {
        return "";
    }
    $l = stringLength($str) - $i;
    $ext = substr($str, $i + 1, $l);
    return $ext;
}

21. Compare two string case sensitive

//Case sensitive string compare
function str_sensitive_cmp($str1, $str2) {
    if (strcmp($str1, $str2) != 0) {
        return false;
    }
    return true;
}

22. Compare two string case insensitive

//Case insensitive string compare
function str_insensitive_cmp($str1, $str2) {
    if (strcasecmp($str1, $str2) != 0) {
        return false;
    }
    return true;
}

23. Validate GET parameter query string in URL

//validate query string
function validate_query_string($queryString, $min = 1, $max = 32) {
    if (!preg_match("/^([a-zA-Z0-9]{" . $min . "," . $max . "}=[a-zA-Z0-9]{" . $min . "," . $max . "}&?)
        +$/", $queryString)) {
        return false;
    }
    return true;
}

24. Validate alphanumeric with minimum and maximum range

function validate_alphanum($value, $min = 1, $max = 32) {
    if (!preg_match("/^[a-zA-Z0-9]{" . $min . "," . $max . "}
    $/", $value)) {
        return false;
    }
    return true;
}

25. Prevent XXS attacks when user provides input to the form

// Prevents XXS Attacks
function cleanxss($input) {
    $search = array(
        '@<script[^>]*?>.*?</script>@si', // Strip out javascript
        '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
        '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
        '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
    );

    $inputx = preg_replace($search, '', $input);
    $inputx = trim($inputx);
    if (get_magic_quotes_gpc()) {
        $inputx = stripslashes($inputx);
    }
    $inputx = mysql_real_escape_string($inputx);
    return $inputx;
}

That’s all. Thanks for reading.

Soumitra Roy Sarkar

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials Twitter Facebook  Google Plus Linkedin Or Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *