经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » PHP » 查看文章
PHP常用的自定义函数
来源:cnblogs  作者:蜗牛闪电侠  时间:2019/10/8 9:31:56  对本文有异议

php常用自定义函数类下载

https://pan.baidu.com/s/18ZuQm5cx3ynQtQqcQgK0Vw


php 设置字符编码为utf-8

header("Content-Type: text/html;charset=utf-8");


GB2312和utf8相互转换

  1. echo iconv('GB2312', 'UTF-8//IGNORE', $str); //将字符串的编码从GB2312转到UTF-8
  2. //ignore的意思是忽略转换时的错误,如果没有ignore参数,所有该字符后面的字符串都无法被保存。
  3. iconv("UTF-8","GB2312//IGNORE",$data);
  4. print_r(iconv_get_encoding()); //得到当前页面编码信息
  5. // 转码
  6. function gbk($str){return iconv('utf-8','gbk',$str);}
  7. function utf8($str){return iconv('gbk','utf-8',$str);}

路径格式化(替换双斜线为单斜线)

  1. function path_formate($str){
  2. return str_replace('\\\\','\\',$str);
  3. }

获取当前文件的目录

  1. 方法一:
  2. define('BASE_PATH',rtrim(str_replace('\\','/',__DIR__).'/'));
  3. 方法二:
  4. define('BASE_DIR', rtrim(str_replace('\\', '/', dirname(__FILE__)),'/').'/');

打印输出

  1. function dump($var)
  2. {
  3. echo '<pre>';
  4. print_r($var);
  5. echo '</pre>';
  6. }
  7. function vp($var)
  8. {
  9. echo '<pre>';
  10. var_dump($var);
  11. echo '</pre>';
  12. }
  13. function dd($var)
  14. {
  15. echo '<pre>';
  16. var_dump($var);
  17. echo '</pre>';
  18. die;
  19. }

api返回信息

  1. /**
  2. * 数据返回
  3. * @param [int] $code [结果码 200:正常/4**数据问题/5**服务器问题]
  4. * @param [string] $msg [返回的提示信息]
  5. * @param [array] $data [返回的数据]
  6. * @return [string] [最终的json数据]
  7. */
  8. public function return_msg($code, $msg = '', $data = []) {
  9. /*********** 组合数据 ***********/
  10. $return_data['code'] = $code;
  11. $return_data['msg'] = $msg;
  12. $return_data['data'] = $data;
  13. /*********** 返回信息并终止脚本 ***********/
  14. echo json_encode($return_data,JSON_UNESCAPED_UNICODE);
  15. die;
  16. }

字符串截取

方法一:

在公共的common.php中

  1. //字符串截取并且超出显示省略号
  2. function subtext($text, $length)
  3. {
  4. if(mb_strlen($text, utf8’) > $length)
  5. return mb_substr($text,0,$length,’utf8′).’ …’;
  6. return $text;
  7. }

在模版中调用则:
{$tops.title | subtext=18}

方法二:

在公共的common.php中

  1. //字符串截取
  2. function cut_str($sourcestr,$cutlength)
  3. {
  4. $returnstr='';
  5. $i=0;
  6. $n=0;
  7. $str_length=strlen($sourcestr);//字符串的字节数
  8. while (($n<$cutlength) and ($i<=$str_length))
  9. {
  10. $temp_str=substr($sourcestr,$i,1);
  11. $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码
  12. if ($ascnum>=224) //如果ASCII位高与224,
  13. {
  14. $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范,将3个连续的字符计为单个字符
  15. $i=$i+3; //实际Byte计为3
  16. $n++; //字串长度计1
  17. }
  18. elseif ($ascnum>=192) //如果ASCII位高与192,
  19. {
  20. $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范,将2个连续的字符计为单个字符
  21. $i=$i+2; //实际Byte计为2
  22. $n++; //字串长度计1
  23. }
  24. elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母,
  25. {
  26. $returnstr=$returnstr.substr($sourcestr,$i,1);
  27. $i=$i+1; //实际的Byte数仍计1个
  28. $n++; //但考虑整体美观,大写字母计成一个高位字符
  29. }
  30. else //其他情况下,包括小写字母和半角标点符号,
  31. {
  32. $returnstr=$returnstr.substr($sourcestr,$i,1);
  33. $i=$i+1; //实际的Byte数计1个
  34. $n=$n+0.5; //小写字母和半角标点等与半个高位字符宽...
  35. }
  36. }
  37. if ($str_length>$i){
  38. $returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
  39. }
  40. return $returnstr;
  41. }

