Hi all, I have a small piece of code to check that a field is numeric only,

function validate_numeric($variable) {
	return is_numeric($variable);
}

How can I check that text entered is text only ?
so to protect against malicous attacks. . .

Thanks

Dani AI

Generated

Short answer and context: "Text only" needs a precise definition first — do you mean ASCII letters, letters plus spaces/apostrophes (names), letters and numbers (usernames), or any Unicode letters? Pick an allowlist (whitelist) of exactly the characters you want and validate against that on the server; client-side checks are only for UX. This is the recommended approach for input validation and for handling free-form Unicode text. (cheatsheetseries.owasp.org)

Practical PHP options (pick one that matches your allowlist):

  • For simple ASCII checks, the ctype family is fast and clear.
  • For Unicode-aware letter checks use PHP’s Unicode tools or a Unicode-aware regex (match the Unicode letter category).
    Examples (not the same as the snippets already in the thread):
// ASCII letters only (example)
if (ctype_alpha($s)) { /* OK */ }

// Unicode letters (rough example)
if (preg_match('/^\p{L}+$/u', $s)) { /* OK */ }

See the PHP docs for the ctype functions and for preg_match/PCRE Unicode properties when you need international alphabets. (php.net)

Security pitfalls to avoid: do not trust generic sanitizers as a one-stop defence. The old filter that tried to “sanitize” arbitrary strings has been deprecated in modern PHP releases — prefer context-aware output encoding instead. When storing or querying a database use prepared statements; when emitting into HTML use proper HTML-escaping. For XSS prevention and the input-vs-output responsibilities, follow the OWASP guidance. (php.net)

Quick checklist to follow (applies to question and builds on and comments):

  1. Decide exactly which characters are allowed. 2) Normalize input (Unicode NFC). 3) Validate server-side with a whitelist. 4) Limit length. 5) Escape on output for the target context (HTML/JS/SQL). If unsure about Unicode edge cases, use IntlChar helpers. (cheatsheetseries.owasp.org)

Recommended Answers

All 3 Replies

Hmmmm. . . Can anyone make any sence of the following -

preg_replace('#[^A-Za-z0-9]#i', '',

To me, the above reads, if a letter or number, replace with nothing ?
Is that right. .

The code:

preg_replace('#[^A-Za-z0-9]#i', '',

Just removes every character in a string that is not a letter or number. The "^" means not in regular expressions, so

[^A-Za-z0-9]

means not anything inside the brackets.

What do you mean “to protect against malicous attacks. . .” , what type of variables do you want to avoid ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.