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;
}

Wednesday 31 August 2016

Generate an Authentication Code in PHP

In some email activation and verification processes we would need to make authentication codes for those verifications. This PHP function helps in generating such authentication codes for verification purpose. Make use of this code snippet for generating authentication codes.

function generateAuthenticationCode($length) {
    $ac = "abcdefghijklmnopqrstuvwxyz0123456789";
    $ac_len = strlen($ac);
    for($i=0; $i<$length; $i++){
        $position = rand(0,$ac_len);
        $authenticationCode .= $ac{$position};
    }
    return $authenticationCode;
}

Tuesday 30 August 2016

Random Password Generator in PHP

Generate random passwords using this simple PHP function. This function takes length as input and generates a random password or random string for usage. This function can be customized as needed for length and allowed characters. For customization please contact us.

function radomPasswordGenerator($length) {
    $ac = "abcdefghijklmnopqrstuvwxyz0123456789";
    $ac_len = strlen($ac);
    for($i=0; $i<$length; $i++){
        $position = rand(0,$ac_len);
        $randomString .= $ac{$position};
    }
    return $randomString;
}

Monday 29 August 2016

Random Color Generator - Hex Color Code in PHP

Generate random hex color code using this simple random color generator. Creator dynamic background colors using this random color generator in php.

function randomColorGenerator() {
    $colorCode = '#';
    for($i=0; $i<6; $i++) {
        $randValue = rand(0 , 15);
        switch ($randValue) {
            case 10: $randValue = 'A'; break;
            case 11: $randValue = 'B'; break;
            case 12: $randValue = 'C'; break;
            case 13: $randValue = 'D'; break;
            case 14: $randValue = 'E'; break;
            case 15: $randValue = 'F'; break;
        }
        $colorCode .= $randValue;
    }
    return $colorCode;
}

Sunday 28 August 2016

Convert One Timezone to Another Timezone in PHP

Sometimes we need to convert time from one timezone to another timezone for some challenging scenarios. Change from one timezone to another timezone in PHP.

$date = new DateTime("2012-07-05 16:43:21", new DateTimeZone('Asia/Kolkata'));
date_default_timezone_set('America/New_York');
echo date("Y-m-d h:iA", $date->format('U'));

Friday 26 August 2016

Count Words in a String in PHP

In Some cases we need to calculate or count the number of words in a sentence or a long string.
This simple function takes a string as parameter and counts the number of words in the string based on the space in the string.

function countWords($string) {
   $word_array = explode(" ", $string);
   return count($word_array);
}

Thursday 25 August 2016

Text to Link in PHP Functions

Convert URL in content/text to link using this simple PHP function. This PHP function takes a string and converts the URLs in the string to links. This simple function may help in making your simple content into links and referrals to your site.

function url2link($url,$target=0) {
            if($url!="") {
                echo '<a href="'.$url.'"';
                if($target) echo ' target="_blank" ';
                echo '>'.$url.'</a>';
            }
            else echo '<a href="#" onclick="alert(\"No Link Here\")">No Link</a>';
        }

Sunday 14 August 2016

PHP Function to Decode UTF8 Characters to Normal Letters

Simple php function to decode utf8 coded strings. We would have come across situations where we need to replace utf8 characters to latin characters. Below function would be a better replacement for iconv and utf8_decode functions which are available in php by default, but results may vary based on character set that has been set in the system.

