How to Upload Files with PHP
In this tutorial, we will see how to upload files with PHP, so let's assume that we want to upload an image of a product and store it in a folder inside our project, let's see how can do that.
Create the form
First, we create the form to upload the files.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHP Upload File</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ" crossorigin="anonymous">
</head>
<body class="bg-light">
<div class="container">
<div class="row my-5">
<div class="col-md-8 mx-auto">
<div class="card">
<div class="card-body">
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" class="form-control mb-2">
<button class="btn btn-primary" type="submit">
Upload
</button>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe" crossorigin="anonymous"></script>
</body>
</html>
Create the upload.php file
Next, we create a new folder 'uploads' inside our project where we will save the uploaded files.
<?php
// Here the uploaded file will be stored
$uploadDirectory = "uploads/";
// Get the path to the uploaded file
$fileToUpload = $uploadDirectory . basename($_FILES["file"]["name"]);
// Move the file to the directory
if (move_uploaded_file($_FILES["file"]["tmp_name"], $fileToUpload)) {
echo "Your file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
?>