Showing posts with label php snippets. Show all posts
Showing posts with label php snippets. Show all posts

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

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

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

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