PHP Snippet – Request-Argument From Either POST Or GET

In-case you would like to enable a request details from either POST or GET (and you do not really care from where it got from)- this is the proper way to do this.

*consider filtering the input, which should be handled depending on the content you expect to receive.

<?php
function arg_value($name){ /*returns a valid value or empty string. valid argument from either POST or GET */
  $items = [
            filter_input(INPUT_POST, $name, FILTER_UNSAFE_RAW)
           ,filter_input(INPUT_GET,  $name, FILTER_UNSAFE_RAW)
           ];

  $items = array_filter($items, function($item){
                                  $item = (null !== $item) && (false !== $item);
                                  return $item;
                                });
  array_push($items, null); /* null value */
  $items = array_shift($items);
  return $items;
}
?>

PHP Snippet – Generate Random Bytes

This code will generate any amount of bytes, in human readable Hex-characters,
using either random_bytes, mcrypt_create_iv or openssl_random_pseudo_bytes (all with added entropy), an additional, in-case of some sort of error or an old or lack of crypto-libraries PHP instance, there is a mt_rand-based on fallback.

<?php
$get_random_bytes = function($length = 64){
  $length = max(1, $length); /* valid input, at-least 1 byte. */

  $result = true === function_exists('random_bytes')                 ?  bin2hex(random_bytes($length))                          : 
            true === function_exists('mcrypt_create_iv')             ?  bin2hex(mcrypt_create_iv($length, MCRYPT_DEV_URANDOM))  : /* might give false on error */
            true === function_exists('openssl_random_pseudo_bytes')  ?  bin2hex(openssl_random_pseudo_bytes($length, true))     : /* might give false on error */
            false /* fallback */
            ;

  /* in case of FALSE (because of function-error or fallback) we will be using "simpler" random */
  $result = false !== $result ? $result : substr(                                                
                                            preg_replace_callback('#@#', function(){
                                              return dechex(mt_rand(0, 16)); 
                                            }, str_repeat('@', $length * 2))      /*64 bytes are 128 characters*/
                                            ,
                                            (-1 * $length * 2)                    /*trim - make sure exactly 128 characters (for example, if $length is 64)*/
                                          );
  return $result;
};

var_dump(
  $get_random_bytes()
);
?>

PHP Snippet – Script Runtime

REQUEST_TIME_FLOAT is a timestamp of the start of the request, with microsecond precision (PHP 5.4.0+).
microtime(true) returns a float of the current Unix timestamp (microseconds precision).

<?php
$time_start = call_user_func(function(){
                $result = filter_input(INPUT_SERVER, 'REQUEST_TIME_FLOAT', FILTER_SANITIZE_NUMBER_FLOAT);
                return false === $result || null === $result ? microtime(true) : $result;
              });

echo microtime(true) - $time_start
?>

– This is a “dictionary code”, in-order to save the extra anonymous-function call and checking if REQUEST_TIME_FLOAT is available, just use microtime all-along :)

Best practice:
Always use filter_input with some sort of filtering, try to avoid accessing the global variables directly ($_SERVER),
It will also make most of the code-validation engines happy ;)

PHP Human-Readable Time Diff (“5 Hours Ago”, “Will Be In A Day”,…)

