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%@ ?