search
HomeBackend DevelopmentPHP TutorialPHP阿里云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));


阿里云OSS

获取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',//北京节点    ));


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools