What is wrong with the below code - I want to limit the characters a user can use (PHP)?

  • Thread starter Thread starter Lewis
  • Start date Start date
L

Lewis

Guest
$subject=$_POST['subject'];
$charlimit = 20;
if (strlen($subject) < $charlimit)
{
print "<table border=0 width=50% align=center bgcolor=#999999><tr><th width=100%><font color=red size=3>You cannot exceed 60 characters for your subject!</font></th></tr></table><br /><br />
<center><a href='gforum.php'><font color=white size=2><b>< Go Back</font></b></a></center>";
}
 
1) You've set a character limit of 20 but your error message refers to a length of 60
2)Line 3 will only trigger the print statement if $subject contains LESS THAN 20 characters. Change < to > and make $charlimit agree with the message or vice versa
 
$subject=$_POST['subject'];
$charlimit = 20;
if (strlen($subject) < $charlimit)
{
print "<table border=0 width=50% align=center bgcolor=#999999><tr><th width=100%><font color=red size=3>You cannot exceed $charlimit characters for your subject!</font></th></tr></table>


<center><a href='gforum.php'><font color=white size=2><b>< Go Back</font></b></a></center>";
exit;
}

add exit like i did to stop the script and just use $charlimit so you only have to write the max len 1 time for the whole script.

you could try

substr();

$truncated_string = substr($_POST['subject'], 0, 15) . "...";
 
Back
Top