Bootstrap FreeKB - PHP - Upload image files to a volume on Docker
PHP - Upload image files to a volume on Docker

Updated:   |  PHP articles

Let's say you have created a PHP container on Docker, and the /usr/local/docker/images directory is mounted to /var/www/images as a volume in your PHP container. 

 

This article will explain how you can use HTML and PHP to upload files (such as images) to the PHP container and then over to /usr/local/docker/images on the Docker host, which ultimately will make the file (image) available at /var/www/images in the PHP container.

The following command can be used to ensure you have file_uploads = On in your PHP Docker container.

~]$ sudo docker exec php-fpm php -i | grep file_uploads
file_uploads => On => On

 


HTML

Use the following HTML to create a form that will post the file to file_upload.php.

<form action="file_upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="upload">
    <input type="submit">
</form>

 

In this example, an image of Goofy is selected.

 


PHP

Let's say file_upload.php contains the following. Since the name key in the HTML is upload and $_FILES variable in your PHP must also be upload.

<?php
  $file        = $_FILES["upload"]["name"];
  $temp_file   = $_FILES["upload"]["tmp_name"];
  $remote_file = "/usr/local/docker/images/$file";
?>

 

The tmp_name key will contain something like /tmp/php8AADgm5fzds in the PHP Docker container, not on the Docker host, where /tmp/php8AADgm5fzds is the file that was uploaded (goofy.png in this example). The goal here is to copy the temp file (/tmp/php8AADgm5fzds) from the PHP container to the Docker host.

The ssh2_connect and ssh2_auth_password or ssh2_auth_pubkey_file and ssh2_scp_send functions can be used to copy the temp file (/tmp/php8AADgm5fzds) from the PHP container to the Docker host. Of course, this assumes that your can make an SSH connection to your Docker system using basic authentication (username, password) or using a public/private key pair (passwordless authentication).

<?php
    $connection = ssh2_connect("your docker server hostname or ip address", 22);

    if (!$connection) {
      echo "<span style='font-size: 14px'>ssh2_connect failed</span>";
      exit();
    }

    $username = "john.doe";
    $password = "itsasecret";
    $authenticate = ssh2_auth_password($connection, $username, $password);

    if (!$authenticate) {
      echo "<span style='font-size: 14px'>ssh2_auth failed</span>";
      exit();
    }

    if (!ssh2_scp_send($connection, $temp_file, $remote_file, 0644)) {
      echo "ssh2_scp_send failed";
      exit();
    }

    ssh2_exec($connection, 'exit');
?>

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter b405ae in the box below so that we can be sure you are a human.