File Uploads

While it is possible to upload files into directories reserved for that purpose on a server this is generally not a good idea and leads to various problems, not the least security. A better solution stores such content in the database. The following example shows the steps for a solution the allows for uploading image files in various formats (such as jpg and png).

  1. First we need a table to store the data. In this case the data is encoded as base64 strings which can be stored as varchar.
    create table uploads (img varchar);
    
  2. The file upload1.php shows a very simple upload form:
    <form action="upload2.php" method="post" enctype="multipart/form-data">
      Select file to upload:
      <input type="file" name="file">
      <input type="submit" value="Upload">
    </form>
    
  3. In the next step (upload2.php) we encode the image data and write it into the DB:
    <?php
    include 'header.php';
    
    $file = $_FILES['file'];
    $filename = $file['name'];
    $base64 = base64_encode(file_get_contents($file['tmp_name']));
    $image = "data:image/jpeg;base64,".$base64;
    $query = pg_query("INSERT INTO uploads (img) VALUES ('$image')")
    ?>
    
  4. Now we can display the images:
    <?php 
    include 'header.php'; ?>
    
    $query = 'select img from uploads';
    $result = pg_query($query) or die('Query failed: ' . pg_last_error());
    while ($x = pg_fetch_object($result)) {
      echo '<img src="' . $x->img . '" />';
    }
    ?>
    
  5. The file header.php contains the code for establishing the DB connection (Postgres):
    <?php 
    $dbconn = 
      pg_connect("host=myhost.some.where
      dbname=mydb
      user=myuser 
      password=mypw")
      or die('Could not connect: ' . pg_last_error());
    ?>
    

Note that this solution does not involve any temporary directories where file contents is written. This is the preferred method.