Very Useful PHP Functions – Part 1

Following are very useful functions that can be used to control many aspects of PHP program. Functions include chop, character filter, search and replace and more.

<?php
// get variables by requesting
function getVar(&$value, $default = null)
{
    return isset($value) ? $value : $default;
}
// usage
// $act = getVar($_REQUEST["act"]);
?>

Character, word Filter

<?php
// disallow if character found
if (strpos($string, '#') !== false || strpos($string, '\') !== false) {
    // One of those two characters is in the string.
}
?>

Search and Replace

<?php
// search and replace
$find = "what";
$replace = "yes";
$text = "our text with word what";
echo str_replace($find, $replace, $text);
?>
<?php
// search and replace array
$search  = array('A', 'B', 'C', 'D', 'E');
$replace = array('B', 'C', 'D', 'E', 'F');
$subject = 'A';
echo str_replace($search, $replace, $subject);
?>
<?php
// replace many things from input
$rule = array("https://" => "", ".com" => "", "www" => "");
echo strtr("$myText", $rule);
?>

Chop Word

<?php
// chop word
$str = "Hello World!";
echo $str . "<br>";
echo chop($str,"World!");
?>

Clear White Space

<?php
// clear white space from beginning and end of given text
$trimmed = trim($text);
?>

Find Files and List them

<?php
    // get all php files  (specific types of files from a location)
    $files = glob('*.php');  
    print_r($files);  
 
    /* output looks like: 
    Array 
    ( 
        [0] => phptest.php 
        [1] => pi.php 
        [2] => post_output.php 
        [3] => test.php 
    ) 
    */
?>

Generate Unique ID with Timestamp

// generate a truly unique string (ID)
echo md5(time() . mt_rand(1,1000000));
?>

OR

<?php
// unique string
echo uniqid();
?>

OR

<?php
    // with prefix  
    echo uniqid('foo_');  
    /* prints 
    foo_4bd67d6cd8b8f 
    */  
 
    // with more entropy  
    echo uniqid('',true);  
    /* prints 
    4bd67d6cd8b926.12135106 
    */  
 
    // both  
    echo uniqid('bar_',true);  
    /* prints 
    bar_4bd67da367b650.43684647 
    */  
?>

Compress and Uncompress Long Data While Storing

<?php
$string = "Lorem ipsum dolor sit amet.";
$compressed = gzcompress($string);
echo "Original size: ". strlen($string)."\n";  
/* prints 
Original size: 800 
*/  
echo "Compressed size: ". strlen($compressed)."\n";  
/* prints 
Compressed size: 418 
*/  
// getting it back  
$original = gzuncompress($compressed);
?>

Detect browser language

<?php
function get_client_language($availableLanguages, $default='en'){
	if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
		$langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);
 
		foreach ($langs as $value){
			$choice=substr($value,0,2);
			if(in_array($choice, $availableLanguages)){
				return $choice;
			}
		}
	} 
	return $default;
}
?>

Download & save a remote image on your server

List Directory Contents

<?php
function list_files($dir)
{
	if(is_dir($dir))
  	{
  		if($handle = opendir($dir))
  		{
  			while(($file = readdir($handle)) !== false)
  			{
  				if($file != "." && $file != ".." && $file != "Thumbs.db")
  				{
  					echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
  				}
  			}
  			closedir($handle);
  		}
	}
}
?>

Create Post Slugs

<?php
function create_slug($string){  
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);  
return $slug;  
}
?>

Get Real IP Address of Client

<?php
    function getRealIpAddr()  
    {  
        if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))  
        {  
            $ip=$_SERVER['HTTP_CLIENT_IP'];  
        }  
        elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))  
        //to check ip is pass from proxy  
        {  
            $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];  
        }  
        else  
        {  
            $ip=$_SERVER['REMOTE_ADDR'];  
        }  
        return $ip;  
    }  
?>

Force file Download

<?php
    /******************** 
    *@file - path to file 
    */  
    function force_download($file)  
    {  
        if ((isset($file))&&(file_exists($file))) {  
           header("Content-length: ".filesize($file));  
           header('Content-Type: application/octet-stream');  
           header('Content-Disposition: attachment; filename="' . $file . '"');  
           readfile("$file");  
        } else {  
           echo "No file selected";  
        }  
    }  
?>

Find Similarity Between Two Strings

<?php
similar_text($string1, $string2, $percent);  
//$percent will have the percentage of similarity
?>

Zip Files on the Fly

<?php
/* creates a compressed zip file */
function create_zip($files = array(),$destination = '',$overwrite = false) {
	//if the zip file already exists and overwrite is false, return false
	if(file_exists($destination) && !$overwrite) { return false; }
	//vars
	$valid_files = array();
	//if files were passed in...
	if(is_array($files)) {
		//cycle through each file
		foreach($files as $file) {
			//make sure the file exists
			if(file_exists($file)) {
				$valid_files[] = $file;
			}
		}
	}
	//if we have good files...
	if(count($valid_files)) {
		//create the archive
		$zip = new ZipArchive();
		if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
			return false;
		}
		//add the files
		foreach($valid_files as $file) {
			$zip->addFile($file,$file);
		}
		//debug
		//echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
 
		//close the zip -- done!
		$zip->close();
 
		//check to make sure the file exists
		return file_exists($destination);
	}
	else
	{
		return false;
	}
}
/***** Example Usage ***/
$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
create_zip($files, 'myzipfile.zip', true);
?>

unzip files

<?php
/**********************
*@file - path to zip file
*@destination - destination directory for unzipped files
*/
function unzip_file($file, $destination){
	// create object
	$zip = new ZipArchive() ;
	// open archive
	if ($zip->open($file) !== TRUE) {
		die (’Could not open archive’);
	}
	// extract contents to destination directory
	$zip->extractTo($destination);
	// close archive
	$zip->close();
	echo 'Archive extracted to directory';
}
?>

Convert URLs within String into hyperlinks

<?php
function makeClickableLinks($text) {
 $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
 '<a href="\1">\1</a>', $text);
 $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
 '\1<a href="https://\2">\2</a>', $text);
 $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
 '<a href="mailto:\1">\1</a>', $text);
 
return $text;
}
?>

Resize Images on the fly

<?php
/**********************
*@filename - path to the image
*@tmpname - temporary path to thumbnail
*@xmax - max width
*@ymax - max height
*/
function resize_image($filename, $tmpname, $xmax, $ymax)
{
	$ext = explode(".", $filename);
	$ext = $ext[count($ext)-1];
 
	if($ext == "jpg" || $ext == "jpeg")
		$im = imagecreatefromjpeg($tmpname);
	elseif($ext == "png")
		$im = imagecreatefrompng($tmpname);
	elseif($ext == "gif")
		$im = imagecreatefromgif($tmpname);
 
	$x = imagesx($im);
	$y = imagesy($im);
 
	if($x <= $xmax && $y <= $ymax)
		return $im;
 
	if($x >= $y) {
		$newx = $xmax;
		$newy = $newx * $y / $x;
	}
	else {
		$newy = $ymax;
		$newx = $x / $y * $newy;
	}
 
	$im2 = imagecreatetruecolor($newx, $newy);
	imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
	return $im2; 
}
?>