What are the best practices for handling user permissions and security in PHP code?

When handling user permissions and security in PHP code, it is important to validate user input, sanitize data to prevent SQL injection attacks, and use prepared statements for database queries. Additionally, always use HTTPS to encrypt data transmission and implement secure password hashing techniques.

// Example of validating user input and using prepared statements for database queries

// Validate user input
$username = $_POST['username'];
$password = $_POST['password'];

// Sanitize data to prevent SQL injection
$username = mysqli_real_escape_string($conn, $username);
$password = mysqli_real_escape_string($conn, $password);

// Use prepared statements for database queries
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

// Check if user exists and password matches
if($result->num_rows > 0) {
    // User authenticated, proceed with secure actions
} else {
    // Invalid credentials, handle error
}