Jump to content

Does anyone have a function for validating URL entry.


bag

Recommended Posts

Users have the capability of entering URLs and I have used the following

 

$pattern = "^(https?|ftp)\:\/\/([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?@)?[a-z0-9+\$_-]+(\.[a-z0-9+\$_-]+)*(\:[0-9]{2,5})?(\/([a-z0-9+\$_-]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:@/&%=+\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?\$";

if ( preg_match($pattern, $url) == FALSE ) {

 

It got a bit out of hand and I'm lost.  This one fails to validate valid urls and url validation must be something that has been done to death.

I've not really looked at your pattern in any detail, but it should throw an error. PCRE patterns (ie preg_ functions) require delimiters. A search on google for validating URL should turn up millions of possible patterns, it mainly depends on how accurate you wish to be and which URLs you wish to support ie protocols (http://, ftp:// etc), domains (.co.uk, .info etc), parameters (?id=10&name=bob) and so on.

 

If you are using PHP 5.2 or newer then it would probably make more sense to use filter_var as suggested by JAY6390.

 

… it mainly depends on how accurate you wish to be and which URLs you wish to support ie protocols (http://, ftp:// etc), domains (.co.uk, .info etc), parameters (?id=10&name=bob) and so on.

 

… it would probably make more sense to use filter_var as suggested by JAY6390.

 

With regards to the filter extension, the quoted portion of your first paragraph is just as relevant as with the regex approach. The FILTER_VALIDATE_URL filter will accept a wide variety of URLs and it's likely the application will want to accept a subset only. That said, for a first-step the filter works as advertised.

 

Just to clarify, FILTER_VALIDATE_URL will happily accept URLs like the following (and many more):

  • abcdefghjiklmnopqrstuvwxz://.
  • foo://!
  • news:
  • file:_=~-_$.$_-~=_
  • .://.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.