PHP各种常用函数方法封装

对象转数组

function ObjectToArray($data)
{
    if (is_object($data)) {
        $data = get_object_vars($data);
    }
    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    } else {
        return $data;
    }
}

数组转JSON数据

function ArrayToJson($data, $type = true)
{
    $data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    if ($type) {
        print_r($data);
        exit;
    } else {
        return $data;
    }
}

以数组的形式返回关于文件路径的信息

pathinfo(path, options);

/**
['dirname']: 目录路径
['basename']: 文件名
['extension']: 文件后缀名
['filename']: 不包含后缀的文件名
**/

// path:规定要检查的路径。

/**
options:
PATHINFO_DIRNAME - 只返回 dirname
PATHINFO_BASENAME - 只返回 basename
PATHINFO_EXTENSION - 只返回 extension
PATHINFO_FILENAME - 只返回 filename
**/

获取PHP代码执行后的结果

<?php 
function run_code($code)
{
    $file_name = rand() . 'txt';
    $content = '<?php $text = ' . $code . ' ?>';
    file_put_contents($file_name, $content);
    include($file_name);
    unlink($file_name);
    return $text;
}
?>

多维数组降维

function ArrMd2Ud($arr)
{
    #将数值第一元素作为容器,作地址赋值。
    $ar_room = &$arr[key($arr)];
    #第一容器不是数组进去转呀
    if (!is_array($ar_room)) {
        #转为成数组
        $ar_room = array($ar_room);
    }
    #指针下移
    next($arr);
    #遍历
    while (list($k, $v) = each($arr)) {
        #是数组就递归深挖,不是就转成数组
        $v = is_array($v) ? call_user_func(__FUNCTION__, $v) : array($v);
        #递归合并
        $ar_room = array_merge_recursive($ar_room, $v);
        #释放当前下标的数组元素
        unset($arr[$k]);
    }
    return $ar_room;
}

字符串加密解密

/**
 * $string:需要加解密的字符串;
 * $operation:E表示加密,D表示解密;
 * $key:自定义密匙
 */
function string($string, $operation, $key = '')
{
    $key = md5($key);
    $key_length = strlen($key);
    $string = $operation == 'D' ? base64_decode($string) : substr(md5($string . $key), 0, 8) . $string;
    $string_length = strlen($string);
    $rndkey = $box = array();
    $result = '';
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($key[$i % $key_length]);
        $box[$i] = $i;
    }
    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if ($operation == 'D') {
        if (substr($result, 0, 8) == substr(md5(substr($result, 8) . $key), 0, 8)) {
            return substr($result, 8);
        } else {
            return '';
        }
    } else {
        return str_replace('=', '', base64_encode($result));
    }
}

反腾讯网址安全检测

/*
反腾讯网址安全检测系统
Description:屏蔽腾讯电脑管家网址安全检测
Version:2.6
Author:易航
Link:http://blog.bri6.cn
*/
if (!function_exists('real_ip')) {
    function real_ip()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_CF_CONNECTING_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CF_CONNECTING_IP'])) {
            $ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
        } elseif (isset($_SERVER['HTTP_CLIENT_IP']) && preg_match('/^([0-9]{1,3}\.){3}[0-9]{1,3}$/', $_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and preg_match_all('#\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}#s', $_SERVER['HTTP_X_FORWARDED_FOR'], $matches)) {
            foreach ($matches[0] as $xip) {
                if (!preg_match('#^(10|172\.16|192\.168)\.#', $xip)) {
                    $ip = $xip;
                    break;
                }
            }
        }
        return $ip;
    }
}
if (empty($_SERVER['HTTP_REFERER'])) {
    $_SERVER['HTTP_REFERER'] = '';
}
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$http_accept = $_SERVER['HTTP_ACCEPT'];
//IP屏蔽
$iptables = '977012992~977013247|977084416~977084927|1743654912~1743655935|1949957632~1949958143|2006126336~2006127359|2111446272~2111446527|3418570752~3418578943|3419242496~3419250687|3419250688~3419275263|3682941952~3682942207|3682942464~3682942719|3682986660~3682986663|1707474944~1707606015|1709318400~1709318655|1884967642|1884967620|1893733510|1709332858|1709325774|1709342057|1709341968|1709330358|1709335492|1709327575|1709327041|1709327557|1709327573|1975065457|1902908741|1902908705|3029946827|236000818';
$remoteiplong = bindec(decbin(ip2long(real_ip())));
foreach (explode('|', $iptables) as $iprows) {
    if ($remoteiplong == $iprows) exit('欢迎使用');
    $ipbanrange = explode('~', $iprows);
    if ($remoteiplong >= $ipbanrange[0] && $remoteiplong <= $ipbanrange[1])
        exit('欢迎使用');
}
//HEADER特征屏蔽
if (!isset($http_accept) || preg_match("/manager/", strtolower($user_agent)) || isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] == '' || strpos($user_agent, 'Mozilla') === false && strpos($user_agent, 'ozilla') !== false || isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'urls.tr.com') !== false || isset($_COOKIE['ASPSESSIONIDQASBQDRC']) || empty($user_agent) || strpos($user_agent, 'HUAWEI G700-U00') !== false && !isset($http_accept) || strpos($user_agent, 'iPhone OS 5_0') !== false && strpos($user_agent, 'Compatible') !== false || preg_match("/Alibaba.Security.Heimdall/", $user_agent)) {
    exit('欢迎使用');
}
if (strpos($user_agent, 'Coolpad Y82-520') !== false && $http_accept == '*/*' || strpos($user_agent, 'Mac OS X 10_12_4') !== false && $http_accept == '*/*' || strpos($user_agent, 'iPhone OS') !== false && $http_accept == '*/*' || strpos($user_agent, 'Android') !== false && $http_accept == '*/*' || strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'en') !== false && strpos($_SERVER['HTTP_ACCEPT_LANGUAGE'], 'zh') === false || strpos($user_agent, 'en-') !== false && strpos($user_agent, 'zh') === false) {
    exit('您当前浏览器不支持或操作系统语言设置非中文,无法访问本站!');
}
if (preg_match("/Windows NT 6.1/", $user_agent) && $http_accept == '*/*' || preg_match("/Windows NT 5.1/", $user_agent) && $http_accept == '*/*' || preg_match("/vnd.wap.wml/", $http_accept) && preg_match("/Windows NT 5.1/", $user_agent)) {
    exit('您的浏览器版本太低,请复制到其他浏览器打开!');
}

