DigitalOcean Spaces – Learn how to use Spaces with PHP

DigitalOcean Spaces – Learn how to use Spaces with PHP

Using DigitalOcean Spaces with your next PHP project is a beautiful idea. Spaces will give you all the hard drive space that you could ever need. This post can help you build your next PHP project with DigitalOcean Spaces. Building out an infrastructure can be a difficult job for anyone, but DigitalOcean’s services make it a bit easier.

Mounting Object Storage

You could upload directly to S3 compatible storage using a PHP package, but it is easier to mount a bucket and let the file system handle the rest. Read my post on Mounting Object Storage if you need help getting started.

By mounting your bucket to your local file system, it will allow you to have nearly unlimited storage space for your app. In addition to storing uploaded files to object storage, you could also save backups, log files, and anything else you could imagine.

PHP Uploading to DigitalOcean Spaces

Your code will probably be a lot more complicated than the example below. However, I think the code below will suffice for this blog post.


<?php
$message = '';
if(!empty($_FILES['uploaded_file'])) {
  $path = 'uploads/';
  $path = $path . uniqid('u', true) . '-' . basename($_FILES['uploaded_file']['name']);

  if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
    $message = 'The file ' . basename( $_FILES['uploaded_file']['name']) . ' has been uploaded';
  } else {
    $message = 'There was an error uploading the file, please try again!';
    $message .= $_FILES['uploaded_file']['error'];
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Upload your files</title>
</head>
<body>
  <?php echo $message; ?>
  <form enctype="multipart/form-data" action="upload.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="submit" value="Upload"></input>
  </form>
</body>
</html>

The code in the example above shows you how to upload a file to a folder. You will need to change the path to where you mounted your bucket. Of course, you will need to make sure you validate the file type and restrict it to users who are logged in.

Conclusion

Digitalocean Spaces is the best object storage service currently available. While they might not have as much space available as AWS, it is compatible with S3, easy to use, and has a better UI.

Please don’t store any sensitive or confidential information in your buckets. If you must, then please make sure you have the proper settings and those files aren’t publicly exposed.


Image Credit DigitalOcean.

Comments are closed.