What are the best practices for securely storing and retrieving user-uploaded files in PHP applications?

When storing and retrieving user-uploaded files in PHP applications, it is important to follow best practices to ensure security. This includes validating file types, sanitizing file names, storing files outside of the web root directory, and using proper file permissions to restrict access.

// Example of securely storing a user-uploaded file
$uploadDir = '/path/to/upload/directory/';
$allowedTypes = ['image/jpeg', 'image/png'];
$maxFileSize = 1048576; // 1MB

if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $fileType = $_FILES['file']['type'];
    $fileName = basename($_FILES['file']['name']);
    $fileSize = $_FILES['file']['size'];

    if (in_array($fileType, $allowedTypes) && $fileSize <= $maxFileSize) {
        $uploadPath = $uploadDir . $fileName;
        move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath);
        echo 'File uploaded successfully.';
    } else {
        echo 'Invalid file type or size.';
    }
} else {
    echo 'Error uploading file.';
}