Saturday, August 17, 2013

PHP Memory Usage


This is a simple example of a class, which can be used to collect the PHP script memory usage information and to print all information.


PHP Memory Usage - Class

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 class MemoryUsageInformation {
    private $real_usage;
    private $statistics = array();
 
    // Memory Usage Information constructor
    public function __construct($real_usage = false) {
      $this->real_usage = $real_usage;
    }
 
    // Returns current memory usage with or without styling
    public function getCurrentMemoryUsage($with_style = true) {
      $mem = memory_get_usage($this->real_usage);
      return ($with_style) ? $this->byteFormat($mem) : $mem;
    }
 
    // Returns peak of memory usage
    public function getPeakMemoryUsage($with_style = true) {
      $mem = memory_get_peak_usage($this->real_usage);
      return ($with_style) ? $this->byteFormat($mem) : $mem;
    }
 
    // Set memory usage with info
    public function setMemoryUsage($info = '') {
      $this->statistics[] = array('time' => time(), 
                                  'info' => $info, 
                                  'memory_usage' => $this->getCurrentMemoryUsage());
    }
 
    // Print all memory usage info and memory limit and 
    public function printMemoryUsageInformation() {
      foreach ($this->statistics as $satistic) {
        echo  "Time: " . $satistic['time'] . 
              " | Memory Usage: " . $satistic['memory_usage'] . 
              " | Info: " . $satistic['info'];
        echo "\n";
      }
      echo "\n\n";
      echo "Peak of memory usage: " . $this->getPeakMemoryUsage();
      echo "\n\n";
    }
 
    // Set start with default info or some custom info
    public function setStart($info = 'Initial Memory Usage') {
      $this->setMemoryUsage($info);
    }
 
    // Set end with default info or some custom info
    public function setEnd($info = 'Memory Usage at the End') {
      $this->setMemoryUsage($info);
    }
 
    // Byte formatting
    private function byteFormat($bytes, $unit = "", $decimals = 2) {
     $units = array('B' => 0, 'KB' => 1, 'MB' => 2, 'GB' => 3, 'TB' => 4, 
       'PB' => 5, 'EB' => 6, 'ZB' => 7, 'YB' => 8);
 
     $value = 0;
     if ($bytes > 0) {
      // Generate automatic prefix by bytes 
      // If wrong prefix given
      if (!array_key_exists($unit, $units)) {
       $pow = floor(log($bytes)/log(1024));
       $unit = array_search($pow, $units);
      }
 
      // Calculate byte value by prefix
      $value = ($bytes/pow(1024,floor($units[$unit])));
     }
 
     // If decimals is not numeric or decimals is less than 0 
     // then set default value
     if (!is_numeric($decimals) || $decimals < 0) {
      $decimals = 2;
     }
 
     // Format output
     return sprintf('%.' . $decimals . 'f '.$unit, $value);
    }
  }



?>
Usage of  Class
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 // Create new MemoryUsageInformation class
  $m = new MemoryUsageInformation(true);
 
  // Set start
  $m->setStart();
 
  // Create example array
  $a = array();
 
  // Set memory usage before loop
  $m->setMemoryUsage('Before Loop');
 
  // Fill array with
  for($i = 0; $i < 100000; $i++) {
    $a[$i] = uniqid();
  }
 
  // Set memory usage after loop
  $m->setMemoryUsage('After Loop');
 
  // Unset array
  unset($a);
 
  // Set memory usage after unset
  $m->setMemoryUsage('After Unset');
 
  // Set end
  $m->setEnd();
 
  // Print memory usage statistics
  $m->printMemoryUsageInformation();


?>
CHECK Output of PHP Memory class

Objects to Array php


Every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects.



This post defines two simple function to convert
:multidimensional Objects to Arrays
:multidimensional Arrays to Objects


Function to Convert stdClass Objects to Multidimensional Arrays
Objects to Array php


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function objectToArray($d) {
  if (is_object($d)) {
   // Gets the properties of the given object
   // with get_object_vars function
   $d = get_object_vars($d);
  }
 
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return array_map(__FUNCTION__, $d);
  }
  else {
   // Return array
   return $d;
  }
 }
 
?>




Function to Convert Multidimensional Arrays to stdClass Objects
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function arrayToObject($d) {
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return (object) array_map(__FUNCTION__, $d);
  }
  else {
   // Return object
   return $d;
  }
 }

?>

Function usage

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


// Create new stdClass Object
 $init = new stdClass;
 
 // Add some test data
 $init->foo = "Test data";
 $init->bar = new stdClass;
 $init->bar->baaz = "Testing";
 $init->bar->fooz = new stdClass;
 $init->bar->fooz->baz = "Testing again";
 $init->foox = "Just test";
 
 // Convert array to object and then object back to array
 $array = objectToArray($init);
 $object = arrayToObject($array);
 
 // Print objects and array
 print_r($init);
 echo "\n";
 print_r($array);
 echo "\n";
 print_r($object);

?>

Saturday, July 20, 2013

Two way encryption in PHP Mcrypt

This class provides the functionality to encrypt and decrypt a text string. The class makes use of the PHP mcrypt extension which provides the ability to create two way encryption, or decoding of text messages.


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

error_reporting(E_ALL);

