Free cookie consent management tool by TermsFeed Generator PHP Validate URL | Amir Kamizi
AMIR KAMIZI
Home Blog Courses Books Newsletter Store Membership Buy me a coffee
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 = "example.com";
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

Conclusion

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
  • FILTER_VALIDATE_URL

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

PHP Validate Email
Feb 15, 2023 programming

PHP Validate Email

Today we are going to talk about validating emails in PHP. In a lot of projects you need to validate the emails given by the user to make sure the email address has a correct format. ...

4 Min Read Read More
PHP Sanitize Data
Feb 15, 2023 programming

PHP Sanitize Data

Today we are going to talk about sanitizing data in PHP. Sanitizing data is a very important step, especially when you are dealing with user data. ...

7 Min Read Read More

Recommended Courses

Introduction to Machine Learning in PHP

Introduction to Machine Learning in PHP

Learn to Build Different Machine Learning Models Easily ...

PHP Tutorial Beginner to Advanced

PHP Tutorial Beginner to Advanced

Learn everything you need to start a successful career as a PHP developer ...