What are some best practices for handling access control and authentication in PHP applications?

Access control and authentication are crucial aspects of PHP applications to ensure that only authorized users can access certain resources or perform specific actions. Best practices include using secure authentication methods like password hashing, implementing role-based access control to restrict permissions based on user roles, and validating user input to prevent common security vulnerabilities like SQL injection and cross-site scripting.

// Example of implementing secure authentication with password hashing
$password = $_POST['password'];
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

// Example of implementing role-based access control
$user_role = $_SESSION['user_role'];
if ($user_role === 'admin') {
    // Allow access to admin-only resources
} else {
    // Redirect or show an error message for unauthorized users
}

// Example of validating user input to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = mysqli_query($conn, $query);