What are some best practices for ensuring data security in PHP portals with user-uploaded files?
Issue: User-uploaded files can pose a security risk if not properly handled in PHP portals. To ensure data security, it is important to validate file types, sanitize file names, store files outside of the web root directory, and implement access controls.
// Validate file type
$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
$uploaded_file_extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if (!in_array($uploaded_file_extension, $allowed_extensions)) {
die('Invalid file type.');
}
// Sanitize file name
$cleaned_file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $_FILES['file']['name']);
// Store file outside of web root directory
$upload_directory = '/path/to/uploaded/files/';
$upload_path = $upload_directory . $cleaned_file_name;
move_uploaded_file($_FILES['file']['tmp_name'], $upload_path);
// Implement access controls
chmod($upload_path, 0644);