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;
}