How can PHP be used to validate and sanitize user input when uploading files to a server?
When uploading files to a server, it is important to validate and sanitize user input to prevent security vulnerabilities such as file injection attacks. PHP provides functions to check file types, file sizes, and sanitize file names to ensure safe file uploads.
// Validate and sanitize user input when uploading files to a server
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
$file_name = basename($_FILES['file']['name']);
$file_type = $_FILES['file']['type'];
$file_size = $_FILES['file']['size'];
// Validate file type
$allowed_types = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($file_type, $allowed_types)) {
die('Invalid file type. Allowed types: jpeg, png, gif');
}
// Validate file size
if ($file_size > 5242880) { // 5MB
die('File size is too large. Maximum size allowed is 5MB');
}
// Sanitize file name
$file_name = preg_replace("/[^A-Za-z0-9\-_.]/", '_', $file_name);
// Move uploaded file to destination folder
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $file_name);
} else {
die('Error uploading file. Please try again.');
}
Keywords
Related Questions
- What is the significance of using $_GET in PHP for passing variables in URLs?
- What are the common pitfalls when using a PHP Templating Engine for displaying dynamic content like error messages?
- Are there any recommended resources or tutorials available for learning how to create a simple text editing feature in PHP for a CMS?