I had no option but to ask you pros to help me out.
Well,I have a HTML form that allows the user input a message and a name.I wanted to set the message's maximum byte to 600-byte and set the name's max byte to 30 byte, but should I use the php to set the limit of user input? If there is a way to handle it in php I would want to know .
<form id="formed" action="second.php" method="post">
<textarea rows="5" cols="20" name="text" id="text"></textarea><br />
<input type="text" name="name" id="name"/><br />
<input type="submit" name="sub" id="sub"/><input type="button" id="display" value="display">
</form>
You should detect this on both the client and server side. Doing it on the client side lets the user know they shouldn't make the string any longer, and doing it on the server side ensures that the string actually won't be any longer than what you want.
The html on the client side can be modified by anyone through a tool such as the developer tools in a browser, so one could remove the maxlength property of your html elements and then send a string much longer than 30 characters.
<textarea rows="5" cols="20" name="text" id="text" maxlength="600"></textarea>
<input type="text" name="name" id="name" maxlength="30">
if(strlen($_POST['name']) > 30) {
// Name is too long, report an error to the user
}
if(strlen($_POST['text']) > 600) {
// Text is too long, report an error to the user
}
Input tags have a maxlength attribute, used such as:
<input type="text" name="name" id="name" maxlength="30" />
Textarea elements in HTML5 have maxlength attribute, but is only supported in some browsers.
You could also implement JS checking, ie called on keydown events on those inputs, or when submitting the form.
To truncate a string to a maximum length via PHP, you can use substr. For example, to truncate a string to a maximum length of 30 characters:
$str = substr($str, 0, 30);