php上传图片

 

 

    /**
     * Notes: 文件上传
     * Created by jessie@seabig.cn
     * DateTime: 2020-02-18 16:17
     */
    public function UploadImg()
    {
        $this->_globals();
        //数据过滤
        if (!$_FILES) {
            die(json_encode(array("status" => "false","code" => "500", "msg" => "上传失败,请上传文件")));
        }
        $savepath = _FILE_PATH;
        $tempFile = $_FILES['file']['tmp_name'];
        //获取文件
        $file = $_FILES['file'];
        //$savepath = _FILE_PATH;
        $tempFile = $file['tmp_name'];

        //获取文件名
        $name = substr($file['name'], 0, strrpos($file['name'], "."));

        //获取文件后缀名
        $ext = strtolower(substr(strrchr($file['name'],'.'),1));

        //定义文件保存路径、递归创建文件夹
        $mkpath = $savepath . "/" . date("Y") . "/" . date("m") . "/" . date("d");

        $this->mkpath($mkpath);

        //生成文件名
        $filesname = date("Y") . "/" . date("m") . "/" . date("d") . "/" . date('His') . strtolower($this->random(16)) . "." . $ext;
        $move = move_uploaded_file($tempFile, $savepath . "/" . $filesname);
        if ($move) {
//            layui富文本编辑器上传图片接口 (返回格式不一样)
            die(json_encode(array("status" => "true","code" => "0", "msg" => "上传成功", "data" => array("src" => '/uploads/'.$filesname, "title" => $name))));
        } else {
            die(json_encode(array("status" => "false","code" => "500", "msg" => "上传失败")));
        }
    }

    /**
     * 生成随机数字
     *
     * @param int 长度 $length
     * @param int 是否仅限数字 $numeric
     * @return unknown
     */
    private function random($length, $numeric = 0)
    {
        PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
        if ($numeric) {
            $hash = sprintf('%0' . $length . 'd', mt_rand(0, pow(10, $length) - 1));
        } else {
            $hash = '';
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
            $max = strlen($chars) - 1;
            for ($i = 0; $i < $length; $i++) {
                $hash .= $chars[mt_rand(0, $max)];
            }
        }
        return $hash;
    }


    /**
     *创建多级文件夹 *
     * @param 路径 /data/wwwroot/vhost/abc.seabig.cn/uploads/2002/
     * @param 权限 755/777 $mode
     */
    public function mkpath($path, $mode = 0777)
    {
        $path = str_replace("\\", "_|", $path); //将$path 中的 "\\" 替换为 "_|"
        $path = str_replace("/", "_|", $path);
        $path = str_replace("__", "_|", $path);
        $dirs = explode("_|", $path);
        $path = $dirs[0];
        for ($i = 1; $i < count($dirs); $i++) {
            $path .= "/" . $dirs[$i];
            if (!is_dir($path)) {
                mkdir($path, $mode);
            }
        }
    }

 

posted @ 2020-03-30 19:31  北满  阅读(234)  评论(0编辑  收藏  举报