Tuesday 20 September 2016

Compress and Uncompress Data in PHP

Compress string and data in php. Some long strings has to be compressed in-order to pass the data. Use this below function to compress data in php and to uncompress data in php.

Compress Data :
gzcompress($string);

Uncompress Data :
gzuncompress($compressed_string);

Monday 19 September 2016

PHP Function to List Files From Directory

PHP function to list the files in the given path. List files from a directory with this php functions as link, so that you can open the files in new tabs.

function listFiles($path) {
    if(is_dir($path)) {
          if($handle = opendir($path)) {
              while(($file = readdir($handle)) !== false) {
                  if($file != "." && $file != ".." && $file != "Thumbs.db") {
                      echo '<a target="_blank" href="'.$path.$file.'">'.$file.'</a><br>'."\n";
                  }
              }
              closedir($handle);
          }
    }
}

Sunday 18 September 2016

PHP Validation Function for Maximum String Length

Useful PHP form validation function to validate the length of the string against the maximum allowed string length which in default has a maximum length of 10. Use this validation function to validate the string length of a string.

function validateMaxLength($allowed_length, $allowed_length=10) {
    return (strlen($allowed_length) <= (int)$allowed_length);
}

Saturday 17 September 2016

PHP Function to Validate URLs

Usage of simple URL validation function in php. This simple function helps in validation of URL for correct format, this also validates for mailto links in the content.

function validateURL($url) {
    return (bool)preg_match("^((((https?|ftps?|gopher|telnet|nntp)://)|(mailto:|news:))(%[0-9A-Fa-f]{2}|[-()_.!~*';/?:@&=+$,A-Za-z0-9])+)([).!';/?:,][[:blank:]])?$",$url);
}

Friday 16 September 2016

Check for Script Tags in String using PHP Functions

In order to make hacking attempts fail we need to make our input contents safe and secure. Here to avoid unwanted issue due to script injection we make the content/string safe of script tags. Thus script hacking cannot be done in our contents.

function validateJsScriptSafe($value) {
    return (bool)(!preg_match("/<script[^>]*>[srn]*(<!--)?|(-->)?[srn]*</script>/",$value));
}

Thursday 15 September 2016

PHP Validation Function for HTML Safe

Simple php function to validate html tags in given content. In some cases we need to check if the given string contains html tags in order to avoid hacking attends and also to avoid unwanted elements changing the layout of our site.

function validateHtmlSafe($value) {
    return (bool)(!preg_match("/<(.*)>.*<$1>/", $value));
}

Wednesday 14 September 2016

Submit URL to Search Engines for Indexing

In order to generate organic traffic to our website, we need our site links to be indexed in search engines. For this, we need to make search engines crawl our URLs. This function helps in submitting our URLs and sitemap XML links to major search engines so that our links gets indexed easily. We need to pass the URL as a parameter for the function is all we need to do.


function submitUrl2SearchEngine($site_url) {
    // Eg: $site_url = http://www.demowebsite.com/sitemap.xml
    @file_get_contents("http://www.google.com/webmasters/sitemaps/ping?sitemap=$site_url");
    @file_get_contents("http://www.bing.com/webmaster/ping.aspx?siteMap=$site_url");
    @file_get_contents("http://search.yahooapis.com/SiteExplorerService/V1/updateNotification?appid=YahooDemo&url=$site_url");
    @file_get_contents("http://submissions.ask.com/ping?sitemap=$site_url");  
}

Tuesday 13 September 2016

PHP Function to Validate Hex Color Code

PHP function to validate the given value for valid hex color code. Validate using this simple php function for valid hex color code.

function validateHexColor($color_code) {
    return (bool)preg_match('/^#?+[0-9a-f]{3}(?:[0-9a-f]{3})?$/i', $color_code);
}

Monday 12 September 2016

PHP Random String Generator

Small php snippet to generate a random string. Simple php function to generate random key/salt for encryption in php.

function randomString($length) {
    $allchars = array_merge( range('a','z'), range('A', 'Z'),range(0,9));
    $allchars = implode("", $allchars);
    return substr(str_shuffle($allchars), 0, $length);
}

Sunday 11 September 2016

PHP Function to Validate Alpha Characters

Validate alpha characters using php snippets. This function allows only alphabets either in small letters or in capital letters. Php regex that allows only alpha characters.

function validateAlpha($string) {
    return (bool)preg_match("/^([a-zA-Z])+$/i", $string);
}

Saturday 10 September 2016

Validate MAC Address in PHP

Simple snippet to validate MAC address in php. This functions receives mac address as input and returns a boolean value based on the check. If mac address is not valid function will return false or if valid it will return true.

function validateMacAddress($mac_address)
    return (bool)preg_match('/^([0-9a-fA-F][0-9a-fA-F]:){5}([0-9a-fA-F][0-9a-fA-F])$/', $mac_address);
}

Friday 9 September 2016

PHP Function to Validate String Length

Simple php function to validate the maximum length of a given string. Use this function to test if a given string's length is within the allowed limit. Validate maximum length of a string in php.

function validateMaxlength($string, $max_len) {
    return (strlen($string) <= (int)$max_len);
}



