What are the best practices for handling file permissions and paths in PHP scripts for file uploads?

When handling file uploads in PHP scripts, it is important to properly set file permissions and validate file paths to ensure security and prevent vulnerabilities. Best practices include setting appropriate permissions on upload directories, sanitizing file paths to prevent directory traversal attacks, and using unique file names to prevent overwriting existing files.

// Set upload directory and permissions
$upload_dir = 'uploads/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Validate file path and sanitize
$filename = basename($_FILES['file']['name']);
$target_path = $upload_dir . $filename;

// Check if file already exists
if (file_exists($target_path)) {
    $target_path = $upload_dir . uniqid() . '_' . $filename;
}

// Move uploaded file to target path
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);