function decode_utf8_string($mystring) {
        $accented = array(
            'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ă', 'Ą',
            'Ç', 'Ć', 'Č', 'Œ',
            'Ď', 'Đ',
            'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ă', 'ą',
            'ç', 'ć', 'č', 'œ',
            'ď', 'đ',
            'È', 'É', 'Ê', 'Ë', 'Ę', 'Ě',
            'Ğ',
            'Ì', 'Í', 'Î', 'Ï', 'İ',
            'Ĺ', 'Ľ', 'Ł',
            'è', 'é', 'ê', 'ë', 'ę', 'ě',
            'ğ',
            'ì', 'í', 'î', 'ï', 'ı',
            'ĺ', 'ľ', 'ł',
            'Ñ', 'Ń', 'Ň',
            'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ő',
            'Ŕ', 'Ř',
            'Ś', 'Ş', 'Š',
            'ñ', 'ń', 'ň',
            'ò', 'ó', 'ô', 'ö', 'ø', 'ő',
            'ŕ', 'ř',
            'ś', 'ş', 'š',
            'Ţ', 'Ť',
            'Ù', 'Ú', 'Û', 'Ų', 'Ü', 'Ů', 'Ű',
            'Ý', 'ß',
            'Ź', 'Ż', 'Ž',
            'ţ', 'ť',
            'ù', 'ú', 'û', 'ų', 'ü', 'ů', 'ű',
            'ý', 'ÿ',
            'ź', 'ż', 'ž',
            'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р',
            'а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'р',
            'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я',
            'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я'
            );
           
        $replace = array(
            'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'A', 'A',
            'C', 'C', 'C', 'CE',
            'D', 'D',
            'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'a', 'a',
            'c', 'c', 'c', 'ce',
            'd', 'd',
            'E', 'E', 'E', 'E', 'E', 'E',
            'G',
            'I', 'I', 'I', 'I', 'I',
            'L', 'L', 'L',
            'e', 'e', 'e', 'e', 'e', 'e',
            'g',
            'i', 'i', 'i', 'i', 'i',
            'l', 'l', 'l',
            'N', 'N', 'N',
            'O', 'O', 'O', 'O', 'O', 'O', 'O',
            'R', 'R',
            'S', 'S', 'S',
            'n', 'n', 'n',
            'o', 'o', 'o', 'o', 'o', 'o',
            'r', 'r',
            's', 's', 's',
            'T', 'T',
            'U', 'U', 'U', 'U', 'U', 'U', 'U',
            'Y', 'Y',
            'Z', 'Z', 'Z',
            't', 't',
            'u', 'u', 'u', 'u', 'u', 'u', 'u',
            'y', 'y',
            'z', 'z', 'z',
            'A', 'B', 'B', 'r', 'A', 'E', 'E', 'X', '3', 'N', 'N', 'K', 'N', 'M', 'H', 'O', 'N', 'P',
            'a', 'b', 'b', 'r', 'a', 'e', 'e', 'x', '3', 'n', 'n', 'k', 'n', 'm', 'h', 'o', 'p',
            'C', 'T', 'Y', 'O', 'X', 'U', 'u', 'W', 'W', 'b', 'b', 'b', 'E', 'O', 'R',
            'c', 't', 'y', 'o', 'x', 'u', 'u', 'w', 'w', 'b', 'b', 'b', 'e', 'o', 'r'
            );
           
        return str_replace($accented, $replace, $mystring);
    }

Saturday 13 August 2016

PHP Function to get Domain Name from URL

Use this php function to get domain name form a URL. A simple function which takes a valid url and returns you a domain name.

function getDomainName($sourceurl) {
    if(filter_var($sourceurl, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED)===FALSE) {
        return false;
    }
    $url_parts = parse_url($sourceurl);
    return $url_parts['scheme'].'://'.$url_parts['host'];
}

Friday 12 August 2016

PHP Function to Check Prime Number

Check if a given number is a prime number or not using this simple PHP script.
Make use of this simple php function to find whether the number is a prime number or not.

function checkPrimeNumber($number) {
    $string = str_repeat("1", $number);
    if(preg_match( '/^1?$|^(11+?)\1+$/', $string )==0) {
        return true;
    }
    return false;
}

Thursday 11 August 2016

Validate Age for User Registration in PHP

Validate date of birth (DOB) for minimum age limit in php function. This simple php scripts in validating age limit for a registration in sites for legal reasons where users with greater age only allowed to register.

function validateMinimumAgeLimit( $dob, $min_age=18 ) {
    $dob     = new DateTime( $dob );
    $min_age = new DateTime( 'now - ' . $min_age . 'years' );
    return $dob <= $min_age;
}

Wednesday 10 August 2016

Check CSV File is in Valid Format in PHP

Function to check whether a file is a valid CSV file. This function basically checks file for the allowed csv meme types rather checking for the content of the csv file for the format.

function isCSV($filename) {
    $allowed_mime_types = [
        'text/csv',
        'text/plain',
        'text/comma-separated-values',
        'application/vnd.ms-excel',
        'application/csv',
        'application/vnd.msexcel',
        'text/anytext',
        'application/octet-stream',
        'application/txt',
        'application/excel',
    ];
    $file_info = file_info_open(FILEINFO_MIME_TYPE);
    $file_mime_type = file_info_file($file_info, $filename);

    return in_array($file_mime_type, $allowed_mime_types);
}


