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