如何通过Laravel检查URL是否存在?

时间:2015-01-09 05:15:19

标签: php url laravel

我看到了这个答案:

How can I check if a URL exists via PHP?

但是,我想知道Laravel中是否存在可以检查URL是否存在(而不是404)的方法吗?

4 个答案:

答案 0 :(得分:5)

我假设您要检查某条路线是否与某个网址匹配。

$routes = Route::getRoutes();
$request = Request::create('the/url/you/want/to/check');
try {
    $routes->match($request);
    // route exists
}
catch (\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e){
    // route doesn't exist
}

答案 1 :(得分:0)

尝试此功能

function checkRoute($route) {
    $routes = \Route::getRoutes()->getRoutes();
    foreach($routes as $r){
        if($r->getUri() == $route){
            return true;
        }
    }

    return false;
}

答案 2 :(得分:0)

不是特别的laravel功能,但你可以试试这个

function urlExists($url = NULL)
{
    if ($url == NULL) return false;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpcode >= 200 && $httpcode < 300) {
        return true;
    } else {
        return false;
 }

答案 3 :(得分:0)

由于您提到要检查外部URL(例如http://google.com/)而不是应用程序内的路由,因此可以在Laravel中使用use GuzzleHttp\Client,如下所示:

use GuzzleHttp\Client;

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

if( $request->getStatusCode() == 200 ) {
    // Do something ...
}