在模版中调用则:
{$brand.brand_description|cut_str=###,10}


字符串make_by_id转成makeById

  1. function changestr($string){
  2. if(!is_string($string)){
  3. die('please input string.');
  4. }
  5. if(strpos($string,'_')){
  6. $stringArr=explode('_',$string);
  7. $str='';
  8. foreach ($stringArr as $v){
  9. $str .= ucfirst($v);
  10. }
  11. return $str;
  12. }
  13. }

数组 字符串 对象 json格式的字符串互转

  1. /**
  2. * 对象 转 数组
  3. *
  4. * @param object $obj 对象
  5. * @return array
  6. */
  7. function object2array(&$object) {
  8. $object = json_decode( json_encode( $object),true);
  9. return $object;
  10. }
  11. /****对象转json数组格式的字符串*****/
  12. function obj2arr($object) {
  13. $json_object = json_encode($object);
  14. echo "<pre>";
  15. var_dump($json_object);die;
  16. $arr = json_decode($json_object, 1);
  17. return $arr;
  18. }
  19. /****json转数组*****/
  20. /**
  21. * [json_to_arr description] json_to_arr 遍历把json转为数组
  22. * @param [type] $jsonstr [description]
  23. * @return boolean [description]
  24. */
  25. //测试数据:$resp='{"jingdong_omnichannel_order_ship_update_responce":{"code":"0","result":"{\\"code\\":\\"400\\",\\"message\\":\\"系统异常:物流组件中为已取消状态\\",\\"success\\":false}"}}';
  26. function json_to_arr2($jsonstr)
  27. {
  28. if (is_string($jsonstr)&&is_array(json_decode($jsonstr, true))) {
  29. $arr = json_decode($jsonstr, true);
  30. foreach ($arr as $k => $v) {
  31. if (is_array($v)) {
  32. foreach ($v as $kk=>$vv){
  33. if(is_string($vv) && is_array(json_decode($vv, true))){
  34. $arr[$k][$kk] = json_decode($vv, true);
  35. }
  36. }
  37. }
  38. if(is_string($v)&&is_sarray(json_decode($v,true))){
  39. $arr[$k]=json_decode($v,true);
  40. }
  41. }
  42. return $arr;
  43. } else {
  44. die('This is not jsonString!');
  45. }
  46. }
  47. /**
  48. * 数组 转 对象
  49. *
  50. * @param array $arr 数组
  51. * @return object
  52. */
  53. function array_to_object($arr) {
  54. if (gettype($arr) != 'array') {
  55. return;
  56. }
  57. foreach ($arr as $k => $v) {
  58. if (gettype($v) == 'array' || getType($v) == 'object') {
  59. $arr[$k] = (object)array_to_object($v);
  60. }
  61. }
  62. return (object)$arr;
  63. }
  64. $arr = array(
  65. 'name'=>'haima',
  66. 'age'=>32,
  67. 'gender'=>'nan'
  68. );
  69. $a=(Object)($arr); //数组转对象
  70. echo '<pre>';
  71. var_dump($a);
  72. $jsonstring=json_encode($array,JSON_UNESCAPED_UNICODE); //对象转json字符串 不转义中文汉字
  73. echo '<pre>';
  74. var_dump($jsonstring);
  75. $abj=json_decode($array); //json转对象
  76. $array=json_decode($array,true); //json转数组
  77. echo '<pre>';
  78. $b=(Array)($a); //对象转数组
  79. var_dump($b);

强制类型转换

  1. /**
  2. * 强制类型转换
  3. * @param string $data
  4. * @param string $type
  5. * @return mixed
  6. */
  7. private function typeCast(&$data, $type)
  8. {
  9. switch (strtolower($type)) {
  10. // 数组
  11. case 'a':
  12. $data = (array) $data;
  13. break;
  14. // 数字
  15. case 'd':
  16. $data = (int) $data;
  17. break;
  18. // 浮点
  19. case 'f':
  20. $data = (float) $data;
  21. break;
  22. // 布尔
  23. case 'b':
  24. $data = (boolean) $data;
  25. break;
  26. // 字符串
  27. case 's':
  28. default:
  29. if (is_scalar($data)) {
  30. $data = (string) $data;
  31. } else {
  32. throw new \InvalidArgumentException('variable type error:' . gettype($data));
  33. }
  34. }
  35. }


php序列化serialize与返回序列化unserialeze

serialize() 把变量和它们的值编码成文本
unserialize() 恢复原先变量


创建日志文件

  1. 方法一(适合临时用):
  1. //数组/字符串都可以
  2. file_put_contents( 'log.log', date('Y-m-d H:i:s',time()) .' ' . var_export($_REQUEST,true) . "\r\n", FILE_APPEND);
  1. 方法二:

例: /www.wdmcake.com/data/log/日期/$file文件名

  1. /**
  2. *$str array/str 要写入的内容
  3. *$dir str 日期文件夹里面的新建的文件夹名字 例如 /www.wdmcake.com/data/log/201806/sms_apiaas
  4. *$file string 文件的名字 例:send_log_20180628.log
  5. */
  6. function wdmlog($str,$dir='log',$file='log')
  7. {
  8. if (!file_exists(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir))
  9. {
  10. make_dir(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir);
  11. }
  12. $str = is_array($str) ? var_export($str,true):$str;
  13. file_put_contents(ROOT_PATH . 'data/log/' . date('Ym'). '/' . $dir.'/' . $file .'_' . date('Ymd') . '.log', local_date('Y-m-d H:i:s') .' ' . $str . "\r\n", FILE_APPEND);
  14. }
  1. 方法三:
  1. function create_log($data,$merchant,$agency,$file='')
  2. {
  3. if(empty($merchant)) die("商户code不可为空");
  4. if(empty($agency)) die("平台code不可为空");
  5. $file_path = ROOT_PATH . 'logdata/'.$merchant.'/'.$agency;
  6. if(!is_dir($file_path)){
  7. mkdir($file_path, 0777, true);
  8. }
  9. file_put_contents($file_path.'/'.$agency.'_' . $file . date('Ymd',time()) . '.log', date('Y-m-d H:i:s',time()) .' ' . var_export($data,true) . "\r\n", FILE_APPEND);
  10. }

返回二维数组其中一段的数据

  1. /**
  2. * [slice description] 返回二维数组其中一段的数据
  3. * @param [type] $arr [description] 传二维关联数组
  4. * @param [type] $star [description] 截取的开始位置
  5. * @param [type] $length [description] 截取的长度
  6. * @param [type] $order [description] 0顺序 -1倒序
  7. * @param [type] $preserve [description] 保持索引关系 true - 保留键名 false - 默认。重置键名
  8. * @return [type] [description]
  9. */
  10. function slice($arr, $star, $length, $order = 0, $preserve = false)
  11. {
  12. foreach ($arr as $key => $value) {
  13. $arr[$key] = array_slice($value, $star, $length, $preserve);
  14. }
  15. if ($order) {
  16. return array_reverse($arr);
  17. }
  18. return $arr;
  19. }

例子:

  1. <?php
  2. header('Content-Type=text/html;charset:utf8');
  3. $arr = array(
  4. [
  5. 'id' => '1',
  6. 'name' => '李四',
  7. 'age' => '21',
  8. 'gender' => '男',
  9. ],
  10. [
  11. 'id' => '2',
  12. 'name' => '王五',
  13. 'age' => '22',
  14. 'gender' => '男',
  15. ],
  16. );
  17. echo '<pre>';
  18. print_r(slice($arr, 0, 2));
  19. //打印:
  20. // 打印结果:
  21. // Array
  22. // (
  23. // [0] => Array
  24. // (
  25. // [id] => 1
  26. // [name] => 李四
  27. // )
  28. // [1] => Array
  29. // (
  30. // [id] => 2
  31. // [name] => 王五
  32. // )
  33. // )

获取ip地址

  1. 方法一
  1. $_SERVER['REMOTE_ADDR']
  1. 方法二
  1. /**
  2. * 获得访问的IP
  3. * Enter description here ...
  4. */
  5. function getIP() {
  6. return isset($_SERVER["HTTP_X_FORWARDED_FOR"])?$_SERVER["HTTP_X_FORWARDED_FOR"]
  7. :(isset($_SERVER["HTTP_CLIENT_IP"])?$_SERVER["HTTP_CLIENT_IP"]
  8. :$_SERVER["REMOTE_ADDR"]);
  9. }
  1. 方法三
  1. /**
  2. * 获得用户的真实IP地址
  3. *
  4. * @access public
  5. * @return string
  6. */
  7. function real_ip()
  8. {
  9. static $realip = NULL;
  10. if ($realip !== NULL)
  11. {
  12. return $realip;
  13. }
  14. if (isset($_SERVER))
  15. {
  16. if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
  17. {
  18. $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
  19. /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
  20. foreach ($arr AS $ip)
  21. {
  22. $ip = trim($ip);
  23. if ($ip != 'unknown')
  24. {
  25. $realip = $ip;
  26. break;
  27. }
  28. }
  29. }
  30. elseif (isset($_SERVER['HTTP_CLIENT_IP']))
  31. {
  32. $realip = $_SERVER['HTTP_CLIENT_IP'];
  33. }
  34. else
  35. {
  36. if (isset($_SERVER['REMOTE_ADDR']))
  37. {
  38. $realip = $_SERVER['REMOTE_ADDR'];
  39. }
  40. else
  41. {
  42. $realip = '0.0.0.0';
  43. }
  44. }
  45. }
  46. else
  47. {
  48. if (getenv('HTTP_X_FORWARDED_FOR'))
  49. {
  50. $realip = getenv('HTTP_X_FORWARDED_FOR');
  51. }
  52. elseif (getenv('HTTP_CLIENT_IP'))
  53. {
  54. $realip = getenv('HTTP_CLIENT_IP');
  55. }
  56. else
  57. {
  58. $realip = getenv('REMOTE_ADDR');
  59. }
  60. }
  61. preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
  62. $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
  63. return $realip;
  64. }

PHP限制IP访问 只允许指定IP访问 允许*号通配符过滤IP

  1. /**
  2. * 检测访问的ip是否为规定的允许的ip
  3. * Enter description here ...
  4. */
  5. function check_ip(){
  6. $ALLOWED_IP=array('192.168.2.*','127.0.0.1','192.168.2.49');
  7. $IP=getIP();
  8. $check_ip_arr= explode('.',$IP);//要检测的ip拆分成数组
  9. #限制IP
  10. if(!in_array($IP,$ALLOWED_IP)) {
  11. foreach ($ALLOWED_IP as $val){
  12. if(strpos($val,'*')!==false){//发现有*号替代符
  13. $arr=array();//
  14. $arr=explode('.', $val);
  15. $bl=true;//用于记录循环检测中是否有匹配成功的
  16. for($i=0;$i<4;$i++){
  17. if($arr[$i]!='*'){//不等于* 就要进来检测,如果为*符号替代符就不检查
  18. if($arr[$i]!=$check_ip_arr[$i]){
  19. $bl=false;
  20. break;//终止检查本个ip 继续检查下一个ip
  21. }
  22. }
  23. }//end for
  24. if($bl){//如果是true则找到有一个匹配成功的就返回
  25. return;
  26. die;
  27. }
  28. }
  29. }//end foreach
  30. header('HTTP/1.1 403 Forbidden');
  31. echo "Access forbidden";
  32. die;
  33. }
  34. }

获取地址路径里0到第一个\线的部分

  1. function f_dirname($f_path){
  2. return substr($f_path,0,strrpos($f_path,'\\'));
  3. }

获取当前文件所在的文件路径

  1. define('CUR_API_PATH', rtrim(str_replace('\\', '/', dirname(__FILE__)),'/').'/');

获取随机字符串

  1. /**
  2. * 随机字符
  3. * @param int $length 长度
  4. * @param string $type 类型
  5. * @param int $convert 转换大小写 1大写 0小写
  6. * @return string
  7. */
  8. function random($length=10, $type='letter', $convert=0)
  9. {
  10. $config = array(
  11. 'number'=>'1234567890',
  12. 'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
  13. 'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
  14. 'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
  15. );
  16. if(!isset($config[$type])) $type = 'letter';
  17. $string = $config[$type];
  18. $code = '';
  19. $strlen = strlen($string) -1;
  20. for($i = 0; $i < $length; $i++){
  21. $code .= $string{mt_rand(0, $strlen)};
  22. }
  23. if(!empty($convert)){
  24. $code = ($convert > 0)? strtoupper($code) : strtolower($code);
  25. }
  26. return $code;
  27. }

中文字符串反转


检查目标文件夹是否存在,如果不存在则自动创建该目录

  1. /**
  2. * 检查目标文件夹是否存在,如果不存在则自动创建该目录
  3. *
  4. * @access public
  5. * @param string folder 目录路径。不能使用相对于网站根目录的URL
  6. *
  7. * @return bool
  8. */
  9. function make_dir($folder)
  10. {
  11. $reval = false;
  12. if (!file_exists($folder))
  13. {
  14. /* 如果目录不存在则尝试创建该目录 */
  15. @umask(0);
  16. /* 将目录路径拆分成数组 */
  17. preg_match_all('/([^\/]*)\/?/i', $folder, $atmp);
  18. /* 如果第一个字符为/则当作物理路径处理 */
  19. $base = ($atmp[0][0] == '/') ? '/' : '';
  20. /* 遍历包含路径信息的数组 */
  21. foreach ($atmp[1] AS $val)
  22. {
  23. if ('' != $val)
  24. {
  25. $base .= $val;
  26. if ('..' == $val || '.' == $val)
  27. {
  28. /* 如果目录为.或者..则直接补/继续下一个循环 */
  29. $base .= '/';
  30. continue;
  31. }
  32. }
  33. else
  34. {
  35. continue;
  36. }
  37. $base .= '/';
  38. if (!file_exists($base))
  39. {
  40. /* 尝试创建目录,如果创建失败则继续循环 */
  41. if (@mkdir(rtrim($base, '/'), 0777))
  42. {
  43. @chmod($base, 0777);
  44. $reval = true;
  45. }
  46. }
  47. }
  48. }
  49. else
  50. {
  51. /* 路径已经存在。返回该路径是不是一个目录 */
  52. $reval = is_dir($folder);
  53. }
  54. clearstatcache();
  55. return $reval;
  56. }

默认获得文件修改时间

  1. function filetime($way,$char='m'){
  2. date_default_timezone_set('PRC');
  3. switch($char){
  4. case 'c':$localtime = date('Y-m-d H:i:s',filectime($way));
  5. break;
  6. case 'm':$localtime = date('Y-m-d H:i:s',filemtime($way));
  7. break;
  8. case 'a':$localtime = date('Y-m-d H:i:s',fileatime($way));
  9. break;
  10. }
  11. return $localtime;
  12. }

判断后缀类型

  1. function suffixtype($f_path){
  2. $info = pathinfo($f_path);
  3. $f_type = 'file';
  4. switch(strtolower(@$info["extension"])){
  5. case 'jpg':case 'jpeg':case 'gif':
  6. case 'png':case 'bmp':$f_type = 'image';break;
  7. case 'pl':case 'c':case 'cpp':case 'log':case 'asp':case 'php':case 'jsp':case 'txt':case 'xml':case 'html':case 'htm':case 'phtml':case 'jhtml':case 'java':case 'cfg':case 'ini':
  8. case 'text':case 'bat':$f_type = 'text';break;
  9. }
  10. return $f_type;
  11. }

检查文件类型

  1. /**
  2. * 检查文件类型
  3. *
  4. * @access public
  5. * @param string filename 文件名
  6. * @param string realname 真实文件名
  7. * @param string limit_ext_types 允许的文件类型
  8. * @return string
  9. */
  10. function check_file_type($filename, $realname = '', $limit_ext_types = '')
  11. {
  12. if ($realname)
  13. {
  14. $extname = strtolower(substr($realname, strrpos($realname, '.') + 1));
  15. }
  16. else
  17. {
  18. $extname = strtolower(substr($filename, strrpos($filename, '.') + 1));
  19. }
  20. if ($limit_ext_types && stristr($limit_ext_types, '|' . $extname . '|') === false)
  21. {
  22. return '';
  23. }
  24. $str = $format = '';
  25. $file = @fopen($filename, 'rb');
  26. if ($file)
  27. {
  28. $str = @fread($file, 0x400); // 读取前 1024 个字节
  29. @fclose($file);
  30. }
  31. else
  32. {
  33. if (stristr($filename, ROOT_PATH) === false)
  34. {
  35. if ($extname == 'jpg' || $extname == 'jpeg' || $extname == 'gif' || $extname == 'png' || $extname == 'doc' ||
  36. $extname == 'xls' || $extname == 'txt' || $extname == 'zip' || $extname == 'rar' || $extname == 'ppt' ||
  37. $extname == 'pdf' || $extname == 'rm' || $extname == 'mid' || $extname == 'wav' || $extname == 'bmp' ||
  38. $extname == 'swf' || $extname == 'chm' || $extname == 'sql' || $extname == 'cert'|| $extname == 'pptx' ||
  39. $extname == 'xlsx' || $extname == 'docx')
  40. {
  41. $format = $extname;
  42. }
  43. }
  44. else
  45. {
  46. return '';
  47. }
  48. }
  49. if ($format == '' && strlen($str) >= 2 )
  50. {
  51. if (substr($str, 0, 4) == 'MThd' && $extname != 'txt')
  52. {
  53. $format = 'mid';
  54. }
  55. elseif (substr($str, 0, 4) == 'RIFF' && $extname == 'wav')
  56. {
  57. $format = 'wav';
  58. }
  59. elseif (substr($str ,0, 3) == "\xFF\xD8\xFF")
  60. {
  61. $format = 'jpg';
  62. }
  63. elseif (substr($str ,0, 4) == 'GIF8' && $extname != 'txt')
  64. {
  65. $format = 'gif';
  66. }
  67. elseif (substr($str ,0, 8) == "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A")
  68. {
  69. $format = 'png';
  70. }
  71. elseif (substr($str ,0, 2) == 'BM' && $extname != 'txt')
  72. {
  73. $format = 'bmp';
  74. }
  75. elseif ((substr($str ,0, 3) == 'CWS' || substr($str ,0, 3) == 'FWS') && $extname != 'txt')
  76. {
  77. $format = 'swf';
  78. }
  79. elseif (substr($str ,0, 4) == "\xD0\xCF\x11\xE0")
  80. { // D0CF11E == DOCFILE == Microsoft Office Document
  81. if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'doc')
  82. {
  83. $format = 'doc';
  84. }
  85. elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xls')
  86. {
  87. $format = 'xls';
  88. } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'ppt')
  89. {
  90. $format = 'ppt';
  91. }
  92. } elseif (substr($str ,0, 4) == "PK\x03\x04")
  93. {
  94. if (substr($str,0x200,4) == "\xEC\xA5\xC1\x00" || $extname == 'docx')
  95. {
  96. $format = 'docx';
  97. }
  98. elseif (substr($str,0x200,2) == "\x09\x08" || $extname == 'xlsx')
  99. {
  100. $format = 'xlsx';
  101. } elseif (substr($str,0x200,4) == "\xFD\xFF\xFF\xFF" || $extname == 'pptx')
  102. {
  103. $format = 'pptx';
  104. }else
  105. {
  106. $format = 'zip';
  107. }
  108. } elseif (substr($str ,0, 4) == 'Rar!' && $extname != 'txt')
  109. {
  110. $format = 'rar';
  111. } elseif (substr($str ,0, 4) == "\x25PDF")
  112. {
  113. $format = 'pdf';
  114. } elseif (substr($str ,0, 3) == "\x30\x82\x0A")
  115. {
  116. $format = 'cert';
  117. } elseif (substr($str ,0, 4) == 'ITSF' && $extname != 'txt')
  118. {
  119. $format = 'chm';
  120. } elseif (substr($str ,0, 4) == "\x2ERMF")
  121. {
  122. $format = 'rm';
  123. } elseif ($extname == 'sql')
  124. {
  125. $format = 'sql';
  126. } elseif ($extname == 'txt')
  127. {
  128. $format = 'txt';
  129. }
  130. }
  131. if ($limit_ext_types && stristr($limit_ext_types, '|' . $format . '|') === false)
  132. {
  133. $format = '';
  134. }
  135. return $format;
  136. }