Tuesday 9 August 2016

PHP Function to Calculate Age from Date of Birth

Make use of this simple PHP function to calculate age of person from the date of birth. Find your age with this simple php function. Find the age of celebrities with this simple php function.

function calculateAge($dob) {
            $date = $this->calculateDOB($dob);
            $dateObj = new DateTime($date);
            $nowObj = new DateTime();
            $interval = $nowObj->diff($dateObj);
            return $interval->y;
 }

Monday 8 August 2016

PHP Function to create SEO friendly URLs

Use this function to create SEO friendly urls. Make urls readable and seo friendly with this simple php function.

function seoUrlAscii($str, $replace=array(), $delimiter='-') {
            if(!empty($replace)) { $str = str_replace((array)$replace, ' ', $str); }
           
            $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
            $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
            $clean = strtolower(trim($clean, '-'));
            $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
           
            return $clean;
        }

Sunday 7 August 2016

Check whether a word is Palindrome or not in PHP

PHP Function to test whether a given word is a palindrome or not. A Palindrome is a word which when reversed also gives the same word. This simple function helps in finding whether the given word is a palindrome or not.

function isWordPalindrome($word) {
    $word = str_replace(' ', '', $word);
    return $word == strrev($word);
}

Friday 5 August 2016

PHP Function to Create a Directory in given Path

Simple php function to create directory in given path. This makes creating your directory easy and efficient.

function createFolder($path, $foldername) {
            $filename = $path.'/'.$foldername;
          
            if (!file_exists($filename)) {
                mkdir($path.'/'.$foldername, 0777);
                return true;
                exit;
            } else { return true; }

}

Pass your path in $path variable and the folder name in $foldername variable.

Wednesday 3 August 2016

Generate Folder Name based on ID or Number in PHP

PHP Function to generate folder name based on id or a number. Use the following function to create folder name as desired based on your needs.

function generateFolderName($no) {
    $id = ceil(($no/1000))-1;    //Here "1000" defines the folder change after 1000 files
    $folder = "";
    while($id >= 0) {
        $folder = chr($id % 26 + 65) . $folder;
        $id = floor($id / 26) - 1;
    }
    return strtolower($folder);
}


This makes folder name change after 1000 files. Hence 1-1000 will return "a" and 1001-2000 will return "b" and hence like that.

Monday 1 August 2016

PHP function to Download File

Download a file from given URL and store it in the specified path. This simple function takes url and path as inputs and saves the file from the url to the specified path.

We can download image files, pdf files, csv files and sql files from the specified url and store in the required path.

function downloadFile($file_url, $save_path) {
            $newfname = $
save_path;
            $file = fopen ($
file_url, 'rb');
            if($file) {
                $newfile = fopen ($newfname, 'wb');
                if($
newfile ) {
                    while(!feof($file)) {
                        fwrite($
newfile , fread($file, 1024 * 8), 1024 * 8);
                    }
                }
            }
            if($file) { fclose($file); }
            if($
newfile ) { fclose($newfile ); }
 }

Sunday 31 July 2016

Function to make Variables safe in PHP

Use  this efficient function to make all variables safe from hacking and tampering of data . Use this basic function to validate an extra extend and increase security for PHP POST, GET and REQUEST variables.

function makeVariablesSafe($mystring) {
            $mystring= trim($mystring);
            return $mystring= mysql_real_escape_string($mystring);

}

Saturday 30 July 2016

Convert Centimeters(cm) to Feets and Inches in PHP

Very useful php function to convert centimeter to display as Feets and inches. This function is used to calculate height of celebrities.

function cm2feet($cm) {
            $inches = $cm/2.54;
            $feet = intval($inches/12);
            $inches = $inches%12;
            return sprintf('%d \' %d "', $feet, $inches);

}

Friday 29 July 2016

Get Short Title of the Title in PHP Function

Simple function to get subset of words from a big string. Use this simple function to trim a big sentence into a short string with subset of words.

function getTrimedSentence($string, $max_length, $offset=0, $add_dots=1){
    $words_array = explode(" ", $string);
    return
        ($add_dots && $offset>0 ? " ... " : "") .
        implode(" ", array_splice($words_array, $offset, $max_length)) .
        ($add_dots && $max_length < count($words_array) ? " ... " : "");
}

