Upload PHP files to OSS and Delete remote alicloud OSS files

Time:2022-5-7

When deleting, remember not to take the domain name or ‘/’ as the path symbol. For example, the full path is: ‘ https://hxty.oss-cn-beijing.aliyuncs.com/data/pdf/contract/2021-06-16/HXSHB21061611594482340c.pdf ‘is the path here_ The file path is: ‘data / PDF / contract / 2021-06-16 / hxshb2106161594482340c pdf’。

<?php
include './aliyun-oss-php-sdk-2.4.2/autoload.php';
 
use OSS\OssClient;
use OSS\Core\OssException;
 
error_reporting(E_ALL);
ini_ set('display_errors', 1); // error message
ini_ set('display_startup_errors', 1); // PHP startup error message
session_start();
/**
 *Take two decimal places
 *@ param type $STR number with decimal
 *@ return type returns the exact two digit decimals
 */
 
function num_format($str) {
    if (strpos($str, '.') === false) {
        return $str;
    }
    $retArr = explode(".", $str);
    $strs = substr($retArr[1], 0, 2);
    return $retArr[0] . "." . $strs;
}
 
function create_folders($dir) {
    return is_dir($dir) or ( create_folders(dirname($dir)) and mkdir(iconv("UTF-8", "GBK", $dir), 0777, true));
}
$file = $_FILES['file'];
 
$accessKeyId = '';// Ram alioss background can get
$accessKeySecret = '';// Ram alioss background can get
$endpoint = 'oss-cn-beijing. aliyuncs. com';// You can get the background overview of alioss
$bucket = 'planet-cross';// Create a group, whatever you want, with normal permissions
echo '<pre>';
var_dump($_SESSION);
if ($file) {
    $filename = "/upload/image/" . date("Ymd");
    if (!file_exists("." . $filename)) {
        create_folders("." . $filename);
    }
//Get suffix
    $ary = explode('.', $file['name']);
    $su = end($ary);
//File name
    $filenames = $filename . "/" . time() . rand(1, 10000) . "." . $su;
    move_uploaded_file($file['tmp_name'], "." . $filenames);
 
    $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
    $filenames = ltrim($filenames, '/'); // Remove the first '/'
//Start uploading
    $pic = $filenames;
    try {
        $oss = $ossClient->uploadFile($bucket, $pic, $filenames);
        $filenames = $oss['info']['url'];
        $_SESSION['file']=$filenames;
        echo $filenames;
        echo '<img src="' . $filenames . '" />';
        //Delete local file
    } catch (\OSS\Core\OssException $e) {
        die("Failed to upload file ");
        return false;
    }
} else if(!empty($_SESSION['file'])){
    try {
        $patch=trim(parse_url($_SESSION['file'])['path'],'/');
        $ossClient = new \OSS\OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $oss=$ossClient->deleteObject($bucket,$patch);
        $_SESSION['file']=null;
    } catch (OssException $e) {
        printf(__FUNCTION__ . ": FAILED\n");
        printf($e->getMessage() . "\n");
        return;
    }
}
 
 
    /**
     *Delete file
     *You can delete files uploaded by calling Ajax file
     * @param type $path_ File path
     *When deleting, remember not to bring the domain name or / this path symbol
     */
    function delfile($path_file) {
        if (config('config.OSS_OPEN')) {
            try {
                //When deleting, remember not to take the domain name or '/' as the path symbol. For example, the full path is: ' https://hxty.oss-cn-beijing.aliyuncs.com/data/pdf/contract/2021-06-16/HXSHB21061611594482340c.pdf 'is the path here_ The file path is: 'data / PDF / contract / 2021-06-16 / hxshb2106161594482340c pdf'。
                $path_ file=trim(parse_url($path_file)['path'],'/');// Remove the domain name,
                $ossClient = new \OSS\OssClient(config('config.OSS_KEY'), config('config.OSS_SECRET'), config('config.OSS_ENDPOINT'));
                $ossClient->deleteObject(config('config.OSS_BUCKET'), $path_file);
            } catch (OssException $e) {
                printf(__FUNCTION__ . ": FAILED\n");
                printf($e->getMessage() . "\n");
                return;
            }
        } else {
            $val2 = "." . $path_file;
            if (file_exists($val2)) {
                $unlinkfilename = trim($path_file, "/");
                unlink($unlinkfilename);
            }
        }
    }

When deleting, remember not to take the domain name or ‘/’ as the path symbol. For example, the full path is: ‘ https://hxty.oss-cn-beijing.aliyuncs.com/data/pdf/contract/2021-06-16/HXSHB21061611594482340c.pdf ‘is the path here_ The file path is: ‘data / PDF / contract / 2021-06-16 / hxshb2106161594482340c pdf’。

This is the end of this article about uploading PHP files to OSS and deleting remote Alibaba cloud OSS files. For more information about PHP deleting Alibaba cloud OSS files, please search previous articles of developeppaer or continue to browse the relevant articles below. I hope you will support developeppaer in the future!