Code Ripped From WordPress Trunk And Modified To Not Requiring Translator Objects (Use Plain en_US Default).


  // Constants for expressing human-readable intervals
  // in their respective number of seconds.
  define('MINUTE_IN_SECONDS', 60);
  define('HOUR_IN_SECONDS', 60 * MINUTE_IN_SECONDS);
  define('DAY_IN_SECONDS', 24 * HOUR_IN_SECONDS);
  define('WEEK_IN_SECONDS', 7 * DAY_IN_SECONDS);
  define('YEAR_IN_SECONDS', 365 * DAY_IN_SECONDS);


  /**
   * Retrieve the plural or single form based on the supplied amount.
   *
   * @param string $single The text that will be used if $number is 1.
   * @param string $plural The text that will be used if $number is not 1.
   * @param int    $number The number to compare against to use either $single or $plural.
   *
   * @return string Either $single or $plural translated text.
   */
  function _n($single, $plural, $number) {
    return 1 === $number ? $single : $plural;
  }

  /**
   * Determines the difference between two timestamps.
   *
   * The difference is returned in a human readable format such as "1 hour",
   * "5 mins", "2 days".
   *
   * @param int|string $from Unix timestamp from which the difference begins.
   * @param int|string $to   Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
   *
   * @return string Human readable time difference.
   */
  function human_time_diff($from, $to = '') {
    if (empty($to)) {
      $to = time();
    }


    $diff = (int)abs($to - $from);

    if ($diff < HOUR_IN_SECONDS) {
      $mins = round($diff / MINUTE_IN_SECONDS);
      if ($mins <= 1)
        $mins = 1;
      /* translators: min=minute */
      $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
    }
    elseif ($diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS) {
      $hours = round($diff / HOUR_IN_SECONDS);
      if ($hours <= 1)
        $hours = 1;
      $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
    }
    elseif ($diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS) {
      $days = round($diff / DAY_IN_SECONDS);
      if ($days <= 1)
        $days = 1;
      $since = sprintf(_n('%s day', '%s days', $days), $days);
    }
    elseif ($diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS) {
      $weeks = round($diff / WEEK_IN_SECONDS);
      if ($weeks <= 1)
        $weeks = 1;
      $since = sprintf(_n('%s week', '%s weeks', $weeks), $weeks);
    }
    elseif ($diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS) {
      $months = round($diff / (30 * DAY_IN_SECONDS));
      if ($months <= 1)
        $months = 1;
      $since = sprintf(_n('%s month', '%s months', $months), $months);
    }
    elseif ($diff >= YEAR_IN_SECONDS) {
      $years = round($diff / YEAR_IN_SECONDS);
      if ($years <= 1)
        $years = 1;
      $since = sprintf(_n('%s year', '%s years', $years), $years);
    }

    if ($to - $from > 0) {
      $since = 'was ' . $since . ' ago';
    }
    elseif ($to - $from < 0) {
      $since = 'will be in ' . $since;
    }

    return $since;

  }

Try it using the output of time()-9000 for "was 3 hours ago", or time()+9000 for "will be in 3 hours".

PHP Snippet – A Human-Readable Memory-Formatter, Add Commas To A Number By Regular-Expression

<?php

/**
 * @param float $size                - the memory size to format
 * @param bool  $is_add_commas       (optional) - saperete every 3 digits from the end so 56789 will be "56,789".
 * @param bool  $is_full_description (optional) - use *Bytes instead of *b (GigaBytes instead of gb, etc...).
 * @param int   $digits              (optional) - number of digits decimal point, to limit.
 * @return string
 */
function human_readable_memory_sizes($size, $is_add_commas = false, $is_full_description = false, $digits = 20) {
  $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
  $unit_full = array('Bytes', 'KiloByte', 'MegaBytes', 'GigaBytes', 'TeraBytes', 'PetaBytes');

  $out = $size / pow(1024, ($i = floor(log($size, 1024))));

  $out = sprintf("%." . $digits . "f", $out);

  $out = !$is_add_commas ? $out : preg_replace_callback('/(\d)(?=(\d{3})+$)/', function ($arr) {
    return isset($arr[0]) ? "$arr[0]," : "";
  }, $out);

  $out .= ' ' . (!$is_full_description ? $unit[ $i ] : $unit_full[ $i ]);

  return $out;
}

running the following code-lines:

<?php
var_dump(
  human_readable_memory_sizes(982114171659876),
  human_readable_memory_sizes(982114171659876,/*is add commas=*/ true),
  human_readable_memory_sizes(982114171659876,/*is add commas=*/ true,   /*is full description=*/ true),
  human_readable_memory_sizes(982114171659876,/*is add commas=*/ false,  /*is full description=*/ true),
  human_readable_memory_sizes(982114171659876,/*is add commas=*/ false,  /*is full description=*/ true, /*digits limit=*/ 3)
);
?>

will render the following results:

string '893.22763566076537244953 tb' (length=27)
string '893.22,763,566,076,537,244,953 tb' (length=33)
string '893.22,763,566,076,537,244,953 TeraBytes' (length=40)
string '893.22763566076537244953 TeraBytes' (length=34)
string '893.228 TeraBytes' (length=17)