how to: upload files to Rackspace Cloud Files using PHP API and get the public URL for the uploaded file.

Strongly recommended book
Alrighty! So I’ve joined Rackspace Cloud Files to make like simpler for myself when it comes to “I need more storage” :) .

To start with let me give you a brief insight on RackSpace Cloud files.

First up 

First of all in my opinion Rackspace Cloud is far better option than Amazon’s offering when it comes to pricing, black listed IP addresses and general speed of your transactions with your Cloud.

Cloud Files provides you and your applications unlimited online storage for media – items like backups, video files, or user content. And in an industry first, you can deliver that content to your users at blazing speeds over the market-leading global CDN platform, powered by Akamai Technologies, Inc.

You may also be interested in a command line Util that I wrote to backup your Rackspace Cloud files locally to your disk

Jaspreet Chahal's Command Line Rackspace Cloud Files Backup Util

Benefits

  • Scalable, dynamic storage. Use as much or little as you want and only pay for what you use.
  • Manage files through their well written and usable online control panel or pro-grammatically through their REST API.
  • Last but not the least: Serve files publicly at blazing speeds through Akamai’s CDN technology.

Now said that First thing first you need to join Rackspace Files. Here is the link to join RS Cloud files

Its good to know that Cloud Files is tied directly into Akamai’s EdgePlatform so all the uploaded content can be distributed to one of the world’s largest CDN platforms comprised of 84,000+ secure servers deployed in over 72 countries within nearly 1,000 networks.

Now the best part

Pricing

  • Storage starts at $0.15 per gigabyte.
  • Outgoing bandwidth starts at $0.18 per gigabyte
  • Pay only for what you use.

So that now it seems like an interesting bet and you have made up your mind Lets 

. The reason I am so supportive of Rackspace CF is because of the easy to use API and blazing fast speed when it comes to downloading your content such as images. And I like this line on their website

No contracts. No setup fees. Cancel at any time

Now if you have all setup by now its time to roll. Download Cloudfiles API from here.

How do you install the downloaded API:

  1. Extract the downloaded archive and make sure the source code files are in your PHP “include path”.
  2. To use the API in your source code, just make sure to include/require the “cloudfiles.php” script.

Pre-requisite for the above API to work are listed below

  1. This API requires PHP version 5.0+
  2. PHP’s cURL module
  3. PHP enabled with mbstring (multi-byte string) support. If you don’t have this installed on Linux machine then run this command as super user
    #>yum install php-mbstring
    You can find out if this module is install or not by looking at the list that is produced by this command
    #>php -m
    Or just check in phpinfo()
  4. PEAR FileInfo module (for Content-Type detection). This extension is enabled by default as of PHP 5.3.0.

Now I assume that all the above prerequisites are met with and that you are ready to rule :) . First thing I would like to tell is that there is no way that the file that you are trying to upload can be pushed directly to Rackspace cloud. It has to come to your server first but you need not to save it on your server.

I now assume that you have joind RS cloud files and you have your RS Cloud Files API key with you.

There are several uploaders available free of cost. Flash based, HTML5 based and so on. but lets keep things simple and do this with a simple HTML file upload form.

Below is the code for HTML form. Name this file as uploader.php and let it sit in your current site document root.

  1. <form action="uploader.php" method="POST" enctype="multipart/form-data">Select a File: <input type="file" name="to_be_uploaded_file" />
  2. <input type="submit" name="submit" value="Send to Rackspace Cloud Files!" />
  3. </form>

I am not gonna do any validation for “onFormSubmit” (pseudo) so I assume that all the validations such as file size requirement and file extensions will be handled by you.

