In what ways can PHP code be optimized and refactored to improve readability, maintainability, and security?

To optimize and refactor PHP code for improved readability, maintainability, and security, consider the following strategies: 1. Use meaningful variable names and comments to make the code more understandable. 2. Break down complex functions into smaller, reusable functions for easier maintenance. 3. Sanitize user input to prevent SQL injection and cross-site scripting attacks. Example:

// Before refactoring
$un = $_POST['username'];
$pw = $_POST['password'];

$query = "SELECT * FROM users WHERE username='$un' AND password='$pw'";
$result = mysqli_query($conn, $query);

// After refactoring
$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);