PHP Validate URL

PHP Validate URL

Last Updated on Feb 15, 2023

Validate URL in PHP

Do you remember when we talked about validating emails?

There are 2 ways to validate the urls in php as well:

1- using regular expression

To review how to use regular expressions in php check PHP Regular Expressions.

The actual URL syntax is pretty complicated and not easy to represent in regular expression. That’s why the second way is much better.

2- using filters

The second solution is much easier and is the preferred way.

Php has a lot of filters that you can validate and sanitize data with. In order to use them we need to use the function filter_var

It takes the value as the first argument and the filter as the second argument

The filter for validating urls is FILTER_VALIDATE_URL

So let’s do it

$url = "";
if (!filter_var($url,FILTER_VALIDATE_URL)) {
   echo 'invalid url';
} else {
   echo 'url is correct';
// url is correct

And with invalid urls:

$url = "testexamplecom";
if (!filter_var($url,FILTER_VALIDATE_URL)) {
   echo 'invalid url';
} else {
   echo 'url is correct';
// invalid url


Now you know about validating urls in PHP.

I recommend you to open a PHP files and try to validate different types of URLs. see which one is correct and which one is not.

If you have any suggestions, questions, or opinions, please contact me. I’m looking forward to hearing from you!

Key takeaways

  • validate urls in php
  • filters in php

Category: programming

Tags: #php

Join the Newsletter

Subscribe to get my latest content by email.

I won't send you spam. Unsubscribe at any time.

Related Posts