PHP阿里云OSS,七牛云 上传文件
来源:
七牛云PHPSDK下载:http://pan.baidu.com/s/1o69TGcM
7.X版本:
DEMO:
<?phprequire_once './vendor/autoload.php'; use Qiniu\Auth;use Qiniu\Storage\BucketManager;use Qiniu\Storage\UploadManager; $accessKey = 'accessKey';$secretKey = 'secretKey';$auth = new Auth($accessKey, $secretKey); $bucketMgr = New BucketManager($auth);$bucket = 'wsy100';$key = 'QQ图片20150604131612.png'; //文件删除/* $err = $bucketMgr->delete($bucket, $key);if ($err !== null) { var_dump($err);} else { echo 'delete ok';} *//* * 单个文件 * list($ret, $err) = $bucketMgr->stat($bucket, $key);echo "\n====> stat result: \n";if ($err !== null) { var_dump($err);} else { var_dump($ret);} */$token = $auth->uploadToken($bucket);$uploadMgr = New UploadManager(); list($ret, $err) = $uploadMgr->putFile($token, time().'.jpg', 'C:\Users\Administrator\Pictures\images\20150604131612.png');echo "\n====> putFile result: \n";if ($err !== null) { var_dump($err);} else { print_r($ret);}
上传远程URL文件:
$url='http://img.hb.aicdn.com/b3ddfada312d19dc0be9f17f9ca497767cb657871f50a-Hj44uu_fw658';$ret=$bucketMgr->fetch($url, $bucket, $key);print_r($ret);
2.获取bucket所有文件
list($items, $marker, $err) = $bucketMgr->listFiles($bucket, $prefix = null, $marker = null, $limit = 1000, $delimiter = null);echo "\n====> List result: \n";if ($err !== null) { var_dump($err);} else { echo "Marker: $marker\n"; echo 'items====>\n'; print_r($items); //echo (string)$items[10]['putTime']; //echo strtotime($items[10]['putTime']);}
3.删除文件
$err = $bucketMgr->delete($bucket, $key);if ($err !== null) { var_dump($err);} else { echo 'delete ok';}
4.获取单个文件信息
list($ret, $err) = $bucketMgr->stat($bucket, $key);echo "\n====> stat result: \n";if ($err !== null) { var_dump($err);} else { print_r($ret);}
5.文件上传
$token = $auth->uploadToken($bucket);$uploadMgr = New UploadManager(); list($ret, $err) = $uploadMgr->putFile($token, date('Y-m-d-H-i-s',time()).'.jpg', 'C:\Users\Administrator\Pictures\20150504194317.png');echo "\n====> putFile result: \n";if ($err !== null) { var_dump($err);} else { print_r($ret);}
puttime Epoch时间戳的转换
$puttime=substr(str_replace('.', '','1.4357550505488E+16'),0,10);echo $puttime;
trim替换也可以,暂时没找到系统函数转换,也可以除10000000
OR
$puttime=date('Y-m-d H:i:s',1.4357550505488E+16/10000000);
上传策略生成:
$data['scope']='wsy100';$data['deadline']=time()+3600;$encoded=urlsafe_base64_encode(json_encode($data));$signature=hash_hmac('sha1',$encoded,'KEY',true);$encode_signed = urlsafe_base64_encode($signature);$UploadToken='AK:'.$encode_signed.':'.$encoded; echo $UploadToken; /* 第三步:对json序列化后的上传策略进行URL安全的Base64编码,得到如下encoded:eyJzY29wZSI6IndzeTEwMCIsImRlYWRsaW5lIjoxNDM1ODE3NzA5fQ==第四步:用SecretKey对编码后的上传策略进行HMAC-SHA1加密,并且做URL安全的Base64编码,得到如下的encoded_signed:Yu1NpdDvbM1NPr4IxTFsMBLxDQc=第五步:将 AccessKey、encode_signed 和 encoded 用 “:” 连接起来,得到如下的UploadToken:*/ function urlsafe_base64_encode($data) { $data = base64_encode($data); $data = str_replace(array('+','/'),array('-','_'),$data); return $data;}
写完才知道有现成的
$token = $auth->uploadToken($bucket);
可以用。权当练手了吧
ajax上传预览见:
DEMO:http://t.zy62.com/wx.php/Index/upload
API:http://developer.qiniu.com/docs/v6/api/reference/rs/stat.html
6.X版本
6.x版本没有fetch获取远程URL资源上传的方法,封装了个.
七牛文档:http://developer.qiniu.com/docs/v6/sdk/legacy-php-sdk.html
封装好的下载地址:http://pan.baidu.com/s/1gdu95yb
在qiniu/conf.php 15行后加了:
$QINIU_FETCH_HOST='http://iovip.qbox.me';//fetch URL
rsf.php末尾增加:
/** * 从指定URL抓取资源,并将该资源存储到指定空间中 * * @param $url 指定的URL * @param $bucket 目标资源空间 * @param $key 目标资源文件名 * * @return array[] 包含已拉取的文件信息。 * 成功时: [ * [ * "hash" => "<Hash string>", * "key" => "<Key string>" * ], * null * ] * * 失败时: [ * null, * Qiniu/Http/Error * ] * @link http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html */function Qiniu_Fetch($self,$url, $bucket, $key) { global $QINIU_FETCH_HOST; $resource = base64_urlSafeEncode ( $url ); $to = entry ( $bucket, $key ); $url = $QINIU_FETCH_HOST . '/fetch/' . $resource . '/to/' . $to; return Qiniu_Client_Call ( $self, $url );}/** * 计算七牛API中的数据格式 * * @param $bucket 待操作的空间名 * @param $key 待操作的文件名 * * @return 符合七牛API规格的数据格式 * @link http://developer.qiniu.com/docs/v6/api/reference/data-formats.html */function entry($bucket, $key) { $en = $bucket; if (! empty ( $key )) { $en = $bucket . ':' . $key; } return base64_urlSafeEncode ( $en );}/** * 对提供的数据进行urlsafe的base64编码。 * * @param string $data 待编码的数据,一般为字符串 * * @return string 编码后的字符串 * @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64 */function base64_urlSafeEncode($data){ $find = array('+', '/'); $replace = array('-', '_'); return str_replace($find, $replace, base64_encode($data));}
使用方法:
Qiniu_Fetch($client,'http://phpcto.b0.upaiyun.com/courselesson/3/2015104031642-h23061.mp4',$bucket,time().'.mp4');
获取所有文件信息:
<?phprequire_once("qiniu/rs.php");require_once("qiniu/rsf.php");$bucket = 'wsy100';$key = "qqConnect_Server_SDK_php_v2.0.zip";$accessKey = '';$secretKey = ''; Qiniu_SetKeys($accessKey, $secretKey);$client = new Qiniu_MacHttpClient(null);$putPolicy = new Qiniu_RS_PutPolicy($bucket);$upToken = $putPolicy->Token(null); //echo $upToken;exit();/* list($ret, $err) = Qiniu_RS_Stat($client, $bucket, $key);echo "Qiniu_RS_Stat result: \n";if ($err !== null) { print_r($err);} else { $ret['putTime']=date('Y-m-d H:i:s',$ret['putTime']/10000000); print_r($ret);} */print_r(Qiniu_RSF_ListPrefix($client,$bucket));
获取bucket资源列表
<?phprequire_once './aliyun.php';use \Aliyun\OSS\OSSClient;try { $client = OSSClient::factory(array( 'AccessKeyId' => '//Your AccessKeyId', 'AccessKeySecret' => 'Your AccessKeySecret', //在https://ak-console.aliyun.com/获取));$client->createBucket(array( 'Bucket' => 'Your Bucket',)); $objectListing = $client->listObjects(array( 'Bucket' => 'Your Bucket',));foreach ($objectListing->getObjectSummarys() as $objectSummary) { echo $objectSummary->getKey();}} catch (\Aliyun\OSS\Exceptions\OSSException $ex) { echo "Error: " . $ex->getErrorCode() . "\n";} catch (\Aliyun\Common\Exceptions\ClientException $ex) { echo "ClientError: " . $ex->getMessage() . "\n";}
Fatal error: Uncaught exception 'Aliyun\OSS\Exceptions\OSSException' with message 'The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.'解决方案
原因是PHP SDK默认使用杭州节点,而你的bucket非杭州节点,解决方案,在初始化时指定节点.
$client = OSSClient::factory(array( 'AccessKeyId' => 'Your AccessKeyId', 'AccessKeySecret' => 'Your AccessKeySecret', 'Endpoint' => 'http://oss-cn-beijing.aliyuncs.com',//北京节点 ));

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
