Search code examples
phpsqlsql-serverformssql-injection

How Can I Prevent MSSQL Injections in PHP?


I know this is a widely covered topic but after searching Google for MSSQL injection prevention for PHP, I have found close to nothing.

This is the closest answer I could find, but it seems the answer is for MySQL and not MSSQL.

The PHP code I am using allows an admin to log-in to the website via form inputs in order to access the back-end. This code is what logs the admin in after the form has been submit:

<?php
  session_start();

  if($_SERVER['REQUEST_METHOD'] == "POST") {
$conn=mssql_connect('d','a','d');
mssql_select_db('d',$conn);
if(! $conn )
{
  die('Could not connect: ' . mssql_get_last_message());
}

    $username = ($_POST['username']);
    $password = ($_POST['password']);

    $result = mssql_query("SELECT * FROM back_end WHERE username='$username' AND
      password='$password'");
  if(mssql_num_rows($result) > 0) {
      $_SESSION['is_logged_in'] = 1;
      $_SESSION['backname'] = $username;
    }
  }

  if(!isset($_SESSION['is_logged_in'])) {
    header("location:logingbm.php");
    echo "<script>alert('Incorrect log-in information!');</script>";
  } else {
    header("location:../d/index.php");
  }
?>

If somebody could give me a few hints towards what code I should put in to prevent malicious injections, it would be greatly appreciated. Thank you for any help.


Solution

  • You're using the older mssql extension. It's no longer available as of PHP 5.3. Instead, there is now sqlsrv and that function set includes the ability to run prepared statements, which is the most secure way to run your queries.