0

My users have a cookie with a string called code in it, the code is just random numbers or letters between 6 and 15 characters long. How after I receive the code, how can I check to ensure that the code is between 6 and 15 characters long and only contains numbers and letters?

Is using regular expressions the best way?

3 Answers 3

1

There are two easy ways you can do this. One is using regular expressions:

$length = strlen($cookie);
if (6 <= $length && $length <= 15 && preg_match('/^[a-zA-Z0-9]*$/', $cookie)) {
    //...
}

The other is using the built-in ctype_alnum function which does exactly that (making sure a string is alpha-numeric):

$length = strlen($cookie);
if (6 <= $length && $length <= 15 && ctype_alnum($cookie)) {
    //...
}
Sign up to request clarification or add additional context in comments.

Comments

0

I would try something like : ^([a-zA-Z]|\d){6,15}$

“between the beginning and the end of the string, there are between 6 and 15 characters, each of them a letter or a digit”.

And, oh, the function you need is preg_match()

Comments

0

php's regex is pretty quick, and this is a case of a simple selector:

"/^[a-zA-Z0-9]{6,15}$/"

But @amosrivera was right about strlen being faster. If the cookie data is being plugged in the page (echo $_COOKIE['key'];) then the XML entities wont matter as the user can only harm their own page. If the cookie is being stored in a database and being displayed for all users, it would be a different matter altogether.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.