"Anders Thoresson" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Hi,
>
> I'm having problem with a function that I'll use to validate user input
> before passing it to MySQL. For strings, I want to make sure that they
> aren't to long, so I have written this function:
>
> function secure_string($unsafe_string, $max_length = -1, $errormessage =
> "Too many characters." ) */ { // verify that string isn't longer then
> $max_length, if $max_length is set if ($max_length > -1) { if
> (!is_int($max_length)) { error("Variable max_length is not an integer." );
> } if (strlen($unsafe_string) > $max_length) { error($errormessage); } }
...
> and the validation will continue here.
>
>
> When I want to use the max length check I pass a value to the function
like
> this:
>
> $a_header = secure_string($_POST['a_header'], 60, "Header must not be more
> then 60 characters." );
>
> But I having to problems:
> 1) If no max length is passed, and $max_length gets the value -1, the if-
> loop if ($max_length > -1) is still run.
> 2) Calls to my own function error doesn't work. Instead of creating a
> popupwindow with javascript (which works in other places where error() is
> called) the errormessage is printed like html.
>
> What's wrong?
>
> Best regards,
>
> --
> anders thoresson

Having trouble with your line wrap?

Okay.. from what I can decipher you have a logic error starting with the
first if() statement.  You've set a default value of -1 and then you're
testing if the input is greater than -1.  However if the variable Is Set but
Empty the input will evaluate to 0 which is greater than -1 and the
condition will be true.  This is what Jason was talking about but it's only
half the problem.

The other thing is if you're going to use the default value then the
is_int() statement should come *before* the value comparison.  But you
should not need the default value at all becuase your're testing the
validity of $max_length against the length of the string later in the
function.  Provided you know that the value is an integer and less than
$max_length then any testing beyond that is just redundant nonsense.

So fortunately all you need to do is eliminate the default value along with
the first if() statement and you should be good to go..

function secure_string($unsafe_string, $max_length)
{
 if(!is_int($max_length))
  error("Variable max_length is not an integer." );

 if (strlen($unsafe_string) > $max_length)
  error("Too many characters.");
}

- Kevin



-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to