结合数据库获取配置信息

use think\facade\Db;

/**
 * 获取配置信息
 * @param string $name 获取一个配置|保存一个配置
 * @param $value 要保存的值
 * @param $json 是否强制要保存的数据类型为数组并且保存为JSON字符格式
 */
function options($name = false, $value = false, $json = false)
{
  if ($name === false) {
    return Options::all();
  }
  if ($value !== false) {
    if ($json && !is_array($value) && !is_object($value)) sysmsg('保存options表的 ' . $name . ' 字段失败,已开启强制JSON数据类型,但要保存的数据非数组或对象类型,value值:' . var_dump($value));
    return Options::save($name, $value, $json);
  }
  return Options::get($name);
}

class Options
{
  private static $options = null;

  private static array $_options = [];

  public static function initialize()
  {
    if (is_null(self::$options)) {
      $select = Db::name('options')->select();
      self::$options = [];
      foreach ($select as $value) {
        // var_dump($value);
        self::$options[$value['name']] = $value['json'] ? json_decode(empty($value['value']) ? '[]' : $value['value'], true) : $value['value'];
        self::$_options[$value['name']] = $value;
      }
    }
  }

  public static function get($name)
  {
    return isset(self::$options[$name]) ? self::$options[$name] : null;
  }

  public static function all()
  {
    return self::$options;
  }

  public static function save(string $name, $value)
  {
    // 查询配置是否存在
    $find = Db::name('options')->where('name', $name)->find();
    // 如果配置存在
    if (array_key_exists($name, self::$_options) || $find) {
      return self::update($name, $value);
    } else {
      return self::insert($name, $value);
    }
  }

  public static function insert(string $name, $value)
  {
    if (is_array($value) || is_object($value)) {
      $value = Json::encode($value);
      $json = 1;
    } else {
      $json = 0;
    }
    // 插入虚拟模型数据
    self::model($name, $value, $json);
    // 插入数据库数据
    return Db::name('options')->insert(['name' => $name, 'value' => $value, 'json' => $json]);
  }

  /**
   * 设置虚拟模型数据
   */
  public static function model(string $name, $value, $json = 0)
  {
    global $options;
    $options[$name] = $value;
    self::$options[$name] = $value;
    self::$_options[$name] = ['name' => $name, 'value' => $value, 'json' => $json];
    return true;
  }

  public static function update(string $name, $value)
  {
    if (is_array($value) || is_object($value)) {
      $value = Json::encode($value);
      $json = 1;
    } else {
      $json = 0;
    }
    // 更新虚拟模型数据
    self::model($name, $value, $json);
    // 更新数据库数据
    return Db::name('options')->where('name', $name)->update(['value' => $value, 'json' => $json]);
  }
}

动态创建HTML的Element元素

/**
 * 动态创建Element元素
 *
 * @param string $element 要创建的标签
 * @return system\html\ElementBuilder
 */
function element($element)
{
  return new system\html\ElementBuilder($element);
}

