HTML, Javascript, and PHP - maxlength able to be changed through inspect element

Viewed 45

Back with an issue which I'm sure you guys will find easy to fix. Whilst using the maxlength function in html, I noticed that users can simply use inspect element to modify the maxlength deeming it pretty useless.

Basic example of max-length:

<input type="text" name="username" maxlength="250" alt="Please don't change my maxlength">

I'm looking for a solution in Javascript or PHP at preventing this code manipulation on the server side.

Thanks in advance.

2 Answers

There's no point trying to work around this in JS as users can simply bypass your validation code and manually submit a form to your site which has a value longer than the specified maxlength. So you need to deal with it in PHP:

$username = $_POST['username'] ?? '';
if (strlen($username) > 250) {
    // return some sort of error to the user
    exit;
}

Make sure input sanitization and validation on server-side, client-side is not always secure. Like below code block but need more improvement

https://www.php.net/manual/tr/filter.filters.sanitize.php


$input = trim($_POST["YOUR_INPUT"]); // clear left and right whitespaces
$input = filter_var($input, FILTER_SANITIZE_STRING); //sanitize input

if(mb_strlen($input)>=255){
  return "Input can not be longer than 255 chars.";
}

Related