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.
CodePudding user response:
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;
}
CodePudding user response:
For JavaScript side, you may set up a MutationObserver
to prevent maxlength
from being changed.
Bear in mind this is not bulletproof but just adds difficulty. Users might alter the request to change the content that send to the server. So you might also want to validate the data on your server side.
[...document.querySelectorAll('input[maxlength]')].forEach(input => {
const originalMaxLength = input.getAttribute('maxlength');
new MutationObserver((mutations, observer) => {
const mutation = mutations.find(({ attributeName }) => attributeName.toLowerCase() === 'maxlength');
if(mutation && originalMaxLength !== input.getAttribute('maxlength')) {
console.log('maxlength has been changed, restoring...');
input.setAttribute('maxlength', originalMaxLength);
}
}).observe(input, { attributes: true });
})
<h2>Try inspect and change maxlength</h2>
<input type="text" name="username" maxlength="250" alt="Please don't change my maxlength">
CodePudding user response:
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.";
}