获取文件后缀名,并判断是否在定义的数组中

  1. /**
  2. * 获取文件后缀名,并判断是否合法
  3. *
  4. * @param string $file_name //是一个文件的路径
  5. * @param array $allow_type //需要的文件类型数组
  6. * @return blob
  7. */
  8. function get_file_suffix($file_name, $allow_type = array())
  9. {
  10. $file_suffix = strtolower(array_pop(explode('.', $file_name)));
  11. if (empty($allow_type))
  12. {
  13. return $file_suffix;
  14. }
  15. else
  16. {
  17. if (in_array($file_suffix, $allow_type))
  18. {
  19. return true;
  20. }
  21. else
  22. {
  23. return false;
  24. }
  25. }
  26. }

判断路径是文件还是目录

  1. function f_type($f_path){
  2. return is_dir($f_path)?'dir':suffixtype($f_path);
  3. }

计算文件或目录字节大小

  1. //计算文件或目录字节大小
  2. function bytesize_calc($f_path){
  3. if(!is_dir($f_path)){
  4. return sprintf("%u", filesize($f_path));}
  5. $bytesize = 0;
  6. $f_arr = scandir($f_path);
  7. $size = count($f_arr);
  8. for($i=0;$i<$size;$i++){
  9. if('.'==$f_arr[$i]||'..'==$f_arr[$i])continue;
  10. $file_or_dir = $f_path.'/'.$f_arr[$i];
  11. $bytesize += bytesize_calc($file_or_dir);
  12. }
  13. return $bytesize;
  14. }
  15. //获得文件大小
  16. function f_size($f_path){
  17. return size_formate(bytesize_calc($f_path));
  18. }

