非常实用的PHP常用函数汇总

这篇文章主要介绍了非常实用的PHP常用函数,汇总了加密解密、字符串操作、文件操作、SQL注入等函数的实例与用法说明,在PHP项目开发中非常具有实用价值,需要的朋友可以参考下

本文实例总结了一些在php应用开发中常用到的函数,这些函数有字符操作,文件操作及其它的一些操作了,分享给大家供大家参考。具体如下:

1、PHP加密解密

PHP加密和解密函数可以用来加密一些有用的字符串存放在数据库里,并且通过可逆解密字符串,该函数使用了base64和MD5加密和解密。

  1. function encryptDecrypt($key, $string, $decrypt){
  2. if($decrypt){
  3. $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
  4. return $decrypted;
  5. }else{
  6. $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
  7. return $encrypted;
  8. }
  9. }

使用方法如下:

  1. //以下是将字符串“Helloweba欢迎您”分别加密和解密
  2. //加密:
  3. echo encryptDecrypt('password', 'Helloweba欢迎您',0);
  4. //解密:
  5. echo encryptDecrypt('password', 'z0JAx4qMwcF+db5TNbp/xwdUM84snRsXvvpXuaCa4Bk=',1);

2、PHP生成随机字符串

当我们需要生成一个随机名字,临时密码等字符串时可以用到下面的函数:

  1. function generateRandomString($length = 10) {
  2. $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  3. $randomString = '';
  4. for ($i = 0; $i < $length; $i++) {
  5. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  6. }
  7. return $randomString;
  8. }

使用方法如下:

echo generateRandomString(20);

3、PHP获取文件扩展名(后缀)

以下函数可以快速获取文件的扩展名即后缀。代码如下:

  1. function getExtension($filename){
  2. $myext = substr($filename, strrpos($filename, '.'));
  3. return str_replace('.','',$myext);
  4. }

使用方法如下:

$filename = '我的文档.doc';

echo getExtension($filename);

4、PHP获取文件大小并格式化

以下使用的函数可以获取文件的大小,并且转换成便于阅读的KB,MB等格式。代码如下:

  1. function formatSize($size) {
  2. $sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
  3. if ($size == 0) {
  4. return('n/a');
  5. } else {
  6. return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]);
  7. }
  8. }

使用方法如下:

$thefile = filesize('test_file.mp3');

echo formatSize($thefile);

5、PHP替换标签字符

有时我们需要将字符串、模板标签替换成指定的内容,可以用到下面的函数:

  1. function stringParser($string,$replacer){
  2. $result = str_replace(array_keys($replacer), array_values($replacer),$string);
  3. return $result;
  4. }

使用方法如下:

  1. $string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
  2. $replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '<br />');
  3. echo stringParser($string,$replace_array);

6、PHP列出目录下的文件名

如果你想列出目录下的所有文件,使用以下代码即可:

  1. function listDirFiles($DirPath){
  2. if($dir = opendir($DirPath)){
  3. while(($file = readdir($dir))!== false){
  4. if(!is_dir($DirPath.$file))
  5. {
  6. echo "filename: $file<br />";
  7. }
  8. }
  9. }
  10. }

使用方法如下:

listDirFiles('home/some_folder/');

7、PHP获取当前页面URL

以下函数可以获取当前页面的URL,不管是http还是https。代码如下:

  1. function curPageURL() {
  2. $pageURL = 'http';
  3. if (!emptyempty($_SERVER['HTTPS'])) {$pageURL .= "s";}
  4. $pageURL .= "://";
  5. if ($_SERVER["SERVER_PORT"] != "80") {
  6. $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  7. } else {
  8. $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
  9. }
  10. return $pageURL;
  11. }

使用方法如下:

echo curPageURL();

8、PHP强制下载文件

有时我们不想让浏览器直接打开文件,如PDF文件,而是要直接下载文件,那么以下函数可以强制下载文件,函数中使用了application/octet-stream头类型。代码如下:

  1. function download($filename){
  2. if ((isset($filename))&&(file_exists($filename))){
  3. header("Content-length: ".filesize($filename));
  4. header('Content-Type: application/octet-stream');
  5. header('Content-Disposition: attachment; filename="' . $filename . '"');
  6. readfile("$filename");
  7. } else {
  8. echo "Looks like file does not exist!";
  9. }
  10. }

使用方法如下:

download('/down/test_45f73e852.zip');

9、PHP截取字符串长度

