0

How can I check if an url exists in laravel 5.1?

For example, I want to check if www.google.com exists.

$url ="www.google.com";
if(exists(url)){
     // do something
}

What function or code can I use to return true for the above example?

Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52
Wandy Liem
  • 49
  • 1
  • 9

2 Answers2

0

In Laravel you can use use GuzzleHttp\Client as such:

use GuzzleHttp\Client;

$client = new Client();
$request = $client->head('http://google.com/');

if( $request->getStatusCode() == 200 ) {
    // Do something ...
}
Max S.
  • 1,383
  • 14
  • 25
-1

You can use normal PHP code in laravel.

Use get_headers() function, it returns false if the given domain is not registered.

$url = 'http://google.com/';
if(get_headers($url))
    // do something

And don't forget the HTTP (http://) protocol prepending the domain.

nipeco
  • 760
  • 2
  • 9
  • 24
  • 1
    @Wendy Liem please accept the as solution. – Tim van Uum Nov 29 '15 at 08:18
  • 1
    `get_headers()` will become `TRUE` if server returns error codes (like 404). – Rafał Swacha Dec 01 '15 at 12:33
  • 1
    But we don't want to get error codes, we just want to know if the url exists – nipeco Dec 01 '15 at 12:47
  • Yes, but you can get headers for non-existing urls (like server-side generated 404 pages). Example: while checking "stackoverflow.com/NotExisting" you will get "TRUE", becouse headers will be sent, but this is not a valid address. – Rafał Swacha Dec 03 '15 at 08:56
  • You are right! But well there are 2 possibilities, i guess that he wants to know if the domain exists (is registered). In that case `get_headers()` fits totally in. In the case you want to know if a file on the server exists you have to choose another way. Since he said 'it works' it might be the right solution ;) – nipeco Dec 03 '15 at 09:22