How to check if URL exists in PHP?

→ Are you a new visitor? Please visit the page guidance for new visitors ←

How to check if URL exists in PHP?

Let’s say you want to check if an URL exists. You want to do that with PHP because that is what you know, and you want to perform some savings into the database if that URL exists. This can be done in various ways which will work or not depending by case.

1st solution

We can do this by relying on http headers, normally if one URL gives a 200 http response code, it will be seen as success. However if this is something else, either the url does not exist or its an error on the other end. You can use the below example:

2nd solution

On some servers, you are not allowed to use CURL, but this can be used on a server that you have access and know it’s configuration:

3rd solution

This one is similar to the first one, but using preg_match to pass true only if it matches the http code with 2xx value.

Each given solution might/might not work depending on some given circumstances.  It is your choice what you will be using for your projects.

Request an article ←