Wednesday 27 July 2016

Encode Image in PHP as a Data Source

Use this simple php function to encode image into a data source for easy inline of the image data. This method will make the image load faster in webpage.

function encodeImage($filepath) {
    $filecontents = file_get_contents($filepath);
    $base64 = base64_encode($filecontents);
    $imagetype = exif_imagetype($filepath);
    $mime = image_type_to_mime_type($imagetype);
    return "data:$mime;base64,$base64";
}

Tuesday 26 July 2016

HEX to RGB convertor in PHP

PHP function to convert HEX code to RGB values. This functions takes HEX code as input and returns rgb values. It can be customized to return a string of rgb values separated by comma or can be set to return rgb values as an array.

function hexToRGB($hex_code) {
    $hex_code = str_replace("#", "", $hex_code);
   
    if(strlen($hex_code) == 3) {
        $red = hexdec(substr($hex_code,0,1).substr($hex_code,0,1));
        $green = hexdec(substr($hex_code,1,1).substr($hex_code,1,1));
        $blue = hexdec(substr($hex_code,2,1).substr($hex_code,2,1));
    } else {
        $red = hexdec(substr($hex_code,0,2));
        $green = hexdec(substr($hex_code,2,2));
        $blue = hexdec(substr($hex_code,4,2));
    }
    $rgb = array($red, $green, $blue);
    //return implode(",", $rgb); // rgb values will be returned as string separated by commas
    return $rgb; // rgb values will be returned as an array
}

Monday 25 July 2016

Remove Files Older than a date in PHP

PHP function to remove files older than number of days. This simple function takes directory path and no of days as arguments and removes the files older than particular days from the directory.

function removeFilesOlderThan($dir_path, $$no_of_days) {
    if ($handle = opendir($dir_path)) {
        while (false !== ($file = readdir($handle))) {
            $filelastmodified = filemtime($dir_path . '/' . $file);
            $filetype = filetype($dir . '/' . $file);
            if($filetype != 'file') continue;
            if((time() - $filelastmodified) > 24*60*60*$$no_of_days){
                unlink($dir_path . '/' . $file);
            }
        }
        closedir($handle);
    }
    else {
        echo "Directory not available";
    }
}


Make use of the function to remove backup files automatically after particular days in order to avoid too much of load in the server.

Saturday 23 July 2016

PHP Function to read file to CSV array

Use these simple php function to read csv and tsv files to a php array. We can read data from a comma separated file and tab separated file and make a php array with this simple function.

function readCsvTsvToArray($filepath, $preserveKeys=false, $filetype) {
        if($filetype=="csv") $separator=",";
        else if($filetype=="tsv") $separator="  ";
        $array = array();
     
        if (!file_exists($filepath)){ return $array; }
        $fileContent = file($filepath);
     
        for ($x=0; $x<count($fileContent); $x++) {
            if (trim($fileContent[$x]) != '') {
                $line = explode("$separator", trim($fileContent[$x]));
                if ($preserveKeys) {
                    $key = array_shift($line);
                    $array[$key] = $line;
                }
                else { $array[] = $line; }
            }
        }
        return $array;
}

Friday 22 July 2016

Text Watermark a Image in PHP

How to watermark a simple text on a image using PHP?
We can watermark a image using this simple in php. PHP text watermark can be used for creating a copyright  on a image for your website.

header('Content-type: image/jpeg'); // Set the Content Type
$imageJPEG = imagecreatefromjpeg('demo_image.jpg'); // Create Image From Existing File
$textColor = imagecolorallocate($imageJPEG, 255, 255, 255); // Color of the text watermark
$fontStyle = 'my_font.TTF'; // Path of the Font File
$textToWrite = "WaterMark Text"; // Watermark text to place on image
imagettftext($imageJPEG, 25, 0, 75, 300, $textColor, $fontStyle, $textToWrite);
imagejpeg($imageJPEG); // Show Image inBrowser
imagedestroy($imageJPEG);

Thursday 21 July 2016

PHP Function to get IP address of a client

Easy and simple function to get ip address of client address. Below function gets the clients system ip address in normal cases and if the client is present in a proxy then it will get the real ip address.

