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.