URL validation not working right

I’m fairly new to php but feel I have picked it up pretty well so far. I am creating a contact form for my portfolio and I am having trouble trying to validate the URL.

I’m using filter_var with FILTER_VALIDATE_URL, annoyingly it needs http://, so I do a if statement that substrings the first 7 characters to test if it equals http://, this test is failing for some reason, no matter what I try it never passes.

Here is my code for this section: The rest work except the url, and the url works with http://

[php]function VerifyForm(&$values, &$errors)
{
// Do all necessary form verification

if (strlen($values['name']) < 3)
    $errors['name'] = '<style>.name {border-color:red}</style>';
elseif (strlen($values['name']) > 50)
    $errors['name'] = '<style>.name {border-color:red}</style>';

if (!filter_var($values['email'], FILTER_VALIDATE_EMAIL))
    $errors['email'] = '<style>.email{border-color:red}</style>';

// URL - test for value, if > than 0, test if valid
if (strlen($values['url']) > 0)
{
	
	if(!substr($values['url'],0,7) == "http://")
		$values['url'] = "http://{$values['url']}";
	else
		echo "didn't work";

	if(!filter_var($values['url'], FILTER_VALIDATE_URL))
		$errors['url'] = '<style>.url{border-color:red}</style>';
}

if (strlen($values['text']) == 0)
    $errors['text'] = '<style>.text{border-color:red}</style>';
    
return (count($errors) == 0);

}[/php]

If my logic is correct, the first if statement will test if the length of the url is greater than 0, if it is then it will test if the first 7 characters is http://, if its not, it is suppose to append http:// to the url and perform the filter_var.

Any insight would be nice, thanks.

hello jebrown21,
below code for url validation in php
//VAlidate URL in PHP
$url=‘www.google.com’;
if(!preg_match(’|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)(:[0-9]+)?(/.)?$|i’, $url))
{
$new_url = ‘http://’.$url;
if(!preg_match(’|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)(:[0-9]+)?(/.)?$|i’, $new_url))
{
echo $url.’ Wrong URL’;
}
else
{
echo $new_url.’ Correct URL’;
}
}
else
{
echo $url.’ Correct URL’;
}

this will helpful for you
SR

Thanks for the reply, I understand its helpful and easy to do it that way, the reason I posted here though is to find out why my code I posted isn’t working, I can’t learn if I can’t find out where I went wrong.

Again thanks for the help, If anyone else can see the logic error in my code, please let me know.

Well, IF clauses are in this format: IF ( condition AND/OR condition AND/OR condition )

Yours: if(!substr($values[‘url’],0,7) == “http://”)

is basically IF ( NOT(some-value) equal-to something )

What is the NOT of your substr??? Your IF does not make sense… Try it this way:

          if(substr($values['url'],0,7) != "http://")    which is  IF ( something NOT something  )

Hope that explains it… Good luck!

Sponsor our Newsletter | Privacy Policy | Terms of Service