As a security measure? No.
Attacks via user input occur when a user is able to input commands, usually in the form of database queries, into variables you haven't escaped properly. While truncated input might inadvertently prevent an attack, it isn't truly solving the problem.
In terms of security you should validate all user input, and check that the input is only used in a protected fashion, some of the cases are:
- If the value is to be output in HTML, you will want to ensure it either has no HTML tags in it (
strip_tags
) or only the ones you allow (either use a library, or DOMDocument
for this).
- If the value is to be used in a calculation, make sure it's a valid number. Easiest way is to cast as
(int)$foo
or (float)$foo
but your needs may vary.
- If the value is to be stored in a database, make sure you don't build your query in an unsafe way. Best way to keep queries safe is to use prepared statements,
PDO
is good for this. Otherwise you need to make sure you escape user input before building your query.
If you tell a user to only enter letters and numbers for a value, then you should only accept letters and numbers on your server. You can add the same condition on the client side, to prevent surprises for your users (giving them an error before sending a form), but the server is where you actually protect yourself, as client-side validation is informative, it's not protective (it's easily bypassed).
On that basis, if you can only store a limited number of characters in a field, you may as well report it to the user if a field is too long.
Let's say you want an e-mail address no more than 128 characters long, you could handle this at all levels like so:
Database (Model)
CREATE TABLE Emails `email` VARCHAR(128) NOT NULL
PHP (Controller)
$email = $_POST['email'];
if ((strlen($email) > 128) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Produce error that input was invalid
die('ERROR: Invalid e-mail');
}
// Input is valid, store in database (e.g- with PDO)
$stmt = $pdo->prepare('INSERT INTO Emails (email) VALUES (?)');
$stmt->execute([$email]);
HTML (View)
<input name="email" type="email" maxlength="128" placeholder="E-mail" />
This gives you a good mixture of storage efficiency, correctness, safety and feedback to the user; if they have a browser that supports HTML5 they will get early errors if they try to send an invalid value, but we check on the server anyway for safety (non-HTML5 compliant browser, or malicious user).