【问题标题】:How can I check if a URL exists via Laravel?如何通过 Laravel 检查 URL 是否存在?
【发布时间】:2015-03-07 09:37:48
【问题描述】:

我确实看过这个答案:

How can I check if a URL exists via PHP?

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

【问题讨论】:

  • 你想检查外部 url 还是 laravel 内部的路由?
  • @DouglasDC3:我不知道有什么不同。我想检查一个外部网址。
  • 您添加的另一篇文章中描述了最佳方法。
  • @DouglasDC3:所以你是说没有办法通过 Laravel 做到这一点?
  • 据我所知不知道。我已经研究过了,laravel 没有提供这种功能

标签: php url laravel


【解决方案1】:

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

use Illuminate\Support\Facades\Http;

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

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

【讨论】:

    【解决方案2】:

    不是特别的 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;        
       }
    

    【讨论】:

      【解决方案3】:

      试试这个功能

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

      【讨论】:

      • 这不适用于路由参数 - 使用 $routes-&gt;match() 可以解决这个问题。
      【解决方案4】:

      我假设您想检查是否有与某个 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
      }
      

      【讨论】:

      • 有没有办法通过 Laravel 检查外部 URL?
      • OP 提到他想检查一个外部 URL。他没有在应用程序中说出路线。
      • 出于某种原因,即使路线不存在,我也没有收到NotFoundHttpException。相反,我得到一个带有 uri 的路由对象:{fallbackPlaceholder}。有什么想法吗?
      • @ThembaClarenceMalungani 像这样:``` 受保护的函数 routeExists(string $url): bool { $routes = Route::getRoutes(); $request = 请求::create($url); return (bool) $routes->match($request)->getName(); } $this->routeExists($this->request->fullUrl()) ```
      猜你喜欢
      • 2011-01-17
      • 2019-02-28
      • 2017-02-01
      • 2020-07-05
      • 2020-06-25
      • 2011-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多