如何通过 Laravel 检查 URL 是否存在?
How can I check if a URL exists via Laravel?
我确实看过这个答案:
How can I check if a URL exists via PHP?
但是,我想知道 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
}
试试这个功能
function checkRoute($route) {
$routes = \Route::getRoutes()->getRoutes();
foreach($routes as $r){
if($r->getUri() == $route){
return true;
}
}
return false;
}
没有特别的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;
}
由于您提到要检查外部 URL(例如 https://google.com
),而不是应用内的路由,您可以使用 Http
facade in Laravel 这样 (https://laravel.com/docs/master/http-client):
use Illuminate\Support\Facades\Http;
$response = Http::get('https://google.com');
if( $response->successful() ) {
// Do something ...
}
我确实看过这个答案:
How can I check if a URL exists via PHP?
但是,我想知道 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
}
试试这个功能
function checkRoute($route) {
$routes = \Route::getRoutes()->getRoutes();
foreach($routes as $r){
if($r->getUri() == $route){
return true;
}
}
return false;
}
没有特别的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;
}
由于您提到要检查外部 URL(例如 https://google.com
),而不是应用内的路由,您可以使用 Http
facade in Laravel 这样 (https://laravel.com/docs/master/http-client):
use Illuminate\Support\Facades\Http;
$response = Http::get('https://google.com');
if( $response->successful() ) {
// Do something ...
}