A short list of useful PHP functions I use

I’ve decided to share a short list of php functions that I think are quite handy in specific cases. I will try to update it from once in a while and add more functions that I think could be useful.

PHP Functions – the list

//Get the real ip address of your visitor
function get_ip() {
    $server = array(
        'HTTP_CLIENT_IP', 
        'HTTP_X_FORWARDED_FOR', 
        'HTTP_X_FORWARDED', 
        'HTTP_X_CLUSTER_CLIENT_IP', 
        'HTTP_FORWARDED_FOR', 
        'HTTP_FORWARDED', 
        'REMOTE_ADDR'
    );
    foreach ($server as $index) {
        if (isset($_SERVER[$index]) || array_key_exists($index, $_SERVER) === true) {
            foreach (explode(',', $_SERVER[$index]) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP) !== false) {
                    return $ip;
                }
            }
        }
    }
}

/*****************************************************************/

//For easier debugging
function debug($var) {
    echo "<pre>";
    print_r($var);
    echo "</pre>";
}

/*****************************************************************/

//This method is helpful when you want to create a new array from the existing array keys
function reorder_array($array, $key, $value = false) {
    $new = array();
    for ($i = 0; $i < count($array); $i++) {
        if (isset($array[$i][$key])) {
            if (!$value) {
                $new[$array[$i][$key]] = $array[$i];
            } else {
                $new[$array[$i][$key]] = $array[$i][$value];
            }
        }
    }
    return $new;
}

/*****************************************************************/

//A function to generate a random string of characters
function random_char_string($length = 10) {
    $set = 'abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $string = '';
    for ($i = 0; $i < $length; $i++) {
        $string .= $set[rand(0, 61)];
    }
    return $string;
}
echo generate_path(15); //could output something like Wxo1Xk74MhsQjoq

/*****************************************************************/

//A little function to generate a salt string for password hashing
function salt($max = 64) {
    $salt = '';
    for ($i = 0; $i < $max; $i++) {
        $salt.=chr(rand(33, 126));
    }
    return $salt;
}
echo salt(); // could output Kmm3C^{CbfnSN`/6RKt8Yon$|&'jd*d1wRC;2?^t'NHT0Vib"^zZOi^Lod7Tm{de

/*****************************************************************/
//Shorten a string and append '...' if the length of that string is less than the number of characters allowed
function shorten($str, $limit = 30) {
    if (strlen($str) > $limit) {
        return substr($str, 0, $limit) . '...';
    } else {
        return $str;
    }
}

/*****************************************************************/
//Properly escape JSON values
function escape_json_string($val) {
    $val = str_replace('\\', '\\\\', $val);
    $val = str_replace("\n", '\\n', $val);
    $val = str_replace("\r", '\\r', $val);
    $val = str_replace("\t", '\\t', $val);
    $val = str_replace("\v", '\\v', $val);
    $val = str_replace("\f", '\\f', $val);
    $val = str_replace("\n", '\\n', $val);
    $val = str_replace("\n", '\\n', $val);
    return $val;
}

EmberJS History with Undo-Redo

The project I’m currently working on requires an undo/redo implementation. We’re using EmberJS so I had to write a little script to add this sort of functionality. It uses ember’s addBeforeObserver and addObserver to track when the history states should be changed, but in addition it is possible to disable/enable adding states. I this is a quite cool feature which allows to add more flexibility to your application by enabling emberjs history.
This is an example usage.

App = Ember.Application.create({});

obj = Ember.Object.create(Ember.History, {
 _trackProperties: 'width height list'.w(),
 width: '100px',
 height: '50px',
 list: ['item3','carrot','car']
});

obj2 = Ember.Object.create(Ember.History, {
 _trackProperties: 'name surname'.w(),
 name: 'Ignas',
 surname: 'Bernotas',
});

obj2.set('name','Matthew');
obj.set('height','100px');
obj.set('list', ['item1']);
obj2.set('surname', 'Parry');

History.undo(); // surname is now back to Bernotas
History.undo(); // list is now back to ['item3','carrot','car']
History.undo(); // height is now 50px
History.undo(); // name is now Ignas
History.redo(); // name is now Matthew
History.redo(); // height 100px
History.redo(); // list is ['item1'] again
History.redo(); // surname is Parry again

The full code can be found on github