7

I've done some researching on validating URLs in PHP and found that there are many different answers on StackOverflow, some better than others, and some very old and outdated.

I have a field where users can input their website's url. The user should be able to enter the URL in any form, for example:

example.com
www.example.com
http://example.com
http://www.example.com
https://example.com
https://www.example.com

PHP comes with a function to validate URLs, however, it marks the URL as invalid if it doesn't have http://.

How can I validate any sort of URL, with or without http:// or https://, that would ensure the URL is valid?

Thanks.

9
  • 2
    Why don't you simply append http:// to it anyway? Commented Dec 18, 2013 at 22:17
  • Check out parse_url() as a function to explode the URL into components, you could then fix up any thing you need to, and then stitch it all back together for validation. Someone wrote a unparse_url() function in the user comments. Commented Dec 18, 2013 at 22:18
  • Check if string starts with http, if it does not, append it. Commented Dec 18, 2013 at 22:19
  • 1
    @Scuzzy: parse_url() is a highly unfit choice to start any form of URL validation. It is incredibly hard to find any input that doesn't make it through parase_url(). Even strings with several schemata and linebreaks make it through. Commented Dec 18, 2013 at 22:26
  • 2
    @Bagwell the internet is old, it still uses TCP/IP. Commented Dec 18, 2013 at 22:28

5 Answers 5

25

Use filter_var() as you stated, however, by definition a URL must contain a protocol. Using just http will check for https as well:

$url = strpos($url, 'http') !== 0 ? "http://$url" : $url;

Then:

if(filter_var($url, FILTER_VALIDATE_URL)) {
    //valid
} else {
    //not valid
}
Sign up to request clarification or add additional context in comments.

5 Comments

Unfortunately, this will return true although $url = '0812345'. It will add prefix 'http://' and filter_var('http://0812345', FILTER_VALIDATE_URL) will return true. Any suggestion solution?
@fendiSetiawan What makes you think that’s not a valid URL?
Sure, if I run parse_url('http://0812345') it will return '0812345' as hostname. Technically, it's true. But, if user visit that url, it will return not found. Since it's not IP address or domain with TLD. I expect some validation that return true only if it's valid IP address or url website with TLD (example.com). Am I get wrong here? Or Am I just not knowing how url are called "valid"?
There’s valid and then there’s existing or reachable. There should be a question somewhere that addresses that. If not then ask one. You can post the link here as I have some ideas.
Ah... I see... The "unreachable URL" is what I looking for. Thank you for your help. Sorry if my question make some miss-understanding. Thanks.
3

I've also seen this used:

$url = "http://example.com";
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $url)) {
  echo "URL is valid";
}
else {
  echo "URL is invalid";
}

Source: http://codekarate.com/blog/validating-url-php

4 Comments

Because filter_var($url, FILTER_VALIDATE_URL); is too long?
Validating this kind of stuff is way much complexer
Because filter_var isn't available before 5.2, and because it doesn't handle dashes well.
in 7 it does handle dashes
0

You can create a custom validation rule then add the following method in it :

protected function prepareForValidation()
{
        $urlWithHttp = strpos($this->url, 'http') !== 0 ? "http://$this->url" : $this->url;

        $this->merge([
            'url' => $urlWithHttp,
        ]);

}

Comments

0

The question is from a decade ago, and my answer might might not be applicable for all cases, but probably the best approach is to send a small request to the url and see if it works.

Comments

-2

You could also let html validate the url:

Website: <input type="url" name="website" required pattern="https?://.+">

2 Comments

Client side validation should never be trusted.
@Aniket Chowdhury Here's why your answer is out of topic: 1. OP mentions he'd looking for a way to do said validation in PHP 2. Even if we disregard the above, "Let the html validate the url" implies, in the context of the question asked by OP, to let the front end do the validation and accept it at the backend, which is totally not acceptable. Whether front end validation should or should not be done is not the matter at hand, hence the flag.

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.