December 1, 2017 373 Views 0 Comment

12 Essential PHP Functions and Snippets

SHARE THIS ARTICLE

Storing tiny pieces of code snippets is an excellent way to maximize on development effort and save time. As a web developer, it’s good practice to store useful PHP functions and scripts that are highly reusable and sure to come in handy for future projects. Having the right piece of code at the right time is like having the perfect tool for the job. Here is a list of my top 12 Essential PHP Functions and Snippets, hope they can be useful to someone.

Check if String Begins With …

In PHP we occasionally need to match strings or portions thereof against some other string. I have used this function along with the substring function (substr) on countless occasions to match ip subnets on intranet based applications.


function startsWith($haystack, $needle){
    $length = strlen($needle);
    return (substr($haystack, 0, $length) === $needle);
}
echo startsWith("kodesmart.com", "kode");
//result 1

Add 6 Months to given Date

OK this is quite useful when you need to verify if a date is within a specified time frame or even within the past. The script below will add 6 months to today's date.


$today = date('Y-m-d');
$threeMonthsDate = date("F j, Y", strtotime("+6 months", strtotime($today)));

Apply Title Case to words

This function capitalizes the first letter of each word.


function titleCase($string){
    return ucwords(strtolower($string));
}
//result titleCase("kodesmart is an awesome blog!") > Kodesmart Is An Awesome Blog!

Parse Complex JSON Array to PHP Array

Perfect for when your array doesn't behave nicely with the json_decode function


foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($jsonDataArray)) as $k=>$v){
	$phpParamArray[$k] = $v;
}

Initialize POST Parameters

Initialize $_POST parameters that were not set before submitting the form


function initializeParamsNotSet(){
	$keys = array_keys($_POST);
	$select_keys = array('fname', 'country_code','dob');
	foreach ($select_keys as $select_key) {
		if (in_array($select_keys, $keys)) continue;  // already set
		$_POST[$select_keys] = '';
	}
}

Apply Trim function to each element in an array.

Works on arrays and strings. Perfect for use with $_POST arrays.



function safeTrim($data){
	if($data == null)
		return null;

	if(is_array($data)){
		return array_map('safeTrim', $data);
	}else return trim($data);
}

Custom Error Handler

Sends an email whenever an error is encountered in a PHP script.


// Create the error handler.
function my_error_handler ($e_number, $e_message, $e_file, $e_line, $e_vars){
	$contact_email="errors@kodesmart.com";
	$message = '<div class="error" id="error-palette">';
	$message .= "An error occurred in script '$e_file' on line $e_line: $e_message";
	$message .= "Date/Time: " . date('F j, Y H:i:s');
	$message .= "<div style='display:none' id='error-details'>" . print_r ($e_vars, 1) . "</div>";
	
	error_log ($message, 1, $contact_email);
	if(($e_number != E_NOTICE) && ($e_number < 2048)){
		echo 'A system error occurred. We apologize for the inconvenience';
	}
}
// Use my error handler:
set_error_handler ('my_error_handler');

Set System Date

Useful for establishing the server time in your web application. This can also be set from the php.ini file if you have access to it.


date_default_timezone_set('America/Jamaica');

Make Connection to MySQL Database

Once your developing a custom PHP application with database backend you will most definitely require this piece of code.


function MySQLDB(){
	$this->connection = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_NAME);	 
	/* check connection*/
	if(mysqli_connect_errno()){
		printf("Connection failed: %s\n", mysqli_connect_error());
		exit();
	}
}

Generate Random String

Simple php script for generating strings for use as tokens etc.


function generateRndString($length = 10, $chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890'){
    if($length > 0){
        $len_chars = (strlen($chars) - 1);
        $the_chars = $chars{rand(0, $len_chars)};
        for ($i = 1; $i < $length; $i = strlen($the_chars)){
            $r = $chars{rand(0, $len_chars)};
            if ($r != $the_chars{$i - 1}) $the_chars .=  $r;
        }

        return $the_chars;
    }
}

Redirect to another Page or URL

Using php to redirect to a different URL


header( 'Location: https://www.kodesmart.com' ) ;

Generate CSV from PHP Array

convert php array to excel file.


function generateCsv($data, $delimiter = ',', $enclosure = '"') { 
   $handle = fopen('php://temp', 'r+'); 
   foreach ($data as $line) { 
           fputcsv($handle, $line, $delimiter, $enclosure); 
   } 
   rewind($handle); 
   while (!feof($handle)) { 
           $contents .= fread($handle, 8192); 
   } 
   fclose($handle); 
   return $contents; 
}

PHP Function to Retrieve the URL of the Current Page

Useful for fetching the current page's url


function getPageURL() {
	$pageURL = ‘http’;
	if (!empty($_SERVER[‘HTTPS’])) {
		$pageURL .= “s”;
	}
		$pageURL .= “://”;
	if ($_SERVER[“SERVER_PORT”] != “80”) {
		$pageURL .= $_SERVER[“SERVER_NAME”].”:”.$_SERVER[“SERVER_PORT”].$_SERVER[“REQUEST_URI”];
	} else {
		$pageURL .= $_SERVER[“SERVER_NAME”].$_SERVER[“REQUEST_URI”];
	}
	return $pageURL;
}

If you found these PHP Functions useful please let us know. Share some of your own snippets with us.