接收异步过来的get消息

  1. $sms_result_data = $_GET; //用这种
  2. $param = request()->param(); //thinkphp5接收消息
  3. $sms_result_data1 = file_get_contents("php://input");

curl之get请求

  1. function _curl_get($urldata)
  2. {
  3. $ch = curl_init();
  4. curl_setopt($ch, CURLOPT_URL,$urldata);
  5. curl_setopt($ch, CURLOPT_HEADER, 0);
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  7. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//不验证SSL证书。
  8. $data = curl_exec($ch);
  9. curl_close($ch);
  10. if ($data)
  11. return $data;
  12. else
  13. return false;
  14. }

curl之post请求

如果是有图片要上传加下面用这行代码

curl_file_create(ROOT_PATH.'public'.$value["goods_img"]);

  1. /**
  2. * [post description]
  3. * @param [type] $url [请求的url]
  4. * @param string $post_data [请求的数据]
  5. * @param integer $timeout [请求超时时间]
  6. * @return [type] $Mix [混合数据json|array|obj]
  7. */
  8. function post($url, $post_data = '', $timeout = 3000)
  9. {
  10. header("Content-type:text/html;charset=utf-8");
  11. $ch = curl_init();
  12. curl_setopt ($ch, CURLOPT_URL, $url);
  13. curl_setopt ($ch, CURLOPT_POST, 1);
  14. curl_setopt ($ch, CURLOPT_POSTFIELDS, $post_data);
  15. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  16. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  17. curl_setopt($ch, CURLOPT_HEADER, false);
  18. $file_contents = curl_exec($ch);
  19. curl_close($ch);
  20. if ($content){
  21. return $file_contents;
  22. }else{
  23. return false;
  24. }
  25. }