我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用...表示,以下函数可以满足你的需求。代码如下:

  1. /*
  2. Utf-8、gb2312都支持的汉字截取函数
  3. cut_str(字符串, 截取长度, 开始长度, 编码);
  4. 编码默认为 utf-8
  5. 开始长度默认为 0
  6. */
  7. function cutStr($string, $sublen, $start = 0, $code = 'UTF-8'){
  8. if($code == 'UTF-8'){
  9. $pa = "/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/";
  10. preg_match_all($pa, $string, $t_string);
  11. if(count($t_string[0]) - $start > $sublen) return join('', array_slice($t_string[0], $start, $sublen))."...";
  12. return join('', array_slice($t_string[0], $start, $sublen));
  13. }else{
  14. $start = $start*2;
  15. $sublen = $sublen*2;
  16. $strlen = strlen($string);
  17. $tmpstr = '';
  18. for($i=0; $i<$strlen; $i++){
  19. if($i>=$start && $i<($start+$sublen)){
  20. if(ord(substr($string, $i, 1))>129){
  21. $tmpstr.= substr($string, $i, 2);
  22. }else{
  23. $tmpstr.= substr($string, $i, 1);
  24. }
  25. }
  26. if(ord(substr($string, $i, 1))>129) $i++;
  27. }
  28. if(strlen($tmpstr)<$strlen ) $tmpstr.= "...";
  29. return $tmpstr;
  30. }
  31. }

使用方法如下:

$str = "jQuery插件实现的加载图片和页面效果";

echo cutStr($str,16);

10、PHP获取客户端真实IP

我们经常要用数据库记录用户的IP,以下代码可以获取客户端真实的IP:

  1. //获取用户真实IP
  2. function getIp() {
  3. if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  4. $ip = getenv("HTTP_CLIENT_IP");
  5. else
  6. if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
  7. $ip = getenv("HTTP_X_FORWARDED_FOR");
  8. else
  9. if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  10. $ip = getenv("REMOTE_ADDR");
  11. else
  12. if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  13. $ip = $_SERVER['REMOTE_ADDR'];
  14. else
  15. $ip = "unknown";
  16. return ($ip);
  17. }

使用方法如下:

echo getIp();

11、PHP防止SQL注入

