This article will introduce to you how to use oss web direct transmission in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
Advantages of direct transmission: No need to go through the server, direct transmission from the front end to oss
, thus reducing server bandwidth usage and speeding up user uploads speed.
What this article talks about does not require the installation of expansion packs. It only has direct transmission function, which is very lightweight.
I wrote it with reference to https://github.com/iiDestiny/flysystem-oss. If you need to use other oss
functions in php
, then An expansion pack would be more appropriate.
<?php namespace Service;class OssUploadSignature{ private $accessKeyId; private $accessKeySecret; private $expire = 300; // 5分钟有效期 private $bucketHost; // Bucket 域名 private $conditions = [ // 限制 [ 'content-length-range', // 内容限制 0, // 最小上传 10 * 1024 * 1024 // 最大上传10m ], [ 0 => 'starts-with', 1 => '$key', // 必须带key 2 => 'images/', // 如:/images 只能放在/images的路径 ] ]; public function setBucketHost($bucketHost) { $this->bucketHost = $bucketHost; return $this; } public function setAccessKeyId($accessKeyId) { $this->accessKeyId = $accessKeyId; return $this; } public function setAccessKeySecret($accessKeySecret) { $this->accessKeySecret = $accessKeySecret; return $this; } public function signatureConfig() { $end = time() + $this->expire; $arr = [ 'expiration' => $this->gmt_iso8601($end), 'conditions' => $this->conditions, ]; $base64Policy = base64_encode( json_encode($arr) ); $signature = base64_encode(hash_hmac('sha1', $base64Policy, $this->accessKeySecret, true)); return [ 'OSSAccessKeyId' => $this->accessKeyId, 'policy' => $base64Policy, 'signature' => $signature, 'expire' => $end, 'bucketHost' => $this->bucketHost ]; } // fix bug https://connect.console.aliyun.com/connect/detail/162632 public function gmt_iso8601($time) { return (new \DateTime(null, new \DateTimeZone('UTC')))->setTimestamp($time)->format('Y-m-d\TH:i:s\Z'); }}
bucketHost can be viewed at
oss.
policy, pay attention to whether there are line breaks (I didn’t even notice...)
Recommended study: " PHP Video Tutorial》
The above is the detailed content of How to use oss web direct transmission in php. For more information, please follow other related articles on the PHP Chinese website!