curl之post_get请求

如果是有图片要上传加下面用这行代码

curl_file_create(ROOT_PATH.'public'.$value["goods_img"]);

  1. 方法一
  1. /**
  2. * [_curl_post_get description]
  3. * 如果$data为空转为get请求.https不验证证书
  4. * @param [type] $url [url]
  5. * @param array $data [要传的数据]
  6. * @param integer $timeout [设置请求超时的时间]
  7. * @return [type] $Mix [混合数据json|array|obj]
  8. */
  9. function _curl_post($url, $data = '',$timeout = 3000) {
  10. header("Content-type:text/html;charset=utf-8");
  11. $ch = curl_init();
  12. curl_setopt($ch, CURLOPT_URL, $url); //请求的url
  13. curl_setopt($ch, CURLOPT_HEADER, false); ////是否携带head头信息 ture / error
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //返回数据还是打印数据 0,直接输出 1,返回
  15. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //设置请求超时的时间
  16. // https请求 不验证证书和hosts方法:
  17. if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
  18. //if (1 == strpos("$".$url, "https://")) //效果同上面
  19. {
  20. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  21. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  22. }
  23. if(!empty($post_data)){
  24. curl_setopt($ch, CURLOPT_POST,1); //设置post方式请求,如果不写默认为get方式
  25. curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //要传递的参数
  26. }
  27. //发送请求 并接收数据赋值给$data
  28. $data = curl_exec($ch);
  29. //关闭请求资源
  30. curl_close($ch);
  31. $content = iconv('gb2312', 'utf-8//IGNORE',$data); //修改字符编码
  32. if ($content)
  33. return $content;
  34. else
  35. return false;
  36. }
  1. 方法二
  1. /**
  2. * curl访问
  3. * @author rainfer <81818832@qq.com>
  4. * @param string $url
  5. * @param string $type
  6. * @param boolean $data
  7. * @param string $err_msg
  8. * @param int $timeout
  9. * @param array $cert_info
  10. * @return string
  11. */
  12. function go_curl($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array())
  13. {
  14. $type = strtoupper($type);
  15. if ($type == 'GET' && is_array($data)) {
  16. $data = http_build_query($data);
  17. }
  18. $option = array();
  19. if ( $type == 'POST' ) {
  20. $option[CURLOPT_POST] = 1;
  21. }
  22. if ($data) {
  23. if ($type == 'POST') {
  24. $option[CURLOPT_POSTFIELDS] = $data;
  25. } elseif ($type == 'GET') {
  26. $url = strpos($url, '?') !== false ? $url.'&'.$data : $url.'?'.$data;
  27. }
  28. }
  29. $option[CURLOPT_URL] = $url;
  30. $option[CURLOPT_FOLLOWLOCATION] = TRUE;
  31. $option[CURLOPT_MAXREDIRS] = 4;
  32. $option[CURLOPT_RETURNTRANSFER] = TRUE;
  33. $option[CURLOPT_TIMEOUT] = $timeout;
  34. //设置证书信息
  35. if(!empty($cert_info) && !empty($cert_info['cert_file'])) {
  36. $option[CURLOPT_SSLCERT] = $cert_info['cert_file'];
  37. $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
  38. $option[CURLOPT_SSLCERTTYPE] = $cert_info['cert_type'];
  39. }
  40. //设置CA
  41. if(!empty($cert_info['ca_file'])) {
  42. // 对认证证书来源的检查,0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
  43. $option[CURLOPT_SSL_VERIFYPEER] = 1;
  44. $option[CURLOPT_CAINFO] = $cert_info['ca_file'];
  45. } else {
  46. // 对认证证书来源的检查,0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
  47. $option[CURLOPT_SSL_VERIFYPEER] = 0;
  48. }
  49. $ch = curl_init();
  50. curl_setopt_array($ch, $option);
  51. $response = curl_exec($ch);
  52. $curl_no = curl_errno($ch);
  53. $curl_err = curl_error($ch);
  54. curl_close($ch);
  55. // error_log
  56. if($curl_no > 0) {
  57. if($err_msg !== null) {
  58. $err_msg = '('.$curl_no.')'.$curl_err;
  59. }
  60. }
  61. return $response;
  62. }
  1. 方法三
  1. //curl模拟post发送请求
  2. function curl_sent($url, $postFields = null)
  3. {
  4. $header = array(
  5. // 'Content-Type: application/json',
  6. 'Content-Type: application/x-www-form-urlencoded'
  7. );
  8. $ch = curl_init();
  9. curl_setopt($ch, CURLOPT_URL, $url);
  10. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  11. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  12. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  13. // https 请求
  14. if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
  15. {
  16. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  17. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  18. }
  19. if (is_array($postFields) && 0 < count($postFields))
  20. {
  21. curl_setopt($ch, CURLOPT_POST, true);
  22. $postMultipart = false;
  23. foreach ($postFields as $k => $v)
  24. {
  25. if ('@' == substr($v, 0, 1))
  26. {
  27. $postMultipart = true;
  28. break;
  29. }
  30. }
  31. unset($k, $v);
  32. if ($postMultipart) {
  33. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  34. } else {
  35. curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
  36. }
  37. }
  38. $reponse = curl_exec($ch);
  39. if (curl_errno($ch))
  40. {
  41. throw new JosSdkException(curl_error($ch), 0);
  42. } else {
  43. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  44. if (200 !== $httpStatusCode)
  45. {
  46. throw new JosSdkException($reponse, $httpStatusCode);
  47. }
  48. }
  49. curl_close($ch);
  50. return $reponse;
  51. }

