# JS PHP insert data in database - is it secure enough?

I'm working on a webapp and I'm using js/php (php and jquery latest versions).

Is there anything I should do to improve security?

I'm not super worried about safety as the current users are using a very buggy (pretty much every exploit works) and outdated (php 4) platform and never attempted anything.

But better be safe than sorry and learn in the process.

IN JS SIDE I HAVE THIS:

a function to insert data

function insertItem() {


First i do some js validation for empty fields (will check again in php side)

 var valErrors = 0;
if (!$('#addName_input').val()) {$('#addName_input').addClass("inputError");
valErrors++;
}
if (valErrors>0) {
new Noty({
type: 'error',
layout: 'topCenter',
timeout: '2000',
progressBar: 'true',
overlay: 'true',
text: 'The name is empty'
}).show();
return false;
}


I also use a js regex plugin to help me limit what users can type on inputs that have important data. That way i can prevent from inserting letters in input designed for numbers, etc (but i also check that later on php side)

Then i serialize the form data

var data = $("#newForm").serialize();  i send it using ajax: $.ajax({
type: 'POST',
url: 'modules/' + moduleFolder + '/funcs/insert.php',
data: data,
dataType: 'json',
success: function(response) {


now on the PHP side (insert.php)

if the request method is not post i redirect

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { header("HTTP/1.1 301 Moved Permanently"); header("Location: ../../../."); exit(); }  then i fetch the request data: $name   = isset($_POST['addName_input']) ?$_POST['addName_input'] : '' ;


then i do some validations

if (empty($name)) { }  and check with a validation class if the string "hasSomething()" i dont want: if (hasNumbers($name) || hasSpecialChars($name))  then i filter_sanitize all the vars $name  = filter_var($name, FILTER_SANITIZE_STRING);  and finally use a database class (with prepared statements) to insert the data $insert = $db->query('INSERT INTO zapp_list_tablename (id,name) VALUES (?,?,?)', NULL,$name);

• You're inserting one variable as three values into two fields? – luser droog Sep 10 '19 at 4:57
• did you truncate the Javascript? I would guess so, given that valErrors is set to true in the first conditional block and then immediately checked in the next condition... but I could be wrong... also, could you paste more of the PHP? The lines above aren't exactly stub code but it helps to have more context with how the lines are used... the limit for code on this site has been increased to 65535 characters – Sᴀᴍ Onᴇᴌᴀ Sep 12 '19 at 22:05