I am using the strpos function to validate a url that is submitted by a user and I want to make sure I'm not missing anything that would allow the user to bypass the validation and submit a url that is inappropriate.
Take the following as an example, if I only want a user to be able to input a url associated with the youtube domain, I don't want them to be able to put a wildcard (*) or something in that would "trick" the strpos function.
$url = $request->input('url');
// Check if Youtube url is found
if (strpos($url, 'http://youtube.com') > -1)
{
// some code
}
// some code
Thanks!
strpos
returns false when in a not found condition and 0
if the string appears in the first column, which also looks like false
to PHP, so it would be more accurate to use ===
or !==
$url = $request->input('url');
// Check if Youtube url is found
if (strpos($url, 'http://youtube.com') !== FALSE)
{
// some code when youtube is found in url
}
You would be better off using a Regular expression.
^(https?\:\/\/)?(www\.)?(youtube\.com|youtu\.?be)\/.+$
Try it out.
Remember to test with type safe equation.
strpos
will find the position of first occurrence in the string. So if there is a match in the beginning of string (position 0)
if (strpos($url, 'http://youtube.com') > -1)
will return 0 which will be interpreted as false
. You're in trouble here.
Instead, do it type safely:
if (strpos($url, 'http://youtube.com') !== false)
This means no matter where in the string your substring is found, it will be considered true and you know there is a match.