0

I have a little chat application where I want the users to be able to send username and a message. The Javascript validation for it looks like this:

js Validation:

    var re_username = /^[a-zA-Z.-]+(?:\040[a-zA-Z.-]+)*$/;
    var is_username = re_username.test($('#chatusername').val());

    var re_message = /^[a-zA-Z.]+(?:\040[\w\,\.\:\?\!\&\-\n\%\@]+)*$/;
    var is_message = re_message.test($('#messagecomment').val());

... then I'm sending it with JSON.stringify() and via $.ajax({}) to PHP with prepared statements, which then looks like this:

php:

require('../dbconfig.php');

$mysqli = new MySQLi($server,$user,$password,$database);

// prepare and bind
$stmt = $mysqli->prepare("INSERT INTO messages (username, message) VALUES (?, ?)");
$stmt->bind_param("ss", $username, $message);

$data = file_get_contents("php://input");
$arr = json_decode($data,true);

$username = $mysqli->real_escape_string($arr['username']);          
$message = $mysqli->real_escape_string($arr['message']);

// possible php validation ?:
if(preg_match("/^[a-zA-Z.-]+(?:\040[a-zA-Z.-]+)*$/u", $username)) {
  print $json_invalid;
  exit;
}

if(preg_match("/^[a-zA-Z.]+(?:\040[\w\,\.\:\?\!\&\-\n\%\@]+)*$/u", $message)) {
  print $json_invalid;
  exit;
}

$stmt->execute()
$stmt->close();
...

Is this setup fairly safe or how should a proper formattting, php validation and preg_match() look like when allowing characters like ,.:?!&-n%@ ?

Philipp M
  • 3,306
  • 5
  • 36
  • 90
  • One problem - one question. – Your Common Sense May 12 '17 at 13:34
  • Reduced it to one question and looking at the provided link and your sql injection tutorial ... . So in addition I should use prepared statements and parameterized queries? – Philipp M May 12 '17 at 14:22
  • yes, regarding mysqli you should be using prepared statements. – Your Common Sense May 12 '17 at 14:26
  • @Your Common Sense: I updated my setup and now also use prepared statements. Please see update above. Is this setup fairly safe when allowing characters like ,.:?!&-n%@ for an input field? Or what else should I consider? – Philipp M May 14 '17 at 14:06

0 Answers0