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

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

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











In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
