How to Upload Image in PHP and Store in Folder
In this tutorial we are going to see how to upload and store files in a folder using PHP, also we will see how to check file size, file extension and if the file already exists in the folder.
Create the form
Let's first create the form for uploading the file, the form contains only one field that allows users to choose the file to upload.
<!DOCTYPE html>
<html>
<body>
<form method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="file" id="file">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
PHP script for uploading and storing the file
Next, we add the PHP code to store the file in the folder.
<?php
// Check for form submission
if(isset($_POST["submit"])) {
$directory = "uploads/";
$file = $directory . basename($_FILES["file"]["name"]);
$uploaded = true;
$file_ext = strtolower(pathinfo($file,PATHINFO_EXTENSION));
// Check if file already exists
if (file_exists($file)) {
echo "Sorry, file already exists.";
$uploaded = false;
}
// Check file size
if ($_FILES["file"]["size"] > 1000000) {
echo "Sorry, your file is too large.";
$uploaded = false;
}
// Check file extension
if($file_ext != "jpg" && $file_ext != "png" && $file_ext != "jpeg"
&& $file_ext != "gif" ) {
echo "Only JPG, JPEG, PNG & GIF files are allowed.";
$uploaded = false;
}
// Check if file is uploaded
if (!$uploaded) {
echo "File was not uploaded.";
} else {
if (move_uploaded_file($_FILES["file"]["tmp_name"], $file)) {
echo "File ". htmlspecialchars( basename( $_FILES["file"]["name"])). " uploaded successfully.";
} else {
echo "Error while uploading your file.";
}
}
}
?>