How can the PHP code be optimized for better performance and security?
To optimize PHP code for better performance and security, you can implement the following best practices: 1. Use prepared statements for database queries to prevent SQL injection attacks. 2. Minimize the use of global variables and sanitize user input to prevent cross-site scripting (XSS) attacks. 3. Enable output buffering to reduce the number of HTTP requests and improve page load times. Example PHP code snippet using prepared statements for database queries:
// Establish a database connection
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Using prepared statements to prevent SQL injection
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);
// Set parameters and execute
$username = "john_doe";
$stmt->execute();
// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "Username: " . $row["username"] . "<br>";
}
// Close statement and connection
$stmt->close();
$conn->close();