PHP

This page is a collection of various PHP code snippets.

Base64 Functions

/**
    * Decode base64 data
    *
    * @param  string  $data
    *
    */
function decode_base64($data) {

    $data = explode(',', $data, 2);

    $decoded = base64_decode($data[1]);

    return $decoded;
}

/**
    * Validate base64 data is image/jpeg
    *
    * @param  string  $data
    * @param  string  $mimetype
    *
    */
function validate_base64($data, $mimetype) {

    if ('image/jpeg' == $mimetype)
    {
        $img = imagecreatefromstring($data);
        if (!$img) {
            return false;
        }

        imagejpeg($img, 'tmp.jpg');
        $info = getimagesize('tmp.jpg');

        unlink('tmp.jpg');

        if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
            return true;
        }

        return false;
    }
}
Example of how to use the base64 functions above:
$file = [];
$file['content'] = decode_base64($data);

// validate the decoded base64 string
if (!validate_base64($file['content'], 'image/jpeg'))
{
    // invalid base64 'image/jpeg'
    $error =  'INVALID_DATA';

    return false;
}

Request

/**
    * use the request path
    * to create an array of URL segments
    */
$request_path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $request_path);

echo '<pre>';
print_r($request_path);
echo '</pre>';

/**
    * get the remaining characters after the last forward slash
    *
    * @param  string  $path
    *
    * @return string
    *
    */
function last_segment($path) {
    return substr($path, strrpos($path, "/")+1);
}

Date/Time Functions

/** 
    * to default date object to GMT, add this
    * either inside the function or outer scope
    */
date_default_timezone_set("GMT");

//return mysql format datetime string
/**
    * @param  object  $date
    *
    * @return string  mysql format datetime
    * @return bool (false) if error
    *
    */
function mysql_datetime($date) {
    return $date->format('Y-m-d H:i:s');
}

//return gmt date object
function strtodate($str) {
    $date = date_create();        
    return date_timestamp_set($date, strtotime($str));
}

String Functions

/**
    * is string null or empty
    */
function null_or_empty($str){
    return (!isset($str) || trim($str)==='');
}

/**
    * does string start with sub-string
    *
    * @param string $haystack a string
    * @param string $needle a sub-string to search for
    * @return bool
    *
    */
function startsWith($haystack, $needle)
{
    return !strncmp($haystack, $needle, strlen($needle));
}
/**
    * does string end with sub-string
    */
function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }
    return (substr($haystack, -$length) === $needle);
}

/**
    * replace first occurrence of sub-string  
    *
    * @param string $search a sub-string to search for
    * @param string $replace a sub-string to replace sub-string with
    * @param string $str a string
    * @return string
    * 
    */
function str_replace_first($search, $replace, $str) {
    $pos = strpos($str, $search);
    if ($pos !== false) {
        $str = substr_replace($str, $replace, $pos, strlen($search));
    }
    return $str;
}

/**
    * replace last occurrence of sub-string  
    * same as str_replace_first above with words reversed
    */
function str_replace_last($search, $replace, $str) {
    //reverse the words
    $str = implode(' ',array_reverse(explode(' ',$str)));
    $pos = strpos($str, $search);
    if ($pos !== false) {
        $str = substr_replace($str, $replace, $pos, strlen($search));
    }
    return $str;
}

//remove adjacent hyphens, return single hyphens
function rm_adj_hyphen($str) {
    trim(preg_replace('/-+/', '-', $str), '-');
}
    
//remove adjacent spaces, return single spaces
function rm_adj_space($str) {    
    preg_replace('!\s+!', ' ', $str);
}

//remove numbers from a string    
function rm_number($str) {
    return preg_replace('/[0-9]+/', '', $str);
}

//truncate to word limit and append ellipsis by default
//if no trailing ellipsis desired, pass empty string for last parameter
function limit_words($str, $max_words, $append = '…') {
    $str_array = explode(' ',$str);
    if(count($str_array) > $max_words && $max_words > 0)
        $str = implode(' ',array_slice($str_array, 0, $max_words)).$append;
    return $str;
}
comments powered by Disqus