0

How to check if string has a server depending if url is absolute or relative?

function hasServer($url){
    ...
}

If this, returns true

hasServer('http://www.google.com/');

else return false

hasServer('/about-us/team/');
quakeglen
  • 165
  • 3
  • 7

2 Answers2

1

I think this is what you're looking for:

$url = 'http://www.google.com/';
$hasServer = filter_var($url, FILTER_VALIDATE_URL);
  • why did you go and change it to single quotes from [my edited](http://stackoverflow.com/revisions/37120937/2) double quotes? I don't see the improvement here and if there should be a variable passed inside single quotes and the OP wants to pass, your answer will fail – Funk Forty Niner May 09 '16 at 16:37
  • @Fred-ii- why would you use double quotes on a string literal? It is bad practice in general so it should be avoided. If the OP puts a variable inside single quotes then that's his mistake and he learns one more thing. I didn't know your edit would disappear from history, did you lose rep for that? – Salomao Rodrigues May 09 '16 at 20:30
1

There are actually a few options from my experience. One would be to use the headers() function and then to analyse what information you obtained inside the resulting array.

$arrayResult = headers('http://www.google.com/');
foreach ($arrayResult as $value)
{
  echo "-- ".$value."<br>";
}

The output should give you all the information you need regarding if the url actually exists.

A simpler solution in my opinion is to just check if the fopen() function actually works on the url!

if (fopen('http://www.google.com/', "r")
{
  echo "the URL exists!<br>";
}

You can choose which one servers your needs better.

Webeng
  • 7,050
  • 4
  • 31
  • 59