Affordable Hosting and Web Development Services    (615) 541-9327
Blog-Uru's Subscribe to Music City Guru News feed
Customer Testimonials
The Random Sniglet
Refresh | More Sniglets

5 Php Functions For Code Life Article # 498 

Web development doesn’t have to be a difficult position, if you have a toolbox of sorts, which can help you with the ‘heavy lifting’ of applications and provide easier tasks that get repetitive.

I want to share my tools with you, in the hopes that they may also lend a hand in the workings of your applications or website developments.

What Percentage is that of that thing?

What percent of this is that? This is an interesting little function that provides me with percentiles when I need to know the percentage of X value based on a total value. What percentage of X is Y? Boink! Answer is always correct, and I never have to touch the calculator.

function percent($num_amount, $num_total) {
    $count1 = $num_amount / $num_total;
    $count2 = $count1 * 100;
    $count = number_format($count2, 0);
return $count ."%";
}

echo percent(200, 1000);

Sanitizing form inputs for fun and profit

Today’s internet is a volatile environment where anything can happen, and without warning, usually does. It’s become common practice to protect your website and it’s server from being compromised by the ‘hackers’ who seek to find security holes in any system. To prevent such acts of senseless defacing and breach of security systems, it’s always a real good idea to protect your assets whenever you allow input from the dirty internet and it’s an even better idea to sanitize your data before storing it on your website’s database or file structure.

class Validator {
public $_filterArgs;

function removeTags($fieldName,
     $encodeAmp = false,
     $preserveQuotes = false,
     $encodeLow = false,
     $stripLow = false,
     $stripHigh = true) {

  $this->_filterArgs[$fieldName]['filter'] = FILTER_SANITIZE_STRING;
  $this->_filterArgs[$fieldName]['flags'] = FILTER_REQUIRE_ARRAY;

if($encodeAmp) {
     $this->_filterArgs[$fieldName]['flags'] |= FILTER_FLAG_ENCODE_AMP;
   }		

  if($preserveQuotes){
       $this->_filterArgs[$fieldName]['flags'] |= FILTER_FLAG_NO_ENCODE_QUOTES;
  }
  if($encodeLow) {
      $this->_filterArgs[$fieldName]['flags'] |= FILTER_FLAG_ENCODE_LOW;
  }
  if($encodeHigh) {
    $this->_filterArgs[$fieldName]['flags'] |= FILTER_FLAG_ENCODE_HIGH; 
  }
  if($stripLow) {
    $this->_filterArgs[$fieldName]['flags'] |= FILTER_FLAG_STRIP_LOW;
  }
  if($stripHigh) {
     $this->_filterArgs[$fieldName]['flags'] |= FILTER_FLAG_STRIP_HIGH;
  }
 }
}

This function, saved in a class file, (call it validator.class.php) will greatly reduce the amount of ‘filth’ that could find it’s way into your forms, and basically strip off any unwanted ‘gunk’ that a malicious attacker might wish to inject into your website’s system. This is only one of many gunk-removing functions available for protecting your website from the myriad of attacks that lurk in the dark corners of the internet.

Short hand ‘if’ statements, save time and space

Decisions happen all the time in PHP and when you need to make a quick YES/NO decision, having a one-line snippet of code takes all the work out of building the ‘gate’ which can end up saving you TONS of time and space in your code.

Example standard decision:

if($answer == "no") {
   $response = "You answered no.";
}else{
   $response = "OK. You answered Yes." ;
}

Four lines of code to check what the answer was and provide an response based on that answer. Now, let’s shorten it to a single line with a shorthand ‘if’ statement.

echo ($answer == "no" ? "You answered no." : "OK. You answered Yes.");

Now, this is a very basic example, but you can clearly see how this single line of code does the work of the 4-line block of code. Works faster, and takes up less space in your code file. Less filling, and tastes great..

How Long Ago Was That?

If you’ve ever needed to know how long ago something was compared to the current time, this little function kicks butt and does it quite nicely in an efficient little function.

echo TimeAgoEN($timestamp);

function convert_datetime($str) { 
  list($date, $time) = explode(' ', $str);    
  list($year, $month, $day) = explode('-', $date);    
  list($hour, $minute, $second) = explode(':', $time);         
  $timestamp = mktime($hour, $minute, $second, $month, $day, $year);         
  return $timestamp;      
} 

function TimeAgoEN($timestamp){       
    $now = time();    
    $then = convert_datetime($timestamp);    
    $difference = $now-$then;          

     $units = array( 'second' => 1,        
                            'minute' => 60,        
                             'hour' => 3600,        
                             'day' => 86400,        
                             'week' => 604800,        
                              'month' => 2630880,        
                               'year' => 31570560,        
                              'decade' => 315705600,    
                            );         

      foreach($units as $key => $val)  {      
           if($difference >= $val) {          
               $results = floor($difference/$val);                    
               if($results == '1') {
                    $ending = "";
                } else {
                    $ending = "s";
                }          

            $outcome = $results." ".$key.$ending." ago";      
        }    
      }         
    return $outcome; 
}

Convert A Birthdate To An Age

Rather than tell me the date of birth, sometimes we just need to ask “How old are you”? This handy function performs the calculations and returns the age value. Very nice little function, that can be adapted for several things.

function convert_birth_date_to_age($birth_date) {
     $today = gmdate("Y-m-d");
     $bday_arr = explode("-", $birth_date);    
     $today_arr = explode("-", $today);          

if( ($today_arr[1]<$bday_arr[1]) ||
    ($today_arr[1]==$bday_arr[1] && $today_arr[2]<$bday_arr[2])) {        
$var = -1;    
}          

return $today_arr[0]-$bday_arr[0]+$var; 

}

Serialize your data – complex information for a complex world

If you’ve ever needed to store complex variable in a database or a file, you’re probably aware that PHP can do amazing things to simplify performing this task. Using the serialize function, we can convert arrays, or complex data for use in files and databases.

// a complex array
$myvar = array(
	'hello',
	42,
	array(1,'two'),
	'apple'
);

// convert to a string
$string = serialize($myvar);

echo $string;
/* prints
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3:"two";}i:3;s:5:"apple";}
*/

// you can reproduce the original variable
$newvar = unserialize($string);

print_r($newvar);
/* prints
Array
(
    [0] => hello
    [1] => 42
    [2] => Array
        (
            [0] => 1
            [1] => two
        )

    [3] => apple
)
*/

In PHP 5.2 and later, we can perform this same form of serialization with jason_encode() functions, which is preferred now because javascript also supports this and we have an easier solution for it. Now you can use the json_encode() andjson_decode() functions as well:

// a complex array
$myvar = array(
'hello',
42,
array(1,'two'),
'apple'
);

// convert to a string
$string = json_encode($myvar);

echo $string;
/* prints
["hello",42,[1,"two"],"apple"]
*/

// you can reproduce the original variable
$newvar = json_decode($string);

print_r($newvar);
/* prints
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
 [3] => apple
)
*/

Hopefully, these examples will help make your life easier, and improve your ability to write effective and improved applications.

Got more functions? Want to share them? Drop it to us on our contact page.