How can PHP developers ensure proper file and directory permissions for secure uploads?

To ensure proper file and directory permissions for secure uploads in PHP, developers should set the correct permissions on the upload directory to prevent unauthorized access and execution of malicious scripts. This can be achieved by setting the directory permissions to 755 and file permissions to 644, ensuring that only the owner has write permissions and others have read-only access.

// Set the correct permissions for the upload directory
$uploadDir = 'uploads/';
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

// Set the correct permissions for uploaded files
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $uploadFile = $uploadDir . basename($_FILES['file']['name']);
    move_uploaded_file($_FILES['file']['tmp_name'], $uploadFile);
    chmod($uploadFile, 0644);
}