How to upload images with HTML and PHP forms

Often, when we develop web applications, the possibility of uploading files or images to the server is necessary, whether we are webmasters, authorized users or part of the general public of the web.

The exact way to solve the problem will depend on the place where we need to authorize this use of the web, in which we will always have to take into account the possible security holes that we can create It will not be the same to schedule a photo upload

In this tutorial I will try how to upload images with forms and also how to upload images in PHP, with a basic filtering of file types (their extensions), and the saving of these files on the server. I will also comment some simple tricks to increase security of our development.

In this article you will find the following concepts explained in detail:

  1. Bases to understand how to upload files with html and php.
  2. Steps to upload images with html.
  3. Example HTML form to upload any type of file.
  4. explanation of special input label to upload files.
  5. Security checks on uploaded files.
  6. As move an uploaded file to the desired folder.
  7. How to display uploaded images to the server with the form.

Content

  • Bases for uploading files on a website
  • Steps to upload images with html
    • The html form for uploading files
    • HTML tag to attach file
  • Treatment of files uploaded with php
    • Filtering with php of file types uploaded with html
    • Writing images to server folder
    • Security of writing images in server folder
  • Extra: Show images uploaded with html
  • Extra: Download files uploaded with html

Bases for uploading files on a website

To enable the uploading of files on our website, we must know the HTML markup language and the PHP web programming language. For the HTML part we are going to need an HTML form, and in php we will need to know the use of functions and basic knowledge of file paths.

  • Our HTML code (the form) will be in charge of displaying the corresponding options in the user’s browser so that they can see a file explorer on their computer (pc or mobile) and the option to attach their selection.
  • In the server-side programming, using php, we will check what type of file we have uploaded, its size, and if we believe it is correct, we will save it in a folder to prevent it from being lost as a temporary file.

Steps to upload images with html

To allow users to upload images or files via HTML we are going to use:

  • An appropriately configured HTML form.
  • A specific HTML INPUT to attach html files.
  • A button submit that allows us to confirm the submission of the form.

The html form for uploading files

The forms, properly configured, will allow one or more files/images to be attached and, encrypted, send them to the server via protocol http. The result will be a php image upload form.

There are two attributes of the form that will give access to the possibility of uploading files:

  1. the attribute method that indicates the method of sending the data to the server (GET or POST).
  2. The attribute enctype. The type of encryption of the information. By default x-www-urlencoded.

The label of our form would look like this:

<form name="subida-imagenes" type="POST" enctype="multipart/formdata" >

As you can see, apart from the name that is basic for the form to work, I have indicated in the form type (type) the sending of data through POST, and the encryption of the information (enctype), required for a file to be attached, such as multipart/formdata.

The configuration multipart/formdata indicates that the form information will be sent in packets over the network.

HTML tag to attach file

Now that our form tag is ready, let’s introduce the special form tag for files, a input very similar to the others:

<form name="subida-imagenes" type="POST" enctype="multipart/formdata" >
	<input type="file" name="imagen" />
</form>

This label input It will configure itself to upload files just by indicating files in the attribute type. Browsers will immediately identify this attribute and graphically display a button to select system files.

Finally we will add a button of type submit to be able to confirm the submission of the form to the server.

<form name="subida-imagenes" type="POST" enctype="multipart/formdata" >
	<input type="file" name="imagen1" />
	<input type="submit" name="subir-imagen" value="Enviar imagen" />
</form>

Treatment of files uploaded with php

Once the users of our form confirm the sending, on the server, in our usual schedule for processing the data sent, we will have access to the file or files that they have attached. But just as, as a general rule, we have access to the data received through the superglobal variable $_POST or $_GET depending on the method of the form, access to files will also be through the superglobal $_FILES array.

Let’s see what information we have in the $_FILES array for an image called ‘greeting.jpg’ uploaded through our form:

<?php
echo $_FILES['imagen1']['name'];
echo $_FILES['imagen1']['tmp_name'];
echo $_FILES['imagen1']['type'];
echo $_FILES['imagen1']['size'];
echo $_FILES['imagen1']['error'];
?>

through these echo’s I have accessed all the available information of the file in PHP. The printed information would be the following:

greeting
213mnuashduahs0923
image/jpg
120304
0