我们在查询数据库时,出于安全考虑,需要过滤一些非法字符防止SQL恶意注入,请看一下函数:

  1. function injCheck($sql_str) {
  2. $check = preg_match('/select|insert|update|delete|'|/*|*|../|./|union|into|load_file|outfile/', $sql_str);
  3. if ($check) {
  4. echo '非法字符!!';
  5. exit;
  6. } else {
  7. return $sql_str;
  8. }
  9. }

使用方法如下:

echo injCheck('1 or 1=1');

12、PHP页面提示与跳转

我们在进行表单操作时,有时为了友好需要提示用户操作结果,并跳转到相关页面,请看以下函数:

  1. function message($msgTitle,$message,$jumpUrl){
  2. $str = '<!DOCTYPE HTML>';
  3. $str .= '<html>';
  4. $str .= '<head>';
  5. $str .= '<meta charset="utf-8">';
  6. $str .= '<title>页面提示</title>';
  7. $str .= '<style type="text/css">';
  8. $str .= '*{margin:0; padding:0}a{color:#369; text-decoration:none;}a:hover{text-decoration:underline}body{height:100%; font:12px/18px Tahoma, Arial, sans-serif; color:#424242; background:#fff}.message{width:450px; height:120px; margin:16% auto; border:1px solid #99b1c4; background:#ecf7fb}.message h3{height:28px; line-height:28px; background:#2c91c6; text-align:center; color:#fff; font-size:14px}.msg_txt{padding:10px; margin-top:8px}.msg_txt h4{line-height:26px; font-size:14px}.msg_txt h4.red{color:#f30}.msg_txt p{line-height:22px}';
  9. $str .= '</style>';
  10. $str .= '</head>';
  11. $str .= '<body>';
  12. $str .= '<div class="message">';
  13. $str .= '<h3>'.$msgTitle.'</h3>';
  14. $str .= '<div class="msg_txt">';
  15. $str .= '<h4 class="red">'.$message.'</h4>';
  16. $str .= '<p>系统将在 <span >3</span> 秒后自动跳转,如果不想等待,直接点击 <a href="{$jumpUrl}">这里</a> 跳转</p>';
  17. $str .= "<script>setTimeout('location.replace('".$jumpUrl."')',2000)</script>";
  18. $str .= '</div>';
  19. $str .= '</div>';
  20. $str .= '</body>';
  21. $str .= '</html>';
  22. echo $str;
  23. }

使用方法如下:

message('操作提示','操作成功!','https://www.phpfensi.com/');

13、PHP计算时长

我们在处理时间时,需要计算当前时间距离某个时间点的时长,如计算客户端运行时长,通常用hh:mm:ss表示。代码如下:

  1. function changeTimeType($seconds) {
  2. if ($seconds > 3600) {
  3. $hours = intval($seconds / 3600);
  4. $minutes = $seconds % 3600;
  5. $time = $hours . ":" . gmstrftime('%M:%S', $minutes);
  6. } else {
  7. $time = gmstrftime('%H:%M:%S', $seconds);
  8. }
  9. return $time;
  10. }

使用方法如下:

$seconds = 3712;

echo changeTimeType($seconds);

希望本文所述对大家的PHP程序设计有所帮助。

下面特为大家加点料希望大家能喜欢:

本文汇总了常用的PHP函数,包括获取客户端IP,字符串截取,下载等,详情请查看如下代码:

  1. <?php
  2. /**
  3. * 获取客户端IP
  4. * @return [string] [description]
  5. */
  6. function getClientIp() {
  7. $ip = NULL;
  8. if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  9. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  10. $pos = array_search('unknown',$arr);
  11. if(false !== $pos) unset($arr[$pos]);
  12. $ip = trim($arr[0]);
  13. }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
  14. $ip = $_SERVER['HTTP_CLIENT_IP'];
  15. }elseif (isset($_SERVER['REMOTE_ADDR'])) {
  16. $ip = $_SERVER['REMOTE_ADDR'];
  17. }
  18. // IP地址合法验证
  19. $ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
  20. return $ip;
  21. }
  22. /**
  23. * 获取在线IP
  24. * @return String
  25. */
  26. function getOnlineIp($format=0) {
  27. global $S_GLOBAL;
  28. if(emptyempty($S_GLOBAL['onlineip'])) {
  29. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  30. $onlineip = getenv('HTTP_CLIENT_IP');
  31. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  32. $onlineip = getenv('HTTP_X_FORWARDED_FOR');
  33. } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  34. $onlineip = getenv('REMOTE_ADDR');
  35. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  36. $onlineip = $_SERVER['REMOTE_ADDR'];
  37. }
  38. preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
  39. $S_GLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
  40. }
  41. if($format) {
  42. $ips = explode('.', $S_GLOBAL['onlineip']);
  43. for($i=0;$i<3;$i++) {
  44. $ips[$i] = intval($ips[$i]);
  45. }
  46. return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
  47. } else {
  48. return $S_GLOBAL['onlineip'];
  49. }
  50. }
  51. /**
  52. * 获取url
  53. * @return [type] [description]
  54. */
  55. function getUrl(){
  56. $pageURL = 'http';
  57. if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
  58. $pageURL .= "s";
  59. }
  60. $pageURL .= "://";
  61. if ($_SERVER["SERVER_PORT"] != "80") {
  62. $pageURL .= $_SERVER["HTTP_HOST"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  63. } else {
  64. $pageURL .= $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
  65. }
  66. return $pageURL;
  67. }
  68. /**
  69. * 获取当前站点的访问路径根目录
  70. * @return [type] [description]
  71. */
  72. function getSiteUrl() {
  73. $uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
  74. return 'http://'.$_SERVER['HTTP_HOST'].substr($uri, 0, strrpos($uri, '/')+1);
  75. }
  76. /**
  77. * 字符串截取,支持中文和其他编码
  78. * @param [string] $str [字符串]
  79. * @param integer $start [起始位置]
  80. * @param integer $length [截取长度]
  81. * @param string $charset [字符串编码]
  82. * @param boolean $suffix [是否有省略号]
  83. * @return [type] [description]
  84. */
  85. function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true) {
  86. if(function_exists("mb_substr")) {
  87. return mb_substr($str, $start, $length, $charset);
  88. } elseif(function_exists('iconv_substr')) {
  89. return iconv_substr($str,$start,$length,$charset);
  90. }
  91. $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
  92. $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
  93. $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
  94. $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
  95. preg_match_all($re[$charset], $str, $match);
  96. $slice = join("",array_slice($match[0], $start, $length));
  97. if($suffix) {
  98. return $slice."…";
  99. }
  100. return $slice;
  101. }
  102. /**
  103. * php 实现js escape 函数
  104. * @param [type] $string [description]
  105. * @param string $encoding [description]
  106. * @return [type] [description]
  107. */
  108. function escape($string, $encoding = 'UTF-8'){
  109. $return = null;
  110. for ($x = 0; $x < mb_strlen($string, $encoding);$x ++)
  111. {
  112. $str = mb_substr($string, $x, 1, $encoding);
  113. if (strlen($str) > 1) { // 多字节字符
  114. $return .= "%u" . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding)));
  115. } else {
  116. $return .= "%" . strtoupper(bin2hex($str));
  117. }
  118. }
  119. return $return;
  120. }
  121. /**
  122. * php 实现 js unescape函数
  123. * @param [type] $str [description]
  124. * @return [type] [description]
  125. */
  126. function unescape($str) {
  127. $str = rawurldecode($str);
  128. preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
  129. $ar = $r[0];
  130. foreach($ar as $k=>$v) {
  131. if(substr($v,0,2) == "%u"){
  132. $ar[$k] = iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4)));
  133. } elseif(substr($v,0,3) == "") {
  134. $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
  135. } elseif(substr($v,0,2) == "&#") {
  136. echo substr($v,2,-1)."";
  137. $ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));
  138. }
  139. }
  140. return join("",$ar);
  141. }
  142. /**
  143. * 数字转人名币
  144. * @param [type] $num [description]
  145. * @return [type] [description]
  146. */
  147. function num2rmb ($num) {
  148. $c1 = "零壹贰叁肆伍陆柒捌玖";
  149. $c2 = "分角元拾佰仟万拾佰仟亿";
  150. $num = round($num, 2);
  151. $num = $num * 100;
  152. if (strlen($num) > 10) {
  153. return "oh,sorry,the number is too long!";
  154. }
  155. $i = 0;
  156. $c = "";
  157. while (1) {
  158. if ($i == 0) {
  159. $n = substr($num, strlen($num)-1, 1);
  160. } else {
  161. $n = $num % 10;
  162. }
  163. $p1 = substr($c1, 3 * $n, 3);
  164. $p2 = substr($c2, 3 * $i, 3);
  165. if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
  166. $c = $p1 . $p2 . $c;
  167. } else {
  168. $c = $p1 . $c;
  169. }
  170. $i = $i + 1;
  171. $num = $num / 10;
  172. $num = (int)$num;
  173. if ($num == 0) {
  174. break;
  175. }
  176. }
  177. $j = 0;
  178. $slen = strlen($c);
  179. while ($j < $slen) {
  180. $m = substr($c, $j, 6);
  181. if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
  182. $left = substr($c, 0, $j);
  183. $right = substr($c, $j + 3);
  184. $c = $left . $right;
  185. $j = $j-3;
  186. $slen = $slen-3;
  187. }
  188. $j = $j + 3;
  189. }
  190. if (substr($c, strlen($c)-3, 3) == '零') {
  191. $c = substr($c, 0, strlen($c)-3);
  192. } // if there is a '0' on the end , chop it out
  193. return $c . "整";
  194. }
  195. /**
  196. * 特殊的字符
  197. * @param [type] $str [description]
  198. * @return [type] [description]
  199. */
  200. function makeSemiangle($str) {
  201. $arr = array(
  202. '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
  203. '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
  204. 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
  205. 'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
  206. 'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
  207. 'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
  208. 'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
  209. 'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
  210. 'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
  211. 'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
  212. 'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
  213. 't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
  214. 'y' => 'y', 'z' => 'z',
  215. '(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
  216. '】' => ']', '〖' => '[', '〗' => ']', '{' => '{', '}' => '}', '《' => '<',
  217. '》' => '>',
  218. '%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
  219. ':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
  220. ';' => ';', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
  221. '”' => '"', '“' => '"', ''' => '`', '‘' => '`', '|' => '|', '〃' => '"',
  222. ' ' => ' ','.' => '.');
  223. return strtr($str, $arr);
  224. }
  225. /**
  226. * 下载
  227. * @param [type] $filename [description]
  228. * @param string $dir [description]
  229. * @return [type] [description]
  230. */
  231. function downloads($filename,$dir='./'){
  232. $filepath = $dir.$filename;
  233. if (!file_exists($filepath)){
  234. header("Content-type: text/html; charset=utf-8");
  235. echo "File not found!";
  236. exit;
  237. } else {
  238. $file = fopen($filepath,"r");
  239. Header("Content-type: application/octet-stream");
  240. Header("Accept-Ranges: bytes");
  241. Header("Accept-Length: ".filesize($filepath));
  242. Header("Content-Disposition: attachment; filename=".$filename);
  243. echo fread($file, filesize($filepath));
  244. fclose($file);
  245. }
  246. }
  247. /**
  248. * 创建一个目录树
  249. * @param [type] $dir [description]
  250. * @param integer $mode [description]
  251. * @return [type] [description]
  252. */
  253. function mkdirs($dir, $mode = 0777) {
  254. if (!is_dir($dir)) {
  255. mkdirs(dirname($dir), $mode);
  256. return mkdir($dir, $mode);
  257. }
  258. return true;
  259. }