function getIPAddress() {
    if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }
    elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}


Use the above php code snippet to show the ip address of the client in your webpage.

Wednesday 20 July 2016

PHP Function to get browser details

Simple php function to get browser details using user agent. In addition this gives details about OS, browser, browser version, etc.

function getBrowserDetails() {
    $useragent = $_SERVER['HTTP_USER_AGENT'];
    return $useragent;
}

Tuesday 19 July 2016

PHP Function generate authentication string

Simple PHP function to generate a authentication string. Create a random string in php. Generate random password in php using a simple function.

function generateAuthenticationString($length) {
    $allowedChars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $string = "";
    for($i=0;$i<$length;$i++){
        $randPos = rand(0,36);
        $string .= $allowedChars{$randPos};
    }
    return $string;
}

Monday 18 July 2016

PHP Function to Validate Email

Validate Email in php. Simple php function to validate email address.

function validateEmail($email) {
    if(preg_match("~([a-zA-Z0-9!#$%&amp;'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)) {
        return true;
    } else {
        return false;
    }
}

Sunday 17 July 2016

PHP Function to encode and decode string in PHP

Simple php function to encode and decode a string in php. This function uses simple base64_encode to encode the string.

function base64url_encode($mytext) {
    $base64 = base64_encode($mytext);
    $base64url = strtr($base64, '+/=', '-_,');
    return $base64url;
}

function base64url_decode($mytext) {
    $base64url = strtr($mytext, '-_,', '+/=');
    $base64 = base64_decode($base64url);
    return $base64;
}

Saturday 16 July 2016

PHP Function to get current page URL

Most useful php function in getting the current page url

function getCurrentPageURL() {
    $url = 'http';
    if($_SERVER["HTTPS"] == "on") {

         $url .= "s";
    }
    $url .= "://";
    if($_SERVER["SERVER_PORT"] != "80") {
        $url .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
    } else {
        $url .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
    }
    return $url;
}


Use this simple function to get current page url.

Friday 15 July 2016

How to hide notices and warnings in PHP

Method to hide all notices and warnings in php. Use the following code in php.ini file hide all notices and warnings in php.

In php.ini file add the below code

error_reporting = E_ALL & ~E_NOTICE & ~E_WARNING

Thursday 14 July 2016

PHP Function to check whether a file is an image

Easy and efficient way to check whether a file is a image file or not. Use the following function to determine whether a file is a image type or not.

function checkFileForImage($image_path) {
    $image_info = getimagesize($image_path);
    $image_type = $image_info[2];
   
    if(in_array($image_type , array(IMAGETYPE_GIF , IMAGETYPE_JPEG ,IMAGETYPE_PNG , IMAGETYPE_BMP))) {
        // Following file types can also be added in above array if needed
        // IMAGETYPE_SWF, IMAGETYPE_PSD, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM, IMAGETYPE_JPC, IMAGETYPE_JP2, IMAGETYPE_JPX, IMAGETYPE_JB2, IMAGETYPE_SWC, IMAGETYPE_IFF, IMAGETYPE_WBMP, IMAGETYPE_JPEG2000, IMAGETYPE_XBM, IMAGETYPE_ICO, IMAGETYPE_UNKNOWN, IMAGETYPE_COUNT

        $image_width = $image_info[0]; // Additional feature to get width
        $image_height = $image_info[1]; // Additional feature to get height
        return true;
    }
    return false;
}


In the above function "getimagesize" function does the trick. It returns the array containing the details like width, height and image type. Function "checkFileForImage" returns true if the $image_path is an image and false if not.

Wednesday 13 July 2016

PHP Function to Convert Array to Object

Easy php function to convert php array to php object. Php objects are easy to access and get data than array.
function convertToObject(array $array) {
    foreach($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = convertToObject($value);
            }
     }    
     return (object) $array; 

}

Tuesday 12 July 2016

PHP Function to compress image in lossless quality

Efficient php function to compress image quality without any loss in quality and clarity,
function compressImageQuality($source_path, $destination_path , $quality) {
    $info = getimagesize($source_path);
    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source_path);
    }
    elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source_path);
    }
    elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source_path);
    }
    else { die('File format not supported'); }

    imagejpeg($image, $destination_path, $quality);
    return $destination_path;
}


This function will read jpg/gif/png image and compress it and save to jpg format. The imagejpeg  function compresses the image and stores as jpeg image.