class runCrypt 
{
    /**
    *
    * This is called when we wish to set a variable
    *
    * @access    public
    * @param    string    $name
    * @param    string    $value
    *
    */
    public function __set( $name, $value )
    {
        switch( $name)
        {
            case 'key':
            case 'ivs':
            case 'iv':
            $this->$name = $value;
            break;

            default:
            throw new Exception( "$name cannot be set" );
        }
    }

    /**
    *
    * Gettor - This is called when an non existant variable is called
    *
    * @access    public
    * @param    string    $name
    *
    */
    public function __get( $name )
    {
        switch( $name )
        {
            case 'key':
            return 'keee';

            case 'ivs':
            return mcrypt_get_iv_size( MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB );

            case 'iv':
            return mcrypt_create_iv( $this->ivs );

            default:
            throw new Exception( "$name cannot be called" );
        }
    }

    /**
    *
    * Encrypt a string
    *
    * @access    public
    * @param    string    $text
    * @return    string    The encrypted string
    *
    */
    public function encrypt( $text )
    {
        // add end of text delimiter
        $data = mcrypt_encrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
        return base64_encode( $data );
    }
 
    /**
    *
    * Decrypt a string
    *
    * @access    public
    * @param    string    $text
    * @return    string    The decrypted string
    *
    */
    public function decrypt( $text )
    {
        $text = base64_decode( $text );
        return mcrypt_decrypt( MCRYPT_RIJNDAEL_128, $this->key, $text, MCRYPT_MODE_ECB, $this->iv );
    }
} // end of class

?>



Example Usage


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


// a new runCrypt instance
$crypt = new runCrypt;

// encrypt the string
$encoded = $crypt->encrypt( 'my message');
echo $encoded."\n";

// decrypt the string
echo $crypt->decrypt( $encoded ) . "\n";

?>

Round up to multiple in php


Here is a simple function that will round a number up to a given multiple. may this help you

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

function roundUpToMultiple( $number, $multiple)
{
    return ceil( $number/$multiple ) * $multiple;
} 


?>


Example Usage
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

echo roundUpToMultiple( 12, 7 );

?>

Thursday, June 27, 2013

PHP date validation

Date Validation yyyy-mm-dd
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$date = '2013-06-27';

function isValidDate($date)
{
 if(preg_match("/^(\d{4})-(\d{2})-(\d{2})$/", $date, $matches))
 {
  if(checkdate($matches[2], $matches[3], $matches[1]))
  {
   return true;
  }
 }
}

if(isValidDate($date)){
 echo 'valid date';
} else
{
 echo 'invalid date';
}

?>










Date Validation dd-mm-yyyy
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

$date = '27-06-2013';

function isValidDate($date)
{
 if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches))
 {

  if(checkdate($matches[2], $matches[1], $matches[3]))
  {
   return true;
  }
 }
}

if(isValidDate($date))
{
 echo 'valid date';
} else
{
 echo 'invalid date';
}


?>








Date Validation mm-dd-yyyy

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$date = '06-27-2013';

function isValidDate($date)
{
 if(preg_match("/^(\d{2})-(\d{2})-(\d{4})$/", $date, $matches))
{
  if(checkdate($matches[1], $matches[2], $matches[3]))
  {
   return true;
  }
 }
}

if(isValidDate($date)){
 echo 'valid date';
} else
{
 echo 'invalid date';
}

?>









Date Validation dd-mmm-yyyy
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$date = '27-Jun-2013';

function isValidDate($date)
{
 if(preg_match("/^(\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4})$/", $date, $matches)) 
 {
  $month = array('Jan'=>'01'
         ,'Feb'=>'02'
         ,'Mar'=>'03'
         ,'Apr'=>'04'
         ,'May'=>'05'
         ,'Jun'=>'06'
         ,'Jul'=>'07'
         ,'Aug'=>'08'
         ,'Sep'=>'09'
         ,'Oct'=>'10'
         ,'Nov'=>'11'
         ,'Dec'=>'12'
        );

  if(checkdate($month[$matches[2]],$matches[1],$matches[3]))
  {
   return true;
  }
 }
}

if(isValidDate($date))
{
 echo 'valid date';
} else
{
 echo 'invalid date';
}

?>

PHP function to calculate percentage

This post shows you how to calculate a percentage using a division and multiplying its result by 100. This is the simpliest way to calculate a percentage in PHP
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


function percentage($x, $y, $precision) 
{

        // $precision define digit after the decimal point

 $result = round( ($x / $y) * 100, $precision );
 
 return $result;
}


echo percentage(2, 3, 2); // This will print 66.67

echo percentage(2, 3, 0); // This will print 67

?>

Friday, June 21, 2013

Replace characters with icons emoticons php

Learn to use PHP to change character sequences into emoticons or icons by using the str_replace function. You will want to alter the string data as it comes out of the MySQL database for display, not when the data is being inserted into the database.

# USAGE EXAMPLE 

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


$db_string = "Show me some <3 right now. It is raining today [umbr], that gives me peace [peace].";

echo $db_string;
echo "
"; $chars = array("<3", "[peace]", "[umbr]"); $icons = array("❤", "☮", "☂"); $new_str = str_replace($chars,$icons,$db_string); echo $new_str; ?>

 

© 2014 4everTutorials. All rights resevered.

Back To Top