[Seri] - Website đồng hồ - Tạo file function và load file. Tạo hàm upload hình ảnh

Tạo file function và tạo hàm upload hình ảnh

Bài này mình sẽ tạo file function và hàm upload hình ảnh 

Đầu tiên các bạn tạo cho mình file function.php nằm trong app\Helpers. Thư mục Helpers các bạn cũng tự tạo nhé

Và nội dung file function.php như sau

 if (!function_exists('upload_image'))
    {
        /**
         * @param $file [tên file trùng tên input]
         * @param array $extend [ định dạng file có thể upload được]
         * @return array|int [ tham số trả về là 1 mảng - nếu lỗi trả về int ]
         */
        function upload_image($file , $folder = '',array $extend  = array() )
        {
            $code = 1;
            // lay duong dan anh
            $baseFilename = public_path() . '/uploads/' . $_FILES[$file]['name'];

            // thong tin file
            $info = new SplFileInfo($baseFilename);

            // duoi file
            $ext = strtolower($info->getExtension());

            // kiem tra dinh dang file
            if ( ! $extend )
                $extend = ['png','jpg','jpeg','webp'];

            if( !in_array($ext,$extend))
                return $data['code'] = 0;

            // Tên file mới
            $nameFile = trim(str_replace('.'.$ext,'',strtolower($info->getFilename())));
            $filename = date('Y-m-d__').\Illuminate\Support\Str::slug($nameFile) . '.' . $ext;;
            
            // thu muc goc de upload
            $path = public_path().'/uploads/'.date('Y/m/d/');
            if ($folder)
                $path = public_path().'/uploads/'.$folder.'/'.date('Y/m/d/');

            if ( !\File::exists($path))
                mkdir($path,0777,true);

            // di chuyen file vao thu muc uploads
            move_uploaded_file($_FILES[$file]['tmp_name'], $path. $filename);

            $data = [
                'name'              => $filename,
                'code'              => $code,
                'path'              => $path,
                'path_img'          => 'uploads/'.$filename
            ];

            return $data;
        }
    }

Trong file function mình đã tạo một hàm upload_image với các thông số và mình cũng đã comment code lại nên mình không giải thích nữa nhé.

Load file 

Các bạn mở file composer.json và thêm đoạn này vào nhé

"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "files": [
            "app/Helpers/function.php"
        ]
    },

Các bạn tìm tới chỗ autoload và thêm cái chỗ files  như trên nhé.

Bài sau mình sẽ thực hành luôn phần upload ảnh nhé

Để lại comment của bạn nếu gặp khó khăn

Bài viết liên quan