REC

PHP各种常用函数方法封装

易航
3年前发布 /正在检测是否收录...

当前日期和时间

/**
 * 当前日期和时间
 * @return string
 */
function date_time(): string
{
    return date('Y-m-d H:i:s');
}

动态创建Element元素

/**
 * 动态创建Element元素
 *
 * @param string $element
 * @return ElementBuilder
 */
function element($element)
{
    return new ElementBuilder($element);
}

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

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

    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']);
    }
}

解压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;
}

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

/**
 * 获取指定目录下的文件和目录列表
 *
 * @param string $directory 要扫描的目录
 * @return DirScanner
 */
function scan_dir(string $directory)
{
    return new DirScanner($directory);
}

/**
 * 获取指定目录下的文件和目录列表
 */
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_values(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 . $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 目录的路径。
 * @param resource $context 上下文流(context stream) resource
 * @return bool
 */
function delete_directory(string $directory, $context = null)
{
    if (is_dir($directory)) {
        $objects = scandir($directory);
        foreach ($objects as $object) {
            if ($object != "." && $object != "..") {
                if (is_dir($directory . DIR_SEP . $object)) {
                    delete_directory($directory . DIR_SEP . $object);
                } else {
                    unlink($directory . DIR_SEP . $object);
                }
            }
        }
        rmdir($directory, $context);
    } elseif (is_file($directory)) {
        unlink($directory, $context);
    }
}

多维数组转对象

/**
 * 多维数组转对象
 * @param array $d
 * @return object
 */
function array_to_object(array $d): object
{
    if (is_array($d)) {
        $json = json_encode($d);
        return json_decode($json);
    } else {
        return $d;
    }
}

多维对象转数组

/**
 * 多维对象转数组
 * @param object|array $d
 * @return array
 */
function object_to_array($d)
{
    if (is_object($d)) {
        $d = get_object_vars($d); // 获取给定对象的属性
    }
    if (is_array($d)) {
        $function = __FUNCTION__;
        return array_map("self::$function", $d);
    } else {
        return $d;
    }
}

发送电子邮件

/**
 * 发送电子邮件
 * @access public
 * @param string $title 邮件标题
 * @param string $subtitle 邮件副标题
 * @param string $content 邮件内容
 * @param string $email 不填写则默认发送系统配置中的邮箱,优先程度:配置收件人>发信邮箱
 * @return bool|object
 */
function send_mail($title, $subtitle, $content, $email = null)
{
    $site = options('site');
    $mail = options('mail');
    if (empty($email)) {
        $email = empty($mail['recv']) ? $mail['account'] : $mail['recv'];
    }
    $PHPMailer = new \PHPMailer\PHPMailer\PHPMailer();
    $language = $PHPMailer->setLanguage('zh_cn');
    if (!$language) {
        return 'PHPMailer语言文件zh_cn加载失败';
    }
    $PHPMailer->isSMTP();
    $PHPMailer->SMTPAuth = true;
    $PHPMailer->CharSet = 'UTF-8';
    $PHPMailer->SMTPSecure = $mail['secure']; // 允许 TLS 或者ssl协议
    $PHPMailer->Host = $mail['smtp']; // SMTP服务器
    $PHPMailer->Port = $mail['port']; // 服务器端口 25 或者465
    $PHPMailer->FromName = $site['title']; //发件人昵称
    $PHPMailer->Username = $mail['account']; //邮箱账号
    $PHPMailer->From = $mail['account']; //邮箱账号
    $PHPMailer->Password = $mail['pwd']; //邮箱密码
    $PHPMailer->isHTML(true);
    $html = '<!DOCTYPE html><html lang="zh-cn"><head><meta charset="UTF-8"><meta name="viewport"content="width=device-width, initial-scale=1.0"></head><body><style>.container{width:95%;margin:0 auto;border-radius:8px;font-family:"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;box-shadow:0 2px 12px 0 rgba(0,0,0,0.1);word-break:break-all}.title{color:#fff;background:linear-gradient(-45deg,rgba(9,69,138,0.2),rgba(68,155,255,0.7),rgba(117,113,251,0.7),rgba(68,155,255,0.7),rgba(9,69,138,0.2));background-size:400%400%;background-position:50%100%;padding:15px;font-size:15px;line-height:1.5}</style><div class="container"><div class="title">{title}</div><div style="background: #fff;padding: 20px;font-size: 13px;color: #666;"><div style="margin-bottom: 20px;line-height: 1.5;">{subtitle}</div><div style="padding: 15px;margin-bottom: 20px;line-height: 1.5;background: repeating-linear-gradient(145deg, #f2f6fc, #f2f6fc 15px, #fff 0, #fff 25px);">{content}</div><div style="line-height: 2">请注意:此邮件由系统自动发送,请勿直接回复。<br>若此邮件不是您请求的,请忽略并删除!</div></div></div></body></html>';
    $PHPMailer->Body = strtr(
        $html,
        [
            "{title}" => $title . ' - ' . $site['title'],
            "{subtitle}" => $subtitle,
            "{content}" => $content,
        ]
    );
    $PHPMailer->addAddress($email);
    $PHPMailer->Subject = $title . ' - ' . $site['title'];
    if ($PHPMailer->send()) {
        return true;
    } else {
        return $PHPMailer->ErrorInfo;
    }
}

获取配置信息

function options($name = false, $value = false)
{
    if ($name === false && $value == false) {
        return Options::all();
    }
    if (func_num_args() == 1) {
        returnOptions::get($name);
    }
    return Options::save($name, $value);
}
class Options
{
    private static $options = null;

    public static function initialize()
    {
        if (is_null(self::$options)) {
            $select = Db::name('options')->select();
            self::$options = [];
            foreach ($select as $value) {
                self::$options[$value['name']] = $value['value'];
            }
        }
    }

    public static function get($name)
    {
        $name_list = explode('.', $name); // 将路径分解成键名数组
        $value = self::$options; // 初始化$value为数组的根
        // 遍历键名数组,逐级深入到数组中
        foreach ($name_list as $name_value) {
            if (isset($value[$name_value])) {
                $value = $value[$name_value]; // 如果键存在,更新$value
            } else {
                return null; // 如果键不存在,返回null或者你可以选择抛出异常
            }
        }
        return $value; // 返回最终找到的值
    }

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

    public static function save(string $name, $value)
    {
        if (array_key_exists($name, self::$options)) {
            $save = self::update($name, $value);
        } else {
            $save = self::insert($name, $value);
        }
        // 保存虚拟模型数据
        self::model($name, $value);
        return $save;
    }

    public static function insert(string $name, $value)
    {
        // 插入虚拟模型数据
        self::model($name, $value);
        // 插入数据库数据
        return Db::name('options')->insert(['name' => $name, 'value' => $value]);
    }

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

    public static function update(string $name, $value)
    {
        // 更新虚拟模型数据
        self::model($name, $value);
        // 更新数据库数据
        return Db::name('options')->where('name', $name)->update(['value' => $value]);
    }
}

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

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));
    }
}
© 版权声明
本站用户发帖仅代表本站用户个人观点,并不代表本站赞同其观点和对其真实性负责。
转载本网站任何内容,请按照转载方式正确书写本站原文地址。
THE END
喜欢就支持一下吧
点赞 2 分享 赞赏
评论 抢沙发
取消 登录评论