Respectively, these values ​​from first to last represent the following information:

  1. Name of the uploaded file.
  2. Temporary name assigned to the file by the server. This name is unique and allows it to be identified within the temporary folder.
  3. Guy MIME uploaded file: jpg, png, gif, pdf, etc.
  4. size in bytes of the file, if we wanted to calculate the size to kilobytes we should divide by 1024 and to go to megabytes divide it again by 1024.
  5. Upload error code, in our case 0 or UPLOAD_ERR_OK which indicates that no error has occurred. File upload error codes.

Filtering with php of file types uploaded with html

Once we know how to access the information of the uploaded files, I am going to focus on filtering the types of files accepted. Limiting the uploaded file type is highly recommended to avoid potential security issues.

For this example I am going to check that the uploaded image is indeed an image with one of the most common extensions and that its size is less than 1 MB:

<?php
$extensiones = array(0=>'image/jpg',1=>'image/jpeg',2=>'image/png');
$max_tamanyo = 1024 * 1024 * 8;
if ( in_array($_FILES['imagen1']['type'], $extensiones) ) {
     echo 'Es una imagen';
     if ( $_FILES['imagen1']['size']< $max_tamanyo ) {
          echo 'Pesa menos de 1 MB';
     }
}
?>

Writing images to server folder

Once we have our filtered files we will proceed to save them permanently in a folder on our server.

The images or files uploaded through the HTML forms are always stored in a temporary folder of the system, therefore we must move them to be able to save them permanently.

To move the files from the temporary folder directly to our chosen folder we will use the move_uploaded_file(source, destination) function.

The following example would be a script hosted in the root folder of our website, it could be our index.php:

<?php
$ruta_indexphp = dirname(realpath(__FILE__));
$ruta_fichero_origen = $_FILES['imagen1']['tmp_name'];
$ruta_nuevo_destino = $ruta_indexphp . '/imagenes/' . $_FILES['imagen1']['name'];
if ( in_array($_FILES['imagen1']['type'], $extensiones) ) {
     echo 'Es una imagen';
     if ( $_FILES['imagen1']['size']< $max_tamanyo ) {
          echo 'Pesa menos de 1 MB';
          if( move_uploaded_file ( $ruta_fichero_origen, $ruta_nuevo_destino ) ) {
               echo 'Fichero guardado con éxito';
          }
     }
}
?>

For greater clarity I have assigned the routes involved in the process to two variables:

  • The temporary name of the uploaded file, which is located in the temporary folder, in $source_file_path.
  • The full destination path of the file, which is made up of a part of the root path of the script where I am working (I am programming in index.php) plus the name of the folder that I have created to save the images (/images) and finally the final name that the file will have (the original name of the file).

Security of writing images in server folder

When saving the files uploaded by users on our server, it may happen that we do not filter the files entered, or we save files likely to cause security problems. To avoid problems of this type, it is best to include in the folder where we store them a small htaccess-script which prevents code execution:

RemoveHandler .phtml .php3 .php .pl .py .jsp .asp .htm .shtml .sh .cgi .dat
RemoveType .phtml .php3 .php .pl .py .jsp .asp .htm .shtml .sh .cgi .dat

With these two lines in a file with extension .htaccess we will prevent possible code execution by malicious users. Remember that you must include this file in the same folder where you store the files.

And that’s it, with this you would have finished a php image upload form fully functional, with security checks to prevent unexpected file uploads that can cause problems or unexpected hacks.

Extra: Show images uploaded with html

Showing the images saved in our storage folder is simple, we just have to include the path to the file in an IMG html tag:

<img src="imagenes/nombre_imagen.jpg" />

Extra: Download files uploaded with html

If what we want is to include a download link for the stored file instead of using a label img we will use a tag for links TOand we will include in the attribute HREF the path to the file:

<a href="imagenes/nombre_imagen.jpg"> Descarga de la imagen </a>

This link will cause the user to download the file in question, however if the file is, for example, an image or pdf, the user instead of achieving a direct download will view the content, having to download it using the download option from the drop-down menu with right click.

Avoiding viewing files is possible thanks to HTML5 and the most modern browsers: chrome, firefox, opera. We must include the DOWNLOAD attribute in the previous link tag (TO), thus, the final link for a forced download would look like this:

<a href="imagenes/nombre_imagen.jpg" download="nombre_imagen"> Descarga de la imagen </a>

Leave a Reply