Guides

Storage OnLine: Using S3 API with PHP to save, edit and delete data from storage

In the following, how to save, edit and delete objects in buckets, using the S3.php library.

At the end of this example, a real file browser will be created to manage your objects in the Storage OnLine

Uploading files

The file upload operation will be carried out in two stages:

  • upload of the file from the user's computer to its web server;
  • Trasnfer of the file to the Storage OnLine.

Server uploading via HTTP POST is a very common functionality, implemented in many PHP applications, especially through third-party libraries that simplify its management; to be as generic and compatible as possible, the code will only use the standard functions of a common PHP configuration. For this to be possible, however; certain PHP directives (usually in the php.ini file) must be configured correctly:

  • file_uploads: must be set to On;
  • upload_max_filesize: indicates the maximum size of files that can be uploaded via HTTP;
  • post_max_size: indicates the maximum size of the HTTP POST request and must necessarily be greater thanupload_max_filesize because other parameters are often sent in addition to the file itself.

Then, create an uploadFile.php file in the same folder as the other PHP pages and insert this code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
try {
  // configurazione
  require_once 'conf/configuration.php';
  // azioni
  $bucketName = $_REQUEST['bucketName'];
  $prefix = isset($_REQUEST['prefix']) ? $_REQUEST['prefix'] : '';
  $parent = isset($_REQUEST['parent']) ? $_REQUEST['parent'] : '';
  
  if ('POST' == $_SERVER['REQUEST_METHOD']) {
    
    // gestisci upload
    if ($_FILES['file']['error'] > 0) {
      throw new Exception('Errore durante l\'upload del file', $_FILES['file']['error']);
    }
    
    if (is_uploaded_file($_FILES['file']['tmp_name'])) {
      $input = S3::inputFile($_FILES['file']['tmp_name']);
      $uri = $prefix . $_FILES['file']['name'];
      if (S3::putObject($input, $bucketName, $uri)) {
        $message = 'Il file è stato caricato correttamente nel bucket';
      }
      else {
        $message = 'Problemi nella creazione dell\'oggetto nel bucket';
      }
    }
  }
}
catch(Exception $ex) {
  $errorMessage = "Si è verificato un errore (". $ex->getCode()."):\n".$ex->getMessage();
  $errorMessage = nl2br(htmlspecialchars($errorMessage, ENT_NOQUOTES, 'UTF-8'));
}
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title>S3 API test</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>

<?php
if (isset($errorMessage)) {
?>
  <div class="errorMessage">
    <?php echo $errorMessage; ?>
  </div>
<?php
}
else {
?>

<h3>Carica un file</h3>

<?php
  if (isset($message)) {
  ?>
    <div class="message">
      <?php echo $message; ?>
    </div>
  <?php
  }

  $backUrl = 'listObjectsAdvanced.php?bucketName=' . urlencode($bucketName) .
        '&prefix=' . urlencode($prefix) . '&parent=' . urlencode($parent);
  echo '<p><a href="' . $backUrl . '">Indietro</a></p>';
?>

<p>Bucket: <em><?php echo htmlspecialchars($bucketName, ENT_NOQUOTES, 'UTF-8');?></em></p>
<p>Directory: <em><?php echo htmlspecialchars('/'.$prefix,ENT_NOQUOTES,'UTF-8');?></em></p>

<form action="uploadFile.php" method="post" enctype="multipart/form-data">
  <input type="hidden" name="bucketName"
	value="<?php echo htmlspecialchars($bucketName, ENT_NOQUOTES, 'UTF-8');?>" />
  <input type="hidden" name="prefix"
	value="<?php echo htmlspecialchars($prefix, ENT_NOQUOTES, 'UTF-8');?>" />
  <input type="hidden" name="parent"
	value="<?php echo htmlspecialchars($parent, ENT_NOQUOTES, 'UTF-8');?>" />
  <label for="file">Scegli un file da caricare:</label>
  <input type="file" name="file" id="file" />
  <button type="submit">Invia</button>
</form>

<?php
}
?>
</body>
      

Looking at the code:

  • includes the configuration and libraries;
  • retrieves the PHP request parameters, note the use of $_REQUEST to handle both GET and POST requests;
  • in the case of POST, it is assumed that a file exists in the temporary directory;
  • the S3::inputFile() method is used to transform a file name into an array that can be used by the S3.php class;
  • the S3::putObject() method takes care of the actual transfer of bytes into the Storage;
  • error handling via the Exception and try/catch.
listObjectsAdvanced.php page (the browser file that we'll build in this guide).

A note on security: use the htmlspecialchars() and urlencode(), unctions correctly, as buckets and objects may have names containing special HTML characters such as <, >, &, or otherwise not compatible with a URL. So here is how and when to use them:

  • htmlspecialchars() : this is used to insert a string into the HTML code. This function replaces the characters <, >, & (and many others) with the corresponding entity characters: < > and &
  • urlencode(): this is used for the same reason as above, but when adding parameters to a URL. This function translates non-standard characters, allowing them to be correctly passed as parameters.

Finally, note some very important features of the HTML code for the upload form:

  • action="uploadFile.php" redirects to the page itself, which means that the page reloads itself after the submit;
  • method="post" specifies that the request will be of type HTTP POST;
  • enctype="multipart/form-data" indicates that, along with the parameters, a file is also being sent;
  • the various <input type="hidden"> report the parameters received from the page: bucketName, prefix, parent. In this way, once the upload has taken place, you can easily return to the file browser to check that the file has actually been uploaded.

Resources