我确实看过这个答案:
如何通过 PHP 检查 URL 是否存在?
但是,我想知道Laravel中是否存在可以检查URL是否存在(不是404)的方法?
我假设您想检查是否有与某个 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
}
既然你提到你想检查一个外部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 ...
}
不是特别的 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;
}
试试这个函数
function checkRoute($route) {
$routes = 'Route::getRoutes()->getRoutes();
foreach($routes as $r){
if($r->getUri() == $route){
return true;
}
}
return false;
}