How can PHP be used to upload files to a directory with a size limit of 300 kB?
To upload files to a directory with a size limit of 300 kB in PHP, you can use the `$_FILES` superglobal to access the uploaded file information, check the file size using the `size` attribute, and validate it against the maximum allowed size. If the file size exceeds the limit, you can display an error message to the user. If the file size is within the limit, you can move the file to the desired directory using the `move_uploaded_file` function.
<?php
$maxFileSize = 300 * 1024; // 300 KB in bytes
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if ($_FILES['file']['size'] > $maxFileSize) {
echo "Error: File size exceeds the limit of 300 KB.";
} else {
$uploadDir = 'uploads/';
$uploadFile = $uploadDir . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile)) {
echo "File uploaded successfully.";
} else {
echo "Error uploading file.";
}
}
}
?>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="Upload">
</form>
Keywords
Related Questions
- How can the use of plugins in CMS platforms like WordPress affect the functionality and customization of a website?
- What are some recommended Mailer-Classes that can be used as alternatives to the mail() function in PHP?
- How can the problem of "__PHP_Incomplete_Class Object" in sessions be resolved?