Thursday 8 September 2016

PHP Function to Validate IP Address

Simple php function to validate IP address and check whether it is in private network range. Ip validation in php for easy validating of IPv4 address.

function validateIpAddress($ip) {
    if(strtolower($ip)==='unknown' || $ip=="") return false;
    $ip = ip2long($ip); // get ipv4 network address
    if($ip!==false && $ip!==-1) {
        $ip = sprintf('%u', $ip);
        // check private network range
        if ($ip >= 0 && $ip <= 50331647) return false;
        if ($ip >= 167772160 && $ip <= 184549375) return false;
        if ($ip >= 2130706432 && $ip <= 2147483647) return false;
        if ($ip >= 2851995648 && $ip <= 2852061183) return false;
        if ($ip >= 2886729728 && $ip <= 2887778303) return false;
        if ($ip >;= 3221225984 && $ip <= 3221226239) return false;
        if ($ip >;= 3232235520 && $ip <= 3232301055) return false;
        if ($ip >= 4294967040) return false;
    }
    return true;
}

Wednesday 7 September 2016

Email Address Validation in PHP using Regex

Simple regex to validate email address in php. Validate email address in php regex while submitting form.

$email_regex = "/([a-z0-9_]+|[a-z0-9_]+\.[a-z0-9_]+)@(([a-z0-9]|[a-z0-9]+\.[a-z0-9]+)+\.([a-z]{2,4}))/i";
if(!preg_match($email_regex, $email)) {
    echo "Invalid Email Address";
}
else {
    echo "Valid Email Address";
}

Monday 5 September 2016

Simple Time Ago Display Function in PHP

Make use of this simple function to display time ago format details of the time in your comment system. Facebook style time ago display script in simple php.

function timeAgo($date){
    $time = strtotime($date);
    $now = time();
    $ago = $now - $time;
    if($ago<60) {
        $timeago = round($ago);
        $s = ($timeago == 1)?"second":"seconds";
        return "$timeago $s ago";
    } elseif($ago<3600) {
        $timeago = round($ago / 60);
        $m = ($timeago == 1)?"minute":"minutes";
        return "$timeago $m ago";
    } elseif($ago>=3600 && $ago<86400) {
        $timeago = round($ago / 60 / 60);
        $h = ($timeago == 1)?"hour":"hours";
        return "$timeago $h ago";
    } elseif($ago>=86400 && $ago<2629743.83) {
        $timeago = round($ago / 60 / 60 / 24);
        $d = ($timeago == 1)?"day":"days";
        return "$timeago $d ago";
    } elseif($ago>=2629743.83 && $ago<31556926) {
        $timeago = round($ago / 60 / 60 / 24 / 30.4375);
        $m = ($timeago == 1)?"month":"months";
        return "$timeago $m ago";
    } else {
        $timeago = round($ago / 60 / 60 / 24 / 365);
        $y = ($timeago == 1)?"year":"years";
        return "$timeago $y ago";
    }
}

Sunday 4 September 2016

Simple Header and Meta Redirection in PHP

Refresh/Redirect management to different pages in PHP. Simple function to help in refreshing and redirecting a page in PHP. This function helps in redirection by different ways. Header redirection in PHP is a efficient method. We can use meta redirection to redirect and to refresh a page in PHP.

function redirect($url,$header=false,$time=0) {
    if(!headers_sent() && $header) {
        header( 'refresh:'.$time.'; url='.$url.'');
        exit;
    }
    else {
        echo '<script type="text/javascript">';
        echo 'window.setTimeout(function() {
                window.location.href="'.$url.'";
            }, '.($time*1000).');';
        echo '</script>';
        echo '<noscript>';
        echo '<meta http-equiv="refresh" content="'.$time.';url='.$url.'" />';
        echo '</noscript>';
        exit;
    }
}

Saturday 3 September 2016

Explode a String by Multiple Delimiters in PHP

Explode a string using multiple delimiters in php. multipleExplode function helps in spliting a string by multiple delimiters in php.

function multipleexplode($delimiters,$string) {
    $ready = str_replace($delimiters, $delimiters[0], $string);
    $array = explode($delimiters[0], $ready);
    return  $array;
}

Friday 2 September 2016

File Size Calculator in PHP

Calculate the size of a file from a URL and display the size in respective units. This function takes a file url and calculates the size the file in php.

function calculateFileSize($url){
    $size = filesize($url);
    if($size>=1073741824) {
        $fileSize = round($size/1024/1024/1024,1).'GB';
    } elseif($size>=1048576) {
        $fileSize = round($size/1024/1024,1).'MB';
    } elseif($size>=1024) {
        $fileSize = round($size/1024,1).'KB';
    } else {
        $fileSize = $size.' bytes';
    }
    return $fileSize;
}

Thursday 1 September 2016

Simple Tax Calculator in PHP

Tax Calculator for calculating the tax of a product in php. Make use of this php calculator to calculate tax of any country by passing in product rate and tax percentage.

function taxCalculator($amount,$tax_rate){
    $tax_rate = $tax_rate/100;
    $tax = $amount * $tax_rate;
    return $total = $tax + $amount;
}