What are best practices for setting permissions on upload directories in PHP?

When setting permissions on upload directories in PHP, it is important to ensure that the directory is only writable by the web server and not accessible by the public. This helps prevent unauthorized users from uploading malicious files or accessing sensitive information. Setting the correct permissions can help enhance the security of your application.

// Set the correct permissions on the upload directory
$uploadDir = '/path/to/upload/directory';
$permissions = 0755; // Set the appropriate permissions

if (!file_exists($uploadDir)) {
    mkdir($uploadDir, $permissions, true);
} else {
    chmod($uploadDir, $permissions);
}