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

代码如下:

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

<?php
/**
* 获取客户端IP
* @return [string] [description]
*/
function getClientIp() {
$ip = NULL;
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
$pos = array_search('unknown',$arr);
if(false !== $pos) unset($arr[$pos]);
$ip = trim($arr[0]);
}elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ip = $_SERVER['REMOTE_ADDR'];
}
// IP地址合法验证
$ip = (false !== ip2long($ip)) ? $ip : '0.0.0.0';
return $ip;
}

/**
* 获取在线IP
* @return String
*/
function getOnlineIp($format=0) {
global $S_GLOBAL;
if(empty($S_GLOBAL['onlineip'])) {
if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
$onlineip = getenv('HTTP_CLIENT_IP');
} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
$onlineip = getenv('HTTP_X_FORWARDED_FOR');
} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
$onlineip = getenv('REMOTE_ADDR');
} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
$onlineip = $_SERVER['REMOTE_ADDR'];
}
preg_match("/[\d\.]{7,15}/", $onlineip, $onlineipmatches);
$S_GLOBAL['onlineip'] = $onlineipmatches[0] ? $onlineipmatches[0] : 'unknown';
}

if($format) {
$ips = explode('.', $S_GLOBAL['onlineip']);
for($i=0;$i<3;$i++) {
$ips[$i] = intval($ips[$i]);
}
return sprintf('%03d%03d%03d', $ips[0], $ips[1], $ips[2]);
} else {
return $S_GLOBAL['onlineip'];
}
}



/**
* 获取url
* @return [type] [description]
*/
function getUrl(){
$pageURL = 'http';
if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
$pageURL .= "s";
}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["HTTP_HOST"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
}
return $pageURL;
}

/**
* 获取当前站点的访问路径根目录
* @return [type] [description]
*/
function getSiteUrl() {
$uri = $_SERVER['REQUEST_URI']?$_SERVER['REQUEST_URI']:($_SERVER['PHP_SELF']?$_SERVER['PHP_SELF']:$_SERVER['SCRIPT_NAME']);
return 'http://'.$_SERVER['HTTP_HOST'].substr($uri, 0, strrpos($uri, '/')+1);
}



/**
* 字符串截取,支持中文和其他编码
* @param [string] $str  [字符串]
* @param integer $start [起始位置]
* @param integer $length [截取长度]
* @param string $charset [字符串编码]
* @param boolean $suffix [是否有省略号]
* @return [type]   [description]
*/
function msubstr($str, $start=0, $length=15, $charset="utf-8", $suffix=true) {
if(function_exists("mb_substr")) {
return mb_substr($str, $start, $length, $charset);
} elseif(function_exists('iconv_substr')) {
return iconv_substr($str,$start,$length,$charset);
}
$re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
$re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
$re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
$re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
preg_match_all($re[$charset], $str, $match);
$slice = join("",array_slice($match[0], $start, $length));
if($suffix) {
return $slice."…";
}
return $slice;
}

/**
* php 实现js escape 函数
* @param [type] $string [description]
* @param string $encoding [description]
* @return [type]   [description]
*/
function escape($string, $encoding = 'UTF-8'){
$return = null;
for ($x = 0; $x < mb_strlen($string, $encoding);$x ++)
{
$str = mb_substr($string, $x, 1, $encoding);
if (strlen($str) > 1) { // 多字节字符
$return .= "%u" . strtoupper(bin2hex(mb_convert_encoding($str, 'UCS-2', $encoding)));
} else {
$return .= "%" . strtoupper(bin2hex($str));
}
}
return $return;
}
/**
* php 实现 js unescape函数
* @param [type] $str [description]
* @return [type]  [description]
*/
function unescape($str) {
$str = rawurldecode($str);
preg_match_all("/(?:%u.{4})|.{4};|&#\d+;|.+/U",$str,$r);
$ar = $r[0];
foreach($ar as $k=>$v) {
if(substr($v,0,2) == "%u"){
$ar[$k] = iconv("UCS-2","utf-8//IGNORE",pack("H4",substr($v,-4)));
} elseif(substr($v,0,3) == "") {
$ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1)));
} elseif(substr($v,0,2) == "&#") {
echo substr($v,2,-1)."";
$ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1)));
}
}
return join("",$ar);
}

