How can access rights and user authentication be implemented in a PHP script to allow users to upload files to specific directories on a server?

To implement access rights and user authentication in a PHP script for file uploads, you can use session management to authenticate users and check their permissions before allowing them to upload files to specific directories on the server. This can be achieved by storing user credentials in a session variable and verifying them before processing the file upload request.

<?php
session_start();

// Check if user is authenticated
if(!isset($_SESSION['user_id'])) {
    // Redirect to login page or display an error message
    header("Location: login.php");
    exit();
}

// Check user permissions to upload files
if($_SESSION['role'] !== 'admin') {
    // Redirect to unauthorized page or display an error message
    header("Location: unauthorized.php");
    exit();
}

// Process file upload
$targetDir = "uploads/";
$targetFile = $targetDir . basename($_FILES["file"]["name"]);

if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetFile)) {
    echo "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>