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.

Link to comment
Share on other sites

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.

 

Link to comment
Share on other sites

… 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:_=~-_$.$_-~=_
  • .://.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.