Detailed explanation of uploading files using OSS in PHP

Time:2022-9-15
Table of contents
  • 1. Install Alibaba Cloud oss ​​sdk
  • 2. Use
    • 1. Obtain OSS AccessKeyId and AccessKeySecret
    • 2. Simple upload Html processing
    • 3. The controller handles OssImageController.php
    •  4. The service layer handles OssImageService.php
    • 5. oss instance and parameter acquisition package AliOss.php
    • 6. The result is that the upload can be successful
  • 3. Problem description

    1. Install Alibaba Cloud oss ​​sdk

    Execute the following command in the root directory of the website to install the oss sdk.

    composer require aliyuncs/oss-sdk-php

    After installation, you will find a folder named `aliyuncs` in the website root /vendor.

    Note: [Alibaba Cloud oss ​​- sdk documentation (don't need to pay attention)](https://help.aliyun.com/document_detail/32099.html "Official oss – sdk documentation")

    2. Use

    1. Obtain OSS AccessKeyId and AccessKeySecret

    If you don't have these two data, you can refer to https://blog.csdn.net/m_nanle_xiaobudiu/article/details/101756805.

    2. Simple upload Html processing

    upload.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Xiaobu Diu personal website - oss picture upload</title>
    </head>
    <body>
        <form action="oss-image/upload-image.json" method="post" enctype="multipart/form-data">
            <label for="file">file name:</label>
            <input type="file" name="image"><br>
            <input type="submit" name="submit" value="提交">
        </form>
    </body>
    </html>

    3. The controller handles OssImageController.php

    Send the request directly to the service without paying attention to this layer

    <?php
    declare(strict_types = 1);
    namespace app\controllers;
    use app\services\OssImageService;
    class OssImageController extends BaseController
    {
        /**
         * oss upload pictures
         *
         * @return string
         * @throws \OSS\Core\OssException
         */
        public function actionUploadImage()
        {
            return $this->response(OssImageService::service()->uploadImage());
        }
    }

     4. The service layer handles OssImageService.php

    PHP is processed in this layer, just pay attention to this layer

    <?php
    declare(strict_types = 1);
    namespace app\services;
    use app\extensions\AliOss;
    class OssImageService extends BaseService
    {
        /**
         * oss upload pictures
         *
         * @return array
         * @throws \OSS\Core\OssException
         */
        public function uploadImage()
        {
                $ossClient  = AliOss::getOssClient();
                $bucketName = AliOss::getBucketName();
                // file name
                $fileName = $_FILES['image']['name'];
                // temporary file location
                $tmpFile = $_FILES['image']['tmp_name'];
                // Define the oss location where the file is stored
                $ossPath = 'test/'.date('Y-m-d').'/'.date('Hi') .mt_rand(10000,99999);
                // define oss object
                $object = $ossPath .'.' .$this->getExtension($fileName);
                // Execute upload and get return oss information
                $info = $ossClient->uploadFile($bucketName, $object, $tmpFile);
                $ossUrl = $info['oss-request-url'];
                // If the image's protocol is http, convert to https
                if (substr($ossUrl, 0, 4) == 'http') {
                    $ossUrl = substr_replace($ossUrl, 'https', 0, 4);
                }
                $data = [
                    'file_url'  => $ossUrl,
                    'file_name' => basename($ossUrl)
                ];
                return $data;
        }
        /**
         * return file extension
         *
         * @param $fileName
         * @return mixed
         */
        private function getExtension($fileName)
        {
            return pathinfo($fileName)['extension'];
        }
    }

    5. oss instance and parameter acquisition package AliOss.php

    <?php
    declare(strict_types = 1);
    namespace app\extensions;
    use OSS\OssClient;
    use OSS\Core\OssException;
    /**
     *Alibaba cloud oss ​​file upload
     */
    class AliOss
    {
        const endpoint        = 'oss-cn-hongkong.aliyuncs.com';
        const accessKeyId     = 'LSDFskkdDDSSdkfg';
        const accessKeySecret = 'LT9cG3JkGKffRPalgk4n33lk8Ll41d';
        const bucket          = 'hk-server';
        /**
         * According to the Config configuration, get an OssClient instance
         *
         * @return OssClient an OssClient instance
         */
        public static function getOssClient()
        {
            try {
                $ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
            } catch (OssException $e) {
                printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
                printf($e->getMessage() . "\n");
                return null;
            }
            return $ossClient;
        }
        public static function getBucketName()
        {
            return self::bucket;
        }
    }

    6. The result is that the upload can be successful

    Returns the full access url of the image in oss

    
    {
        status: 1,
        msg: "success",
        data: {
            file_url: "https://hk-server.oss-cn-hongkong.aliyuncs.com/test/2018-08-22/211753008.jpg",
            file_name: "211753008.jpg"
        }
    }

    At this time, we can get the picture normally by visiting https://hk-server.oss-cn-hongkong.aliyuncs.com/test/2018-08-22/211753008.jpg, and it is also possible in the oss management console Find the uploaded file.

    This just uploads the file to oss and returns the url of the file to the front end, but does not store the file's information locally. It is suggested here that after receiving the url, the front-end, together with other data of the file (such as classification, file name, etc.), request another interface of the back-end to store the information in the local database.

    3. Problem description

    There may be problems such as The OSS Access Key Id you provided does not exist in our records, don't panic, just regenerate it.

    The above is the detailed content of using OSS to upload files in PHP. For more information about using OSS in PHP, please pay attention to other related articles on developpaer!