/**
 * @package ElementBuilder
 * @description 动态创建HTML的Element标签
 * @author 易航
 * @version 1.0
 * @link http://nav.bri6.cn
 */
class ElementBuilder
{

  private $options = [
    'element' => 'div',
    'inner' => null,
    'attributes' => null
  ];

  private function attributes($attributes)
  {
    return FormBuilder::attributes($attributes);
  }

  public function __construct($element)
  {
    $this->options['element'] = $element;
  }

  /**
   * 设置标签内部的HTML内容
   * @param $innerHTML 要设置的标签HTML内容
   * @return $this
   */
  public function innerHTML($innerHTML)
  {
    $this->options['inner'] = $innerHTML;
    return $this;
  }

  /**
   * 设置标签内部的文本内容
   * @param $innerText 要设置的标签文本内容
   * @return $this
   */
  public function innerText($innerText)
  {
    $this->options['inner'] = empty($innerText) ? $innerText : htmlentities($innerText);
    return $this;
  }

  /**
   * 批量设置标签的属性
   * @param $attributes
   * @return $this
   */
  public function attr($attributes, $content = null)
  {
    if (is_array($attributes)) {
      foreach ($attributes as $key => $value) {
        $this->options['attributes'][$key] = $value;
      }
    }
    if (is_string($attributes)) {
      $this->options['attributes'][$attributes] = $content;
    }
    return $this;
  }

  /**
   * 获取生成的HTML内容
   * @return string
   */
  public function get($html = null)
  {
    $this->innerHTML($html);
    $element = $this->options['element'];
    $content = $this->options['inner'];
    $attributes = $this->attributes($this->options['attributes']);
    if ($content === false) {
      $html = "<$element$attributes />";
    } else {
      $html = "<$element$attributes>$content</$element>";
    }
    return $html;
  }

  public function __toString()
  {
    return $this->get($this->options['inner']);
  }
}

生成站点URl

/**
 * 生成站点URl
 * @param $path URL路径
 * @param $param URL参数
 */
function url($path, $param = null)
{
  $url = 'http://' . DOMAIN . '/' . $path;
  if ($param) {
    $param = http_build_query($param);
    $url = strstr($url, '?') ? trim($url, '&') . '&' .  $param : $url . '?' .  $param;
  }
  return $url;
}

解压ZIP文件到指定目录

function zipExtract($src, $dest)
{
  // 通过ZipArchive的对象处理zip文件
  $zip = new ZipArchive(); //新建一个ZipArchive的对象
  /*
  $zip->open这个方法的参数表示处理的zip文件名。
  如果对zip文件对象操作成功,$zip->open这个方法会返回TRUE
  */
  if ($zip->open($src) === true) {
    $zip->extractTo($dest); //假设解压缩到$dest路径文件夹的子文件夹php
    $zip->close(); //关闭处理的zip文件
    return true;
  }
  return false;
}

删除整个目录

function deldir($dir)
{
    if (!is_dir($dir)) return false;
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (!is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

获取指定目录下的文件和目录列表

/**
 * 获取指定目录下的文件和目录列表
 */
class DirScanner
{
    private array $list;

    private string $directory;

    /**
     * @param string $directory 要扫描的目录
     */
    public function __construct(string $directory)
    {
        $this->directory = str_replace(['//', '\\\\'], ['/', '\\'], $directory);
        $this->directory = preg_match('/^\/|\\\$/', $this->directory) ? $this->directory :  $this->directory . DIRECTORY_SEPARATOR;
        $this->list = array_diff(scandir($directory), ['.', '..']);
    }

    /**
     * 只获取文件
     */
    public function files(array $suffixes = []): array
    {
        return $this->filter($suffixes, 'is_file');
    }

    /**
     * 只获取目录
     */
    public function dirs(): array
    {
        return $this->filter([], 'is_dir');
    }

    /**
     * 获取所有文件和目录
     */
    public function all(): array
    {
        return $this->list;
    }

    /**
     * 过滤列表
     */
    private function filter(array $suffixes, callable $callback): array
    {
        $directory = $this->directory;
        return array_filter($this->list, function ($item) use ($directory, $suffixes, $callback) {
            $path = $directory . DIRECTORY_SEPARATOR . $item;
            if (!empty($suffixes) && is_file($path)) {
                $extension = pathinfo($item, PATHINFO_EXTENSION);
                if (!in_array($extension, $suffixes)) return false;
            }
            return $callback($path);
        });
    }
}

/**
 * 获取指定目录下的文件和目录列表
 * 
 * @param string $directory 要扫描的目录
 * @return DirScanner
 */
function scan_dir(string $directory): DirScanner
{
    return new DirScanner($directory);
}
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    请登录后查看评论内容