As a recap from my previous article, CloudFiles is a an online storage service for your static content.
作为我上一篇文章的回顾,CloudFiles是一项针对您的静态内容的在线存储服务。
Rackspace provides a Software Development Kit (SDK) for multiple programming languages. They store their PHP SDK on GitHub. The PHP SDK requires PHP 5 with the following modules: cURL, FileInfo and mbstring.
Rackspace提供了用于多种编程语言的软件开发套件(SDK)。 他们将PHP SDK存储在GitHub上 。 PHP SDK需要具有以下模块PHP 5:cURL,FileInfo和mbstring。
In this tutorial we are going to review use of the PHP SDK with CloudFiles. Not all parts of the API will be covered but you will get a great start.
在本教程中,我们将回顾将PHP SDK与CloudFiles一起使用。 并非涵盖API的所有部分,但您将获得一个良好的开端。
Once you download the SDK you only need the following files and folders:
下载SDK后,您仅需要以下文件和文件夹:
share/ 分享/ cloudfiles.php cloudfiles.php cloudfiles_exceptions.php cloudfiles_exceptions.php cloudfiles_http.php cloudfiles_http.phpStarting off we have some basic tasks. We need to load the cloudfiles.php file, authenticate with CloudFiles, and create a connection using our authentication token.
首先,我们有一些基本任务。 我们需要加载cloudfiles.php文件,使用CloudFiles进行身份验证,并使用我们的身份验证令牌创建连接。
<?php $your_username = 'jeffk'; $your_api_key = 'longrandomapikey'; require 'cloudfiles.php'; /** * Authenticate using your Rackspace Cloud username and your API key obtained from the control panel **/ $auth = new CF_Authentication($your_username, $your_api_key); /** * If you use Cloud Files in the U.K. use **/ $auth = new CF_Authentication($your_username, $your_api_key, null, UK_AUTHURL); $auth->authenticate(); /** * Now we create the connection with our CF_Authentication instance **/ $connection = new CF_Connection($auth); ?>It’s that simple. Now that we’re connected our next step is to interact with a container.
就这么简单。 现在我们已连接,下一步是与容器进行交互。
We can create, delete, list, and open different containers. To interact with any container we are going to use our $connection object we created above.
我们可以创建,删除,列出和打开不同的容器。 为了与任何容器交互,我们将使用上面创建的$ connection对象。
Lets go through creating a container that stores our files.
让我们来创建一个存储文件的容器。
<?php /** * To create a container, use the $connection variable and call the create_container method. If the container * already exists it will return a container instance and NOT overwrite the container. **/ $images = $connection->create_container("images"); ?>This will return a container object. In the example we named it $images. This will be used to manipulate the container along with any objects in it. If you need to interact with any objects in a container you have to use the create_container method to to access it. Since the container already exists, it will return the instance and it won’t overwrite it.
这将返回一个容器对象。 在示例中,我们将其命名为$images 。 这将用于操纵容器及其中的任何对象。 如果需要与容器中的任何对象进行交互,则必须使用create_container方法来访问它。 由于该容器已经存在,它将返回该实例,并且不会覆盖该实例。
Now, deleting a container that is no longer needed. Note: you cannot remove a container that has objects (files) in it. If there are files inside it you must remove them all prior to deleting the container. At the end of the article there is a snippet for removing all objects and then deleting the container.
现在,删除不再需要的容器。 注意:您不能删除其中包含对象(文件)的容器。 如果其中包含文件,则必须先删除所有文件,然后再删除容器。 在文章的末尾有一个摘录,用于删除所有对象,然后删除容器。
<?php /** * To delete a container call the delete_container method. **/ $connection->delete_container("images"); ?>With these actions done, how about getting the containers? If you want an array of your containers with various information you can use the get_containers method.
完成这些操作后,如何获得容器? 如果您想要一个包含各种信息的容器数组,则可以使用get_containers方法。
<?php /** * Get an array of your available containers and display them. **/ $containers = $connection->get_containers(); foreach($containers as $container) { echo 'Name: '. $container->name; echo 'Number of Objects: '. $container->count; echo 'Bytes Stores: '.$container->bytes; } ?>If you only want the names of the containers we have the list_containers method:
如果只需要容器的名称,则可以使用list_containers方法:
<?php $containers = $connection->list_containers(); print_r($containers); // Returns Array([0] => "images") ?>By default all containers are private. To make them available on the Content Delivery Network and accessible by a url, we have to tell the API to make the container public. Naturally we can return it to private if need be.
默认情况下,所有容器都是私有的。 为了使它们在Content Delivery Network上可用并可以通过url访问,我们必须告诉API将容器公开。 当然,如果需要,我们可以将其归还给私人。
<?php /** * To make a container public use the containers instance and call make_public. You can * optionally include a timestamp for how long the file is cached on the CDN network. The * default is 86400 (1 day) * Calling this method returns the URI the container is available at. **/ $public_uri = $images->make_public(); /** * You can also get the URI by calling the cdn_uri or cdn_ssl_uri attributes **/ $uri => $images->cdn_uri; $https_uri = $images->cdn_ssl_uri; /** * To set a public container private you can call make_private. However, all the files in this container will still be available until the cache time expires. **/ $images->make_private(); ?>To create an object we have to carry over our container instance and use the create_object method with the name of the file. Once we do that, we have to send the contents of the file. There are two ways to do that. The easiest way is to use the load_from_filename method so it will gather all the information for us. The second way we specify the file and the size.
要创建一个对象,我们必须继承我们的容器实例,并使用带有文件名的create_object方法。 完成后,我们必须发送文件的内容。 有两种方法可以做到这一点。 最简单的方法是使用load_from_filename方法,以便它将为我们收集所有信息。 第二种方法是指定文件和大小。
<?php $avatar = $images->create_object('jeffs_avatar.jpg'); $avatar->load_from_filename('/home/user/photos/jeffs_avatar.jpg'); $file_name = '/home/user/photos/jeffs_avatar.jpg'); $file_size = (float) sprintf("%u", filesize($file_name)); $fp = open($file_name, 'r'); $avatar->write($fp, $file_size); ?>To get a private object we can use the steam method. This works really well for protecting content. It’s not just limited to images either, if you wanted to restrict access to a pdf document for your members only, this would be ideal.
要获取私有对象,我们可以使用steam方法。 这对于保护内容确实非常有效。 它也不仅限于图像,如果您只想限制成员访问pdf文档,那将是理想的选择。
<?php $img = $images->get_object('jeff.jpg'); header('Content-Type: '.$img->content_type); $output = fopen("php://output", "w"); $img->stream($output); fclose($output); ?>To delete an object we need to use our container and call the delete_object method.
要删除对象,我们需要使用我们的容器并调用delete_object方法。
<?php $images->delete_object('jeff.jpg'); ?>Here we have an example of scanning a folder for .jpg files and uploading them to Rackspace Cloud Files.
在这里,我们有一个扫描文件夹中的.jpg文件并将其上传到Rackspace Cloud Files的示例。
<?php $api_username = 'jeffk'; $api_key = 'myapikey'; $file_path = '/home/user/images'; require 'cloudfiles.php'; $auth = new CF_Authentication($api_username, $api_key); $auth->authenticate(); $connection = new CF_Connection($auth); $images = $connection->create_container("images"); $url = $images->make_public(); echo 'The url is '.$url; /** * Now that we have our connection and access to the container lets get our files. **/ if ($h = opendir($file_path)) { /** * We just opened the directory and now we are going to scan that directory for any files **/ while (false !== ($file = readdir($h))) { /** * Now we are going to get the extension of the file. If it matches "jpg" then we are going to upload it. * Otherwise we are going to ignore it. **/ $get_extension = explode('.', $file); if ($get_extension[count($get_extension)-1]=='jpg') { /** * Lets create the object and send it to CloudFiles **/ $img = $images->create_object($file); $img->load_from_filename($file_path.'/'.$file); /** Now we delete the image so we don't try to upload it again if we rerun the script **/ unset($img); } } /** * Close the handler for good measure **/ closedir($h); } ?>The next example is deleting a container that already contains objects.
下一个示例是删除已经包含对象的容器。
<?php $objects = $images->list_objects(); if (count($objects)>0) { foreach($objects as $o) { $images->delete_object($o); } } $connection->delete_container("images"); ?>What I provided here were a few basic examples. A few things you might add in are returning the url to the objects, error handling, or even making sure there are 1 or more objects waiting to be uploaded before connecting.
我在这里提供的是一些基本示例。 您可能要添加的一些内容是将URL返回给对象,错误处理,甚至确保在连接之前有1个或多个对象等待上载。
If you get an error as seen below you need to update your ca certificates, refer to your OS manual or web host to get them upgraded. After I successfully tested in my development environment I ran into this issue in production.
如果出现如下所示的错误,则需要更新ca证书,请参阅操作系统手册或网络主机以升级它们。 在开发环境中成功测试后,我在生产中遇到了这个问题。
* About to connect() to lon.auth.api.rackspacecloud.com port 443 * Trying 212.64.148.13... * connected * Connected to lon.auth.api.rackspacecloud.com (212.64.148.13) port 443 * successfully set certificate verify locations: * CAfile: /etc/pki/tls/certs/ca-bundle.crt CApath: none * SSL certificate problem, verify that the CA cert is OK. Details: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed * Closing connection #0 PHP Fatal error: Uncaught exception 'InvalidResponseException' with message 'Unexpected response (): ' in /usr/share/php/cloudfiles/cloudfiles.php:212 Stack trace: #0 /var/www/html/cloudtest.php(18): CF_Authentication->authenticate() #1 {main} thrown in /usr/share/php/cloudfiles/cloudfiles.php on line 212 Fatal error: Uncaught exception 'InvalidResponseException' with message 'Unexpected response (): ' in /usr/share/php/cloudfiles/cloudfiles.php:21Next, Rackspace uses exceptions when errors occur. Wrapping your code in try{ } catch() { } blocks will allow you to get the error message instead of an “ Uncaught exception….” Listed below you can see the different exception classes they use and that they only extend the Exception class provided by php.
接下来,Rackspace在发生错误时使用异常。 将代码包装在try {} catch(){}块中将使您获得错误消息,而不是“ Uncaught exception…”。 在下面列出的列表中,您可以看到它们使用的不同异常类,并且它们仅扩展了php提供的Exception类。
class SyntaxException extends Exception { } class AuthenticationException extends Exception { } class InvalidResponseException extends Exception { } class NonEmptyContainerException extends Exception { } class NoSuchObjectException extends Exception { } class NoSuchContainerException extends Exception { } class NoSuchAccountException extends Exception { } class MisMatchedChecksumException extends Exception { } class IOException extends Exception { } class CDNNotEnabledException extends Exception { } class BadContentTypeException extends Exception { } class InvalidUTF8Exception extends Exception { } class ConnectionNotOpenException extends Exception { }If you were to attempt to remove a container that still had objects in it, the software development kit would throw a NonEmptyContainerException exception that you have to watch for.
如果要尝试删除仍然有对象的容器,则软件开发工具包将引发必须注意的NonEmptyContainerException异常。
<?php /** * Try to run the code **/ try { $connection->delete_container("images"); } /** * If there was an exception thrown, catch it and display the message **/ catch(NonEmptyContainerException $e) { echo $e->getMessage(); }If our container wasn’t empty it would display “Container must be empty prior to removing it”. If you didn’t catch the error it would provide an output such as:
如果我们的容器不是空的,则会显示“容器在移走之前必须为空”。 如果您没有发现错误,它将提供如下输出:
Fatal error: Uncaught exception 'NonEmptyContainerException' with message 'Container must be empty prior to removing it.' in /Users/kreitje/Development/test/ cloudfiles.php:560 Stack trace: #0 /Users/kreitje/Development/test/index.php(25): CF_Connection->delete_container('images') #1 {main} thrown in /Users/kreitje/ Development/test/cloudfiles.php on line 560If developing an application that customers will interact with you will want to catch any exception. Sometimes the error that gets displayed shows sensitive information. Above, you can see where my files are stored. Depending on the error, it’s possible that your API credentials may be displayed on the browser page.
如果开发客户可以与您进行交互的应用程序,则将希望捕获任何异常。 有时显示的错误显示敏感信息。 在上方,您可以看到我的文件存储在哪里。 根据错误,您的API凭证可能会显示在浏览器页面上。
In the software development kit there’s a docs folder that goes over these methods, along with a few extra ones. Now that you have the basics down and know where the documentation is, I challenge you to create a project that interacts with Rackspace CloudFiles.
在软件开发工具包中,有一个docs文件夹介绍这些方法,以及一些其他方法。 现在您已经掌握了基础知识,并且知道文档在哪里,现在我挑战您创建一个与Rackspace CloudFiles交互的项目。
Artush Images on Shutterstock
Shutterstock上的Artush Images
翻译自: https://www.sitepoint.com/using-the-rackspace-php-sdk-2/
相关资源:php-opencloud:用于OpenStack云PHP SDK-源码