用PHP操作OSS学习笔记
笔记一:如何展示自己的bucket列表:
<?php /** * 加载sdk包以及错误代码包 */ require_once 'oss_php_sdk/sdk.class.php'; $oss_sdk_service = new ALIOSS(); $bucket_list = $oss_sdk_service->list_bucket(); $doc = new DOMDocument(); $doc->loadXML($bucket_list->body); echo "<p><b>My bucket list:</b></p>"; echo "<ul>"; $buckets = $doc->getElementsByTagName("Bucket"); foreach( $buckets as $bucket ) { $names = $bucket->getElementsByTagName( "Name" ); $name = $names->item(0)->nodeValue; $ctimes = $bucket->getElementsByTagName( "CreationDate" ); $ctime = $ctimes->item(0)->nodeValue; echo "<li>$name [create time: $ctime]</li>\n"; } echo "</ul>"; ?>
笔记二:通过web上传图片到OSS
先写一个简单的web,用来让用户选择上传文件:
<html> <body> <form action="upload_img.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
再创建一个名为“upload_img.php”的文件,用来执行上传图片到OSS的命令,文件内容如下
<?php /** * 加载sdk包以及错误代码包 */ require_once 'oss_php_sdk/sdk.class.php'; $oss_sdk_service = new ALIOSS(); $bucket = '你的bucket名字'; if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 2000000)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " KB<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; $content = ''; $length = 0; $fp = fopen($_FILES["file"]["tmp_name"],'r'); if($fp) { $f = fstat($fp); $length = $f['size']; while(!feof($fp)) { $content .= fgets($fp,8192); } } $upload_file_options = array('content' => $content, 'length' => $length); $upload_file_by_content = $oss_sdk_service->upload_file_by_content($bucket, $_FILES["file"]["name"], $upload_file_options); $img_url = "http://storage.aliyun.com/" . $bucket . "/" . $_FILES["file"]["name"]; echo "Upload successfully! The OSS URL of this file: " . $img_url . "<br />"; echo "If the bucket is public-read, the uploaded image can be shown as:" . "<br />"; echo "<img src=$img_url />"; } } else { echo "Invalid file"; } ?>