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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27854247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:39:38  来源:igfitidea点击:

How can I check if a URL exists via Laravel?

phpurllaravel

提问by rotaercz

I did look at this answer:

我确实看过这个答案:

How can I check if a URL exists via PHP?

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

However, I was wondering if a method exists in Laravel that can check if a URL exists (not 404) or not?

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

回答by lukasgeiter

I assume you want to check if a there's a route matching a certain URL.

我假设您想检查是否有与某个 URL 匹配的路由。

$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
}

回答by Bhargav Kaklotara

Not particular laravel function, but you can make a try on this

不是特别的 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);
        return ($httpcode >= 200 && $httpcode < 300) ? true : false;        
   }

回答by Max

Since you mentioned you want to check an external URL (eg. https://google.com), not a route within the app , you can use use the Httpfacade in Laravel as such (https://laravel.com/docs/master/http-client):

由于您提到要检查外部 URL(例如https://google.com),而不是应用程序内的路由,因此您可以使用HttpLaravel 中的外观(https://laravel.com/docs/master/http-client):

use Illuminate\Support\Facades\Http;

$response = Http::get('https://google.com');

if( $response->successful() ) {
    // Do something ...
}

回答by aphoe

try this function

试试这个功能

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

    return false;
}