Some useful functions for any php application

Some useful functions for any php application

Online by JSC0d3
June 16, 2014 | | 958 recognitions

I posted some useful features for any application built with PHP (Hypertext Preprocessor). The following is a list of PHP functions that anyone will need at any point in his career. I’ve compiled a list of nine incredibly useful PHP functions and features that you should be familiar with.

Date format validation in PHP:

function check_date_format($date){
    //match the format of the date
    if (preg_match ("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/", $date, $parts)){
        //check weather the date is valid of not
        if(checkdate($parts[2],$parts[3],$parts[1])):
            return true;
        else:
            return false;
        endif;
    }
    else {
        return false;
    }
}

or

function check_date_format($date){
        #2009/12/11
        #2009-12-11
        #2009.12.11
        #09.12.11
        return preg_match('#^([0-9]?[0-9]?[0-9]{2}[- /.](0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01]))*$#''/', $date);
}

Get age by birth date

function getAge($birthdate = '0000-00-00') {
    if (!check_date_format($birthdate) || $birthdate == '0000-00-00'):
        return 'Unknown';
    endif;

    $bits = explode('-', $birthdate);
    $age = date('Y') - $bits[0] - 1;

    $arr[1] = 'm';
    $arr[2] = 'd';

    for ($i = 1; $arr[$i]; $i++) {
        $n = date($arr[$i]);
        if ($n < $bits[$i]){
            break;
        }
        if ($n > $bits[$i]) {
            ++$age;
            break;
        }
    }
    return $age;
}

Make data safe

function _clean($str){
    if (is_array($str)):
        return array_map('_clean', $str);
    else:
        $stripslash = get_magic_quotes_gpc() ? stripslashes($str) : $str;
        return str_replace('\\', '\\\\', strip_tags(trim(htmlspecialchars(($stripslash), ENT_QUOTES))));
    endif;
}
//usage call it somewhere in beginning of your script
_clean($_POST);
_clean($_GET);
_clean($_REQUEST);
// and so on..

Data validation

function validate_data($type, $input){
    switch ($type):
        case 'email' :
            return filter_var($input, FILTER_VALIDATE_EMAIL);
        break;
        case 'url' :
            return filter_var($input, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED)
        break;
        case 'ipv4' :
            return filter_var($input, FILTER_VALIDATE_IP);
        break;
        case 'ipv6' :
            return filter_var($input, FILTER_VALIDATE_IP);
        break;
     endswitch;
}

Validate strong password (must contain 8 characters, 1 uppercase, 1 lowercase and 1 number)

function validate_strong_password($password){
    return preg_match('/^(?=^.{8,}$)((?=.*[A-Za-z0-9])(?=.*[A-Z])(?=.*[a-z]))^.*$/', $password);
}

Validate username (alphabet, digit, @, _ and . are allowed. Minimum 6 character and maximum 50 characters)

function validate_username($username){
    return preg_match('/^[a-zA-Z\d_@.]{6,50}$/i', $username);
}

Validate URL exist

function urlexist($url){
    $url = @parse_url($url);

    if (!$url){
        return false;
    }

    $url = array_map('trim', $url);
    $url['port'] = (!isset($url['port'])) ? 80 : (int)$url['port'];
    $path = (isset($url['path'])) ? $url['path'] : '';

    if ($path == ''){
        $path = '/';
    }

    $path .= (isset($url['query'])) ? '?$url[query]' : '';

    if (isset($url['host']) AND $url['host'] != @gethostbyname($url['host'])){
        if (PHP_VERSION >= 5){
            $headers = @get_headers('$url[scheme]://$url[host]:$url[port]$path');
        }
        else{
            $fp = fsockopen($url['host'], $url['port'], $errno, $errstr, 30);
            if (!$fp){
                return false;
            }
            fputs($fp, 'HEAD $path HTTP/1.1\r\nHost: $url[host]\r\n\r\n');
            $headers = fread($fp, 4096);
            fclose($fp);
        }
        $headers = (is_array($headers)) ? implode('\n', $headers) : $headers;
        return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
    }
    return false;
}

Validate alphanumeric characters

function validate_alphanumeric($string){
    return ctype_alnum ($string);
}

Validate value is a number

function is_number($value, $options = []) {
    if (!is_numeric($value)) {
        return false;
    }
    if (isset($options ['max']) && ($value > (int) $options ['max'])) {
        return false;
    }
    if (isset($options ['min']) && ($value < (int) $options ['min'])) {
        return false;
    }
    return true;
}

 

JSC0d3's Logo
About JSC0d3

JSC0d3 is an entrepreneur, online marketer, and an employee of an IT company. When not building websites, creating content, or helping customers improve their online business, spend time with their wife and two beautiful children. Although he still feels new in WordPress, he enjoys sharing what he has learned with all of you! If you want to get in touch with him, you can do this through this website.

On the same idea

Posted by | February 9, 2019

WordPress' wp_link_pages() function, used for displaying page links in multi-page posts, lacks one big feature You can display a list of...

Posted by | December 14, 2018

Preliminary step: Testing whether the code complies with the format of a fiscal identification code (CIF) That is, the maximum length should be 10...

Posted by | November 8, 2017

Nowadays, a lot of bloggers choose to remove HTML tag from WordPress websites However, for beginners and newbies in this field, they may feel...

Previous PostBackNext Post

Leave here an impression