PHP Function to download a file from URL

Simple php function to download files like pdf, xml, doc and images from a url and save to given path in server
function download_remote($source_url , $destination_path) {
    $file = fopen( $destination_path , 'w+');
    $file_handle = fopen($source_url , "rb");
    while (!feof($file_handle)) {
        $file_contents = fread($file_handle, 8192);
        fwrite($file , $file_contents);
    }
    fclose($file_handle);
    fclose($file);
}
In this $source_url holds the path of file to download and $destination_path holds the path to save file.

Monday 11 July 2016

PHP function to parse text to hyperlinks

Following function is used to parse text and convert the urls into links, in addition it converts mail id to mailto links. This simple function basically functions on regular expressions.

function parseTxt2Links($fulltxt) {
    $fulltxt = str_replace('www.', 'http://www.', $fulltxt);
    $fulltxt = preg_replace('|http://([a-zA-Z0-9-./]+)|', '<a href="http://$1">$1</a>', $fulltxt);
    $fulltxt = preg_replace('/(([a-z0-9+_-]+)(.[a-z0-9+_-]+)*@([a-z0-9-]+.)+[a-z]{2,6})/', '<a href="mailto:$1">$1</a>', $fulltxt);
    return $fulltxt;
}

Sunday 10 July 2016

PHP function to redirect to previous page

Easy way to redirect a webpage to previous page in php
function redirectToPreviousPage() {
    header("Location: {$_SERVER['HTTP_REFERER']}");
    exit;
}
In this $_SERVER is a superglobal variable, in which HTTP_REFERER holds the address of the page which refered this page.

Thursday 21 April 2016

PHP function to get source of webpage

Simple php function to get and display source code of a webpage.
function getSourceCode($pageurl) {
     $lines = file($pageurl);
     $output = "";
     foreach ($lines as $line_num => $line) {
         // loop thru each line and prepend line numbers
         $output.= "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
     }
}

Wednesday 20 April 2016

Php function to validate email address

PHP function to validate Email Address 

Simple php function to validate email address. Helps in validating email address in php.

function isValidEmail($email) {
    if(preg_match("/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/", $email) > 0)
        return true;
    else
        return false;
}

Monday 18 April 2016

PHP function to convert Multidimensional Arrays to stdClass Objects

PHP function to convert Multidimensional Arrays to stdClass Objects

<?php
    function array2object($myarray) {
        if (is_array($myarray)) {
            return (object) array_map(__FUNCTION__, $myarray);
        }
        else {
            return $myarray;
        }
    }
?>

PHP function to convert stdClass Objects to Multidimensional Arrays

PHP function to convert stdClass Objects to Multidimensional Arrays

<?php
    function object2array($myobj) {
        if (is_object($myobj)) {
            $myobj = get_object_vars($myobj);
        }
        if (is_array($myobj)) {
            return array_map(__FUNCTION__, $myobj);
        }
        else {
            return $myobj;
        }
    }
?>

Friday 15 April 2016

PHP Predefined Constants

PHP Predefined Constants

Php in default has some predefined constants. This post explains about some major PHP magic constants.

  • __DIR__ – The directory of the file.
  • __FILE__ – The full path and filename of the file.
  • __CLASS__ – The class name.
  • __FUNCTION__ – The function name.
  • __METHOD__ – The class method name.
  • __LINE__ – The current line number of the file.
  • __NAMESPACE__ – The name of the current namespace

Tuesday 12 April 2016

Add PHP ordinal suffix to Numbers

Add PHP ordinal suffix to Numbers

Function to add st, nd, rd and th to numbers in php

function numberSuffix($number) {
        if(!in_array(($number % 100),array(11,12,13))) {
            switch ($number % 10) {
              case 1: return $number.'st';
              case 2: return $number.'nd';
              case 3: return $number.'rd';
            }
        }
        return $number.'th';
}

Thursday 7 April 2016

Right and Left Trim in php

Right and Left Trim in php

Right Trim:

To right trim a string use "rtrim" function in php
$path = "/test-string/"
echo $path = rtrim($path,"/"); 

Output:
/test-string


Left Trim:

To left trim a string use "ltrim" function in php
$path = "/test-string/"
echo $path = ltrim($path,"/"); 

Output:
test-string/