/**
* 数字转人名币
* @param [type] $num [description]
* @return [type]  [description]
*/
function num2rmb ($num) {
$c1 = "零壹贰叁肆伍陆柒捌玖";
$c2 = "分角元拾佰仟万拾佰仟亿";
$num = round($num, 2);
$num = $num * 100;
if (strlen($num) > 10) {
return "oh,sorry,the number is too long!";
}
$i = 0;
$c = "";
while (1) {
if ($i == 0) {
$n = substr($num, strlen($num)-1, 1);
} else {
$n = $num % 10;
}
$p1 = substr($c1, 3 * $n, 3);
$p2 = substr($c2, 3 * $i, 3);
if ($n != '0' || ($n == '0' && ($p2 == '亿' || $p2 == '万' || $p2 == '元'))) {
$c = $p1 . $p2 . $c;
} else {
$c = $p1 . $c;
}
$i = $i + 1;
$num = $num / 10;
$num = (int)$num;
if ($num == 0) {
break;
}
}
$j = 0;
$slen = strlen($c);
while ($j < $slen) {
$m = substr($c, $j, 6);
if ($m == '零元' || $m == '零万' || $m == '零亿' || $m == '零零') {
$left = substr($c, 0, $j);
$right = substr($c, $j + 3);
$c = $left . $right;
$j = $j-3;
$slen = $slen-3;
}
$j = $j + 3;
}
if (substr($c, strlen($c)-3, 3) == '零') {
$c = substr($c, 0, strlen($c)-3);
} // if there is a '0' on the end , chop it out
return $c . "整";
}

/**
* 特殊的字符
* @param [type] $str [description]
* @return [type]  [description]
*/
function makeSemiangle($str) {
$arr = array(
'0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4',
'5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9',
'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', 'E' => 'E',
'F' => 'F', 'G' => 'G', 'H' => 'H', 'I' => 'I', 'J' => 'J',
'K' => 'K', 'L' => 'L', 'M' => 'M', 'N' => 'N', 'O' => 'O',
'P' => 'P', 'Q' => 'Q', 'R' => 'R', 'S' => 'S', 'T' => 'T',
'U' => 'U', 'V' => 'V', 'W' => 'W', 'X' => 'X', 'Y' => 'Y',
'Z' => 'Z', 'a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd',
'e' => 'e', 'f' => 'f', 'g' => 'g', 'h' => 'h', 'i' => 'i',
'j' => 'j', 'k' => 'k', 'l' => 'l', 'm' => 'm', 'n' => 'n',
'o' => 'o', 'p' => 'p', 'q' => 'q', 'r' => 'r', 's' => 's',
't' => 't', 'u' => 'u', 'v' => 'v', 'w' => 'w', 'x' => 'x',
'y' => 'y', 'z' => 'z',
'(' => '(', ')' => ')', '〔' => '[', '〕' => ']', '【' => '[',
'】' => ']', '〖' => '[', '〗' => ']', '{' => '{', '}' => '}', '《' => '<',
'》' => '>',
'%' => '%', '+' => '+', '—' => '-', '-' => '-', '~' => '-',
':' => ':', '。' => '.', '、' => ',', ',' => '.', '、' => '.',
';' => ';', '?' => '?', '!' => '!', '…' => '-', '‖' => '|',
'”' => '"', '“' => '"', ''' => '`', '' => '`', '' => '|', '' => '"',
' ' => ' ','.' => '.');
return strtr($str, $arr);
}

/**
* 下载
* @param [type] $filename [description]
* @param string $dir  [description]
* @return [type]   [description]
*/
function downloads($filename,$dir='./'){
$filepath = $dir.$filename;
if (!file_exists($filepath)){
header("Content-type: text/html; charset=utf-8");
echo "File not found!";
exit;
} else {
$file = fopen($filepath,"r");
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length: ".filesize($filepath));
Header("Content-Disposition: attachment; filename=".$filename);
echo fread($file, filesize($filepath));
fclose($file);
}
}

/**
* 创建一个目录树
* @param [type] $dir [description]
* @param integer $mode [description]
* @return [type]  [description]
*/
function mkdirs($dir, $mode = 0777) {
if (!is_dir($dir)) {
mkdirs(dirname($dir), $mode);
return mkdir($dir, $mode);
}
return true;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
作者和贡献者 I. 入门指引 1. 简介 2. 简明教程 II. 安装与配置 3. 安装前需要考虑的事项 4. Unix 系统下的安装 5. Mac OS X 系统下的安装 6. Windows 系统下的安装 7. PECL 扩展库安装 8. 还有问题? 9. 运行时配置 III. 语言参考 10. 基本语法 11. 类型 12. 变量 13. 常量 14. 表达式 15. 运算符 16. 流程控制 17. 函数 18. 类与对象(PHP 4) 19. 类与对象(PHP 5) 20. 异常处理 21. 引用的解释 IV. 安全 22. 简介 23. 总则 24. 以 CGI 模式安装时 25. 以 Apache 模块安装时 26. 文件系统安全 27. 数据库安全 28. 错误报告 29. 使用 Register Globals 30. 用户提交的数据 31. 魔术引号 32. 隐藏 PHP 33. 保持更新 V. 特点 34. 用 PHP 进行 HTTP 认证 35. cookies 36. 会话 37. 处理 XForms 38. 文件上传处理 39. 使用远程文件 40. 连接处理 41. 数据库永久连接 42. 安全模式 43. PHP 的命令行模式 VI. 函数参考 I. .NET 函数 II. Advanced PHP debugger III. Alternative PHP Cache IV. Apache 特有函数 V. Array 数组函数 VI. Aspell 函数(已废弃) VII. BC math 高精度数学函数 VIII. Bzip2 压缩函数 IX. Calendar 日历函数 X. CCVS API Functions [deprecated] XI. Character Type Functions XII. Classes/Objects 类/对象函数 XIII. Classkit Functions XIV. ClibPDF Functions XV. COM 和 .Net(Windows)函数 XVI. Crack Functions XVII. Credit Mutuel CyberMUT functions XVIII. CURL, Client URL Library Functions XIX. Cybercash Payment Functions XX. Cyrus IMAP administration Functions XXI. Database (dbm-style) Abstraction Layer Functions XXII. Date/Time 日期/时间函数 XXIII. DB++ Functions XXIV. dBase Functions XXV. DBM Functions [deprecated] XXVI. dbx Functions XXVII. Direct IO Functions XXVIII. Directory 目录函数 XXIX. DOM Functions XXX. DOM XML Functions XXXI. Error Handling and Logging Functions XXXII. Exif Functions XXXIII. File Alteration Monitor Functions XXXIV. filePro Functions XXXV. Filesystem 文件系统函数 XXXVI. Firebird/InterBase Functions XXXVII. Firebird/Interbase Functions (PDO_FIREBIRD) XXXVIII. Forms Data Format Functions XXXIX. FriBiDi Functions XL. FrontBase Functions XLI. FTP 函数 XLII. Function Handling Functions XLIII. Gettext XLIV. GMP Functions XLV. GNU Readline XLVI. GNU Recode Functions XLVII. HTTP 函数 XLVIII. Hyperwave API Functions XLIX. Hyperwave Functions L. IBM DB2, Cloudscape and Apache Derby Functions LI. ICAP Functions [deprecated] LII. iconv Functions LIII. ID3 Functions LIV. IIS Administration Functions LV. Image 图像函数 LVI. IMAP, POP3 and NNTP Functions LVII. Informix Functions LVIII. Ingres II Functions LIX. IRC Gateway Functions LX. KADM5 LXI. LDAP Functions LXII. libxml Functions LXIII. Lotus Notes Functions LXIV. LZF Functions LXV. Mail Functions LXVI. mailparse Functions LXVII. Math 数学函数 LXVIII. MaxDB PHP Extension LXIX. MCAL Functions LXX. Mcrypt Encryption Functions LXXI. MCVE Payment Functions LXXII. Memcache Functions LXXIII. Mhash Functions LXXIV. Microsoft SQL Server and Sybase Functions (PDO_DBLIB) LXXV. Microsoft SQL Server Functions LXXVI. Mimetype Functions LXXVII. Ming functions for Flash LXXVIII. Miscellaneous Functions LXXIX. mnoGoSearch Functions LXXX. Mohawk Software Session Handler Functions LXXXI. mSQL Functions LXXXII. Multibyte String Functions LXXXIII. muscat Functions LXXXIV. MySQL 函数 LXXXV. MySQL Functions (PDO_MYSQL) LXXXVI. MySQL Improved Extension LXXXVII. Ncurses Terminal Screen Control Functions LXXXVIII. Network Functions LXXXIX. Net_Gopher XC. NSAPI-specific Functions XCI. Object Aggregation/Composition Functions XCII. Object property and method call overloading XCIII. ODBC and DB2 functions (PDO_ODBC) XCIV. ODBC Functions (Unified) XCV. oggvorbis XCVI. OpenAL Audio Bindings XCVII. OpenSSL Functions XCVIII. Oracle 函数 XCIX. Oracle Functions (PDO_OCI) C. Oracle 函数(已废弃) CI. Output Control 输出控制函数 CII. Ovrimos SQL Functions CIII. Paradox File Access CIV. Parsekit Functions CV. PDF functions CVI. PDO Functions CVII. PHP / Java Integration CVIII. PHP bytecode Compiler CIX. PHP Options&Information CX. POSIX Functions CXI. PostgreSQL 数据库函数 CXII. PostgreSQL Functions (PDO_PGSQL) CXIII. PostgreSQL Session Save Handler CXIV. PostScript document creation CXV. Printer Functions CXVI. Process Control Functions CXVII. Program Execution Functions CXVIII. Pspell Functions CXIX. qtdom Functions CXX. Radius CXXI. Rar Functions CXXII. Perl 兼容正则表达式函数 CXXIII. POSIX 扩展正则表达式函数 CXXIV. runkit Functions CXXV. SDO Functions CXXVI. SDO Relational Data Access Service Functions CXXVII. SDO XML Data Access Service Functions CXXVIII. Secure Shell2 Functions CXXIX. Semaphore, Shared Memory and IPC Functions CXXX. SESAM Database Functions CXXXI. Session Handling Functions CXXXII. Shared Memory Functions CXXXIII. Shockwave Flash Functions CXXXIV. SimpleXML functions CXXXV. SNMP 函数 CXXXVI. SOAP Functions CXXXVII. Socket Functions CXXXVIII. SQLite Functions CXXXIX. SQLite Functions (PDO_SQLITE) CXL. Standard PHP Library (SPL) Functions CXLI. Stream Functions CXLII. String 字符串处理函数 CXLIII. Sybase Functions CXLIV. TCP Wrappers Functions CXLV. Tidy Functions CXLVI. Tokenizer Functions CXLVII. Unicode Functions CXLVIII. URL 函数 CXLIX. Variable 变量函数 CL. Verisign Payflow Pro Functions CLI. vpopmail Functions CLII. W32api 函数 CLIII. WDDX Functions CLIV. xattr Functions CLV. xdiff Functions CLVI. XML 语法解析函数 CLVII. XML-RPC 函数 CLVIII. XMLReader functions CLIX. XSL functions CLX. XSLT Functions CLXI. YAZ Functions CLXII. YP/NIS Functions CLXIII. Zip File Functions (Read Only Access) CLXIV. Zlib Compression Functions VII. PHP 和 Zend 引擎内部资料 44. PHP 扩展库编程 API 指南 45. Zend API:深入 PHP 内核 46. 扩展 PHP 3 VIII. FAQ:常见问题 47. 一般信息 48. 邮件列表 49. 获取 PHP 50. 数据库问题 51. 安装常见问题 52. 编译问题 53. 使用 PHP 54. PHP 和 HTML 55. PHP 和 COM 56. PHP 和其它语言 57. 从 PHP/FI 2 移植到 PHP 3 58. 从 PHP 3 移植到 PHP 4 59. 从 PHP 4 移植到 PHP 5 60. 杂类问题 IX. 附录 A. PHP 及其相关工程的历史 B. 从 PHP 4 移植到 PHP 5 C. 从 PHP 3 移植到 PHP 4 D. 从 PHP/FI 2 移植到 PHP 3 E. PHP 的调试 F. 配置选项 G. php.ini 配置选项 H. 扩展库分类 I. 函数别名列表 J. 保留字列表 K. 资源类型列表 L. 支持的协议/封装协议列表 M. 可用过滤器列表 N. 所支持的套接字传输器(Socket Transports)列表 O. PHP 类型比较表 P. 解析器代号列表 Q. 关于本手册 R. 开放出版许可协议 S. 函数索引

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值