方法四**:

  1. public $connectTimeout = 0;
  2. public $readTimeout = 0;
  3. public function curl($url, $postFields = null)
  4. {
  5. $ch = curl_init();
  6. curl_setopt($ch, CURLOPT_URL, $url);
  7. curl_setopt($ch, CURLOPT_FAILONERROR, false);
  8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  9. if ($this->readTimeout) {
  10. curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
  11. }
  12. if ($this->connectTimeout) {
  13. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
  14. }
  15. //https 请求
  16. if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
  17. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  18. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  19. }
  20. if (is_array($postFields) && 0 < count($postFields))
  21. {
  22. $postBodyString = "";
  23. $postMultipart = false;
  24. foreach ($postFields as $k => $v)
  25. {
  26. if("@" != substr($v, 0, 1))//判断是不是文件上传
  27. {
  28. $postBodyString .= "$k=" . urlencode($v) . "&";
  29. }
  30. else//文件上传用multipart/form-data,否则用www-form-urlencoded
  31. {
  32. $postMultipart = true;
  33. }
  34. }
  35. unset($k, $v);
  36. curl_setopt($ch, CURLOPT_POST, true);
  37. if ($postMultipart)
  38. {
  39. curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  40. }
  41. else
  42. {
  43. curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
  44. }
  45. }
  46. $reponse = curl_exec($ch);
  47. $reponse = iconv('gb2312', 'utf-8//IGNORE',$reponse); //修改字符编码
  48. create_log('第'.__LINE__.'行', 'wdm', 'jdomnic', 'curl');
  49. create_log($reponse, 'wdm', 'jdomnic', 'curl');
  50. if (curl_errno($ch))
  51. {
  52. throw new Exception(curl_error($ch),0);
  53. }
  54. else
  55. {
  56. $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  57. if (200 !== $httpStatusCode)
  58. {
  59. throw new Exception($reponse,$httpStatusCode);
  60. }
  61. }
  62. curl_close($ch);
  63. return $reponse;
  64. }

判断数组类型参数是否含有空元素值

  1. //$param array
  2. function is_arraynull($param){
  3. if(!is_array($param)){
  4. return '0';
  5. }else{
  6. foreach ($param as $key => $value) {
  7. if($value!=''){
  8. $ret = is_arraynull($value);
  9. }else{
  10. return 1;
  11. }
  12. }
  13. }
  14. }

判断是否传入必要参数

  1. /**
  2. * 判断是否传入必要参数
  3. * @param [type] $inter_param [description]
  4. * @param [type] $agency [description]
  5. * @param [type] $merchant [description]
  6. * @return [type] [description]
  7. */
  8. function judge_parameter($param){
  9. if(!isset($param['inter_param']) || !isset($param['agency']) || !isset($param['merchant'])){
  10. return false;
  11. }
  12. if(empty($param['inter_param']) || empty($param['agency']) || empty($param['merchant'])){
  13. return false;
  14. }
  15. return true;
  16. }
转自[Haima的博客] http://www.cnblogs.com/haima/

原文链接:http://www.cnblogs.com/xssz/p/11620738.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号