HTML / HTML Forms with Advanced Controls

Creating File Upload Forms

This tutorial will guide you through the process of creating a form that allows users to upload files. You will learn how to use the file input type and how to handle file uploads.

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores form elements with advanced features like file upload, range sliders, and date pickers.

1. Introduction

Goal of the Tutorial

This tutorial aims to guide you through the process of creating a form that allows users to upload files to a server. The form will be created using HTML and the file uploads will be handled using PHP.

Learning Outcomes

By the end of this tutorial, you will learn how to:
- Create a form with a file input field in HTML
- Handle file uploads in PHP

Prerequisites

Basic knowledge of HTML and PHP is required to follow this tutorial.

2. Step-by-Step Guide

Concepts

  • HTML File Upload Form: This is a form that allows users to choose a file from their system to be uploaded to a server. The form uses the POST method and the enctype attribute is set to 'multipart/form-data'.
  • PHP File Handling: PHP is used to handle the uploaded file on the server. It can validate the file and move it to a designated location on the server.

Examples

  1. HTML File Upload Form:
<!-- HTML File Upload Form -->
<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>

In the above example, when the user selects a file and clicks the 'Upload File' button, the form data is sent to 'upload.php' for processing.

  1. PHP File Handling:
<?php
$target_dir = "uploads/"; // directory to save the uploaded file
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); // path of the file to be uploaded

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
  echo "Sorry, there was an error uploading your file.";
}
?>

In the above PHP code, $_FILES is a superglobal array in PHP which is used to handle uploaded files. $_FILES["fileToUpload"]["tmp_name"] contains the temporary location of the file on the server.

3. Code Examples

Let's combine the HTML form and PHP file handling into a complete working example.

<!-- HTML File Upload Form -->
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
  Select file to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <input type="submit" value="Upload File" name="submit">
</form>

</body>
</html>
<!-- upload.php -->
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

// Check if file already exists
if (file_exists($target_file)) {
  echo "Sorry, file already exists.";
  exit;
}

// Try to upload file
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
  echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
  echo "Sorry, there was an error uploading your file.";
}
?>

The above code checks if a file with the same name already exists in the 'uploads' directory. If the file does not exist, it tries to upload the file.

4. Summary

In this tutorial, you learned how to create a form that allows users to upload files and how to handle those file uploads in PHP.

5. Practice Exercises

  1. Exercise 1: Create a form that allows users to upload multiple files at once.
  2. Exercise 2: Validate the uploaded file to only accept images (jpg, jpeg, png, and gif).
  3. Exercise 3: Display an error message if the uploaded file exceeds a certain size.

Here are the solutions and explanations for the above exercises:

  • Solution 1: To allow multiple file uploads, add the 'multiple' attribute to the file input field and change the name attribute to an array (e.g., 'fileToUpload[]').
  • Solution 2: To only accept images, check the file extension of the uploaded file. Use the pathinfo() function in PHP to get the file extension and check if it is 'jpg', 'jpeg', 'png', or 'gif'.
  • Solution 3: To check the file size, use $_FILES["fileToUpload"]["size"] which gives the size of the uploaded file in bytes. If the size exceeds the limit, display an error message.

Keep practicing to get more comfortable with file uploads in HTML and PHP. Good luck!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

File Size Checker

Check the size of uploaded files.

Use tool

Age Calculator

Calculate age from date of birth.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help