Now in your uploader.php file add these lines to the top of the file

  1. // include the Rackspace Cloud files PHP API
  2. require('cloudfiles.php');
  3.  
  4. if(count($_POST) > 0) {
  5. $rackspace_user = "rschahaljaspreet"; // replace this with your rackspace user name
  6. $rackspace_api_key = "wow7d180b26bmysecapikeyf80**"; // In case you dont remember this you can get it under my account
  7.  
  8. // Lets connect to Rackspace
  9. $authentication = new CF_Authentication($rackspace_user, $rackspace_api_key);
  10. $authentication->authenticate();
  11. $connection = null;
  12. try {
  13. $connection = new CF_Connection($authentication);
  14. }
  15. catch(AuthenticationException $e) {
  16. echo "Unable to authenticate ".$e->getMessage();
  17. die(0);
  18. }
  19.  
  20. $container = null;
  21. // create a new container if you like uncomment the line below
  22. // $container = new CF_Container($authentication,$connection,"testcontainer");
  23. // Or use an already exsting container
  24. // $container = $connection->get_container('testcontainer');
  25. // or better way to handle this according to me is
  26. try
  27. {
  28. $container = $connection->get_container('images');
  29. $container->make_public();
  30. }
  31. catch(NoSuchContainerException $e) {
  32. $container = new CF_Container($authentication,$connection,"images");
  33. }
  34. catch(InvalidResponseException $res) {
  35. // let your users know or try again or just store the file locally and try again later to push it to the Cloud
  36. }
  37.  
  38. // store file information
  39. $file_to_be_uploaded = $_FILES['to_be_uploaded_file']['tmp_name'];
  40. $filename = $_FILES['to_be_uploaded_file']['name'];
  41.  
  42. // upload this file to Rackspace CF servers
  43. $object = $container->create_object($filename);
  44. $object->load_from_filename($file_to_be_uploaded);
  45. echo $object->public_uri();
  46. // thats it you are done.
  47. }

You can store the path returned by public_uri() function in your database.

I just ran a quick test on the code above and was able to upload a file without any hiccups

here is the URL of my uploaded file

http://c284900.r0.cf1.rackcdn.com/iRecommend.jpg

Now if you notice that the URL c284900.r0.cf1.rackcdn.com is something that is provided by Rackspace. What if you want your own website URL for instead of one supplied by RS.

Simply create a CNAME record such as images.jaspreetchahal.org and point it to your RS CDN container URL.

So I did the same and below is my custom URL for the above

http://images.jaspreetchahal.org/iRecommend.jpg

I hope this helps. If it does I wouldn’t mind you leaving a comment for me :)

Please add your experiences using the comments section below.

Download full source from here

Download Source

Next up is to use the same technique but using plupload. That will be one of my next articles.

 

 

Cheers

 

 

 

VN:F [1.9.22_1171]
Rating: 5.0/5 (2 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 1 vote)
how to: upload files to Rackspace Cloud Files using PHP API and get the public URL for the uploaded file., 5.0 out of 5 based on 2 ratings

Comments

  1. Hi Jaspreet,

    It looks like the PHP library you reference in this awesome tutorial has been deprecated. Any chance you can post another one using this: http://php-opencloud.com/ ?

    Thanks!

  2. Yes, Good example. Enough to start.
    I want to contribute the following:

    When you have (pseudo) subdirectories/subfolders in your cointaines trying getting subdirs with “get_container()” will fail due “Container name cannot contain a ‘/’ character.” I mean this will fail dramatically:

    $container = $connection->get_container(urlencode(‘container/subdir’));

    ===

    So the way to upload to subdirectories is at the “create_object” stage, like this:

    $object = $container->create_object(‘subdir/’ . $filename);
    $object->load_from_filename($file_to_be_uploaded);
    NomikOS recently posted..CheckGmail Error: 200 OK – Solución definitiva.My Profile

  3. thanks for this example, better that rackspace documentation examples

  4. KennethRules says:

    Thanks for this… this really help me out..

  5. Nick Weavers says:

    A heads up for those of us using the UK CloudFiles servers, you need to go to line 137 in cloudfiles.php and change $auth_host=US_AUTHURL to $auth_host=UK_AUTHURL or you’ll get a 401 resulting in a failure to authenticate.

  6. Hey Jaspreet, thanks for the reply! That would be awesome if you could share a bit of your code with us, I’m still having issues trying to use plupload to upload multiple files my CF account.

    -Brian

  7. Hey Jaspreet, great post. I was wondering if you ever got around to working on a plupload + rackspace cloud file implementation guide?

    Thanks!
    -Brian

    • Hi Brian, Thanks for you feedback. Much appreciated. With regard to plupload, you still have to receive the file onto the server before uploading to RackSpace files. If you are interested then I can do a write up. I’ve written code that I use for one of my projects, with some modification I should be able to share that. Let me know if you want me to share that.
      Cheers!

  8. Praneet Loke says:

    Bookmarked! Thank you for being detailed.. :)

  9. best tutorial for using the cloud files php api out there, thanks! this contained 2 things i was looking for, make_public and the uri of the uploaded file.

Speak Your Mind

*

CommentLuv badge