What alternative methods can be used to check file size before uploading in PHP, aside from using $_FILES['file']['size']?
When uploading files in PHP, it's important to check the file size to prevent large files from being uploaded. Aside from using $_FILES['file']['size'], another method to check file size is to use the filesize() function in combination with the $_FILES['file']['tmp_name'] variable. This allows you to get the size of the file before it's uploaded to the server.
// Get the file size using filesize() function
$file_size = filesize($_FILES['file']['tmp_name']);
// Check if the file size is within the limit (e.g. 5MB)
$max_size = 5 * 1024 * 1024; // 5MB in bytes
if ($file_size > $max_size) {
echo "File size exceeds the limit.";
// Handle the error or prevent the file from being uploaded
} else {
// Proceed with the file upload
}
Keywords
Related Questions
- How can PHP.ini settings be adjusted to increase the maximum upload size allowed by net2ftp?
- How can PHP and JavaScript be combined effectively to improve the functionality of dropdown lists on a webpage?
- What are some efficient ways to optimize the performance of a PHP forum that retrieves and displays posts from a MySQL database?