未加星标

PHP - Commonly use PHP functions or code snippets in my PHP projects

字体大小 | |
[开发(php) 所属分类 开发(php) | 发布者 店小二04 | 时间 2017 | 作者 红领巾 ] 0人收藏点击收藏

Few years ago, I had been actively developing stuffs inphp and some of my PHP projects source code are backed up to my GitHub . Here is a compilation of commonly use PHP functions in my PHP projects and they are quite helpful in most of the times.

Hash user password <?php function hashUserPassword($salt, $password) { return hash("SHA512", base64_encode(str_rot13(hash("SHA512", str_rot13($salt . $password))))); } ?> Working with string inputs in secure manner <?php // HTML encode string function htmlEncodeString($str) { return htmlspecialchars($str, ENT_QUOTES, 'UTF-8'); } // Trim whitespace including non-breaking space. function trimString($str, $charlist = " \t\n\r\0\x0B\xC2\xA0") { return utf8_trim($str, $charlist); } // Convert \r\n and \r to \n function linebreakString($str) { return str_replace(array( "\r\n", "\r" ), "\n", $str); } // Only accepts alphanumeric and underscore characters. function isValidUsername($str) { return preg_match('/^[a-zA-Z0-9_]+$/', $str); } // Only accepts alphanumeric, underscore, dash, dot and whitespace characters. function isStandardCharacters($str) { return preg_match('/^[a-zA-Z0-9_\-\.\s]+$/', $str); } // Save string input from textarea for address with new line format. function address($str) { return nl2br(stripslashes(rtrim($str))); } // Normalize string. function normalize($str) { return stripslashes(rtrim($str)); } // Sanitize string. function sanitize($string) { return stripslashes(rtrim(htmlspecialchars($string))); } ?> Get Gravatar <?php function getGravatar($email, $default = 'retro', $size = '50') { return "http://www.gravatar.com/avatar/" . md5(strtolower(trim($email))) . "?d=" . urlencode($default) . "&s=" . $size; } ?> Get IP Address <?php function getIp() { $ipaddress = ''; if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ipaddress = $_SERVER['HTTP_CLIENT_IP']; } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR']; } else if ($_SERVER['REMOTE_ADDR']) { $ipaddress = $_SERVER['REMOTE_ADDR']; } else { $ipaddress = 'UNKNOWN'; } return $ipaddress; } ?> Get current page URL <?php function getCurrentPageUrl() { $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")) . $s; $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":" . $_SERVER["SERVER_PORT"]); return $protocol . "://" . $_SERVER['SERVER_NAME'] . $port . $_SERVER['REQUEST_URI']; } ?> Convert timestamp to time-ago style <?php function timeAgo($timestamp) { $timestamp = (int) $timestamp; $current_time = time(); $diff = $current_time - $timestamp; $intervals = array( 'year' => 31556926, 'month' => 2629744, 'week' => 604800, 'day' => 86400, 'hour' => 3600, 'minute' => 60 ); if ($diff == 0) { return 'just now'; } if ($diff < 60) { return $diff == 1 ? $diff . ' second ago' : $diff . ' seconds ago'; } if ($diff >= 60 && $diff < $intervals['hour']) { $diff = floor($diff / $intervals['minute']); return $diff == 1 ? $diff . ' minute ago' : $diff . ' minutes ago'; } if ($diff >= $intervals['hour'] && $diff < $intervals['day']) { $diff = floor($diff / $intervals['hour']); return $diff == 1 ? $diff . ' hour ago' : $diff . ' hours ago'; } if ($diff >= $intervals['day'] && $diff < $intervals['week']) { $diff = floor($diff / $intervals['day']); return $diff == 1 ? $diff . ' day ago' : $diff . ' days ago'; } if ($diff >= $intervals['week'] && $diff < $intervals['month']) { $diff = floor($diff / $intervals['week']); return $diff == 1 ? $diff . ' week ago' : $diff . ' weeks ago'; } if ($diff >= $intervals['month'] && $diff < $intervals['year']) { $diff = floor($diff / $intervals['month']); return $diff == 1 ? $diff . ' month ago' : $diff . ' months ago'; } if ($diff >= $intervals['year']) { $diff = floor($diff / $intervals['year']); return $diff == 1 ? $diff . ' year ago' : $diff . ' years ago'; } } ?> Create HTML anchor to URL, @mention and #hashtag <?php // Make URL, #mention, #hashtag clickable. function makeClickable($input) { $output = preg_replace(array( '/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?“”‘’]))/', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i' ), array( '<a href="$1" target="_blank" rel="nofollow">$1</a>', ' <a href="profile.php?user=$2" target="_blank" rel="nofollow">@$2</a>', ' <a href="hashtag.php?tag=$2" target="_blank" rel="nofollow">#$2</a>' ), $input); return $output; } ?> BB code style, emoticons conversion <?php // (.*?) is a search pattern, will match with emoticon image filename. function bbCode($var) { $search = array( '/\[\:s(.*?)\:\]/is', '/\[\:t(.*?)\:\]/is', '/\[\:o(.*?)\:\]/is', '/\[\:c(.*?)\:\]/is' ); $replace = array( '<img src="img/smileys/s$1.png">', '<img src="img/tuzkiclub/t$1.gif">', '<img src="img/onionclub/o$1.gif">', '<img src="img/cutes/c$1.gif">' ); $result = preg_replace($search, $replace, $var); return $result; } ?> Generate or get random key <?php // $len is a length of the random key. function getRandomKey($len, $readable = false, $hash = false) { $key = ''; if ($hash) $key = substr(sha1(uniqid(rand(), true)), 0, $len); else if ($readable) { $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; for ($i = 0; $i < $len; ++$i) $key .= substr($chars, (mt_rand() % strlen($chars)), 1); } else for ($i = 0; $i < $len; ++$i) $key .= chr(mt_rand(33, 126)); return $key; } ?> Truncate a long text <?php // $length = 0 will retain the original text length. function truncateLongText($text, $length = 0) { if ($length > 0 && strlen($text) > $length) { $tmp = substr($text, 0, $length); $tmp = substr($tmp, 0, strrpos($tmp, ' ')); if (strlen($tmp) >= $length - 3) { $tmp = substr($tmp, 0, strrpos($tmp, ' ')); } $text = $tmp . '...'; } return $text; } ?> Generate or get random password <?php function generateRandomPassword($length = 9, $strength = 0) { $vowels = 'aeuy'; $consonants = 'bdghjmnpqrstvz'; if ($strength >= 1) { $consonants .= 'BDGHJLMNPQRSTVWXZ'; } if ($strength >= 2) { $vowels .= "AEUY"; } if ($strength >= 4) { $consonants .= '23456789'; } if ($strength >= 8) { $vowels .= '@#$%'; } $password = ''; $alt = time() % 2; for ($i = 0; $i < $length; $i++) { if ($alt == 1) { $password .= $consonants[(rand() % strlen($consonants))]; $alt = 0; }

本文开发(php)相关术语:php代码审计工具 php开发工程师 移动开发者大会 移动互联网开发 web开发工程师 软件开发流程 软件开发工程师

主题: PHPHTMLGit360GitHubUTUV
分页:12
转载请注明
本文标题:PHP - Commonly use PHP functions or code snippets in my PHP projects
本站链接:http://www.codesec.net/view/532907.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 开发(php) | 评论(0) | 阅读(84)