What are some best practices for handling file paths and permissions when working with user-uploaded content in PHP?

When working with user-uploaded content in PHP, it is important to handle file paths and permissions carefully to prevent security vulnerabilities. One best practice is to store user-uploaded files in a separate directory outside of the web root to prevent direct access. Additionally, always sanitize file names to prevent directory traversal attacks. Finally, make sure to set appropriate file permissions to restrict access to uploaded files.

// Define the directory to store user-uploaded files
$uploadDir = '/path/to/upload/directory/';

// Sanitize the file name to prevent directory traversal attacks
$fileName = basename($_FILES['file']['name']);

// Move the uploaded file to the designated directory
if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadDir . $fileName)) {
    echo 'File uploaded successfully.';
} else {
    echo 'Error uploading file.';
}

// Set appropriate file permissions for the uploaded file
chmod($uploadDir . $fileName, 0644);