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.
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
Basic knowledge of HTML and PHP is required to follow this tutorial.
<!-- 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.
<?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.
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.
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.
Here are the solutions and explanations for the above exercises:
pathinfo()
function in PHP to get the file extension and check if it is 'jpg', 'jpeg', 'png', or 'gif'.$_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!