How can SQL injections or malicious upload scripts be prevented to protect PHP websites from attacks?

To prevent SQL injections, PHP websites should use prepared statements with parameterized queries to sanitize user input. To protect against malicious upload scripts, file uploads should be restricted to specific file types and stored in a secure location outside of the web root directory.

// Prevent SQL injections with prepared statements
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Prevent malicious upload scripts
$allowedFileTypes = ['jpg', 'png', 'gif'];
$uploadPath = '/uploads/';

if (in_array(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION), $allowedFileTypes)) {
    move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER['DOCUMENT_ROOT'] . $uploadPath . $_FILES['file']['name']);
}