Simple Tutorials for Smart Learning
<form action="upload.php" method="POST" enctype="multipart/form-data"> <label for="file">Choose a file:</label> <input type="file" name="file" id="file"> <input type="submit" value="Upload File"> </form>
enctype="multipart/form-data"
input
type="file"
if ($_SERVER["REQUEST_METHOD"] === "POST") { $targetDir = "uploads/"; // Directory to store the uploaded file $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION)); // Allowed file types $allowedTypes = array("jpg", "png", "jpeg", "gif", "pdf"); // Validate file type if (in_array($fileType, $allowedTypes)) { // Check for file upload errors if ($_FILES["file"]["error"] === UPLOAD_ERR_OK) { // Move the file to the target directory if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) { echo "File uploaded successfully: $fileName"; } else { echo "Error uploading file."; } } else { echo "Error during file upload."; } } else { echo "Invalid file type. Only JPG, PNG, JPEG, GIF, and PDF files are allowed."; } }
uploads
$maxFileSize = 2 * 1024 * 1024; // 2 MB if ($_FILES["file"]["size"] > $maxFileSize) { echo "File size exceeds the 2MB limit."; }
<?php if ($_SERVER["REQUEST_METHOD"] === "POST") { $targetDir = "uploads/"; $fileName = basename($_FILES["file"]["name"]); $targetFilePath = $targetDir . $fileName; $fileType = strtolower(pathinfo($targetFilePath, PATHINFO_EXTENSION)); $allowedTypes = array("jpg", "png", "jpeg", "gif", "pdf"); $maxFileSize = 2 * 1024 * 1024; // 2 MB if (in_array($fileType, $allowedTypes)) { if ($_FILES["file"]["size"] <= $maxFileSize) { if ($_FILES["file"]["error"] === UPLOAD_ERR_OK) { if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFilePath)) { echo "File uploaded successfully: $fileName"; } else { echo "Error uploading file."; } } else { echo "Error during file upload."; } } else { echo "File size exceeds the 2MB limit."; } } else { echo "Invalid file type. Only JPG, PNG, JPEG, GIF, and PDF files are allowed."; } } ?>
File uploaded successfully: example.jpgInvalid file typeFile size exceeds the limit
example.jpg