Check if the url returns 200 within 5 seconds

This commit is contained in:
Notoric 2024-06-10 04:41:52 +01:00
parent d03bab8e02
commit 25a8619c00
3 changed files with 18 additions and 2 deletions

View File

@ -4,6 +4,7 @@ namespace App\Http\Controllers;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Models\Shortlink; use App\Models\Shortlink;
use GuzzleHttp\Client;
class ShortlinkController extends Controller class ShortlinkController extends Controller
{ {
@ -18,6 +19,21 @@ class ShortlinkController extends Controller
]); ]);
//check if url returns 200 at its final redirect //check if url returns 200 at its final redirect
$guzzle = new Client([
'timeout' => 5
]);
try {
$response = $guzzle->get($request->url, ['allow_redirects' => ['track_redirects' => true]]);
if ($response->getStatusCode() != 200) {
return back()->withErrors([
'error' => 'The URL provided did not return a valid response'
]);
}
} catch (\Exception $e) {
return back()->withErrors([
'error' => 'The URL provided did not return a valid response'
]);
}
$shortlink = new Shortlink(); $shortlink = new Shortlink();
$shortlink->create($request->url, auth()->id()); $shortlink->create($request->url, auth()->id());
@ -27,7 +43,6 @@ class ShortlinkController extends Controller
'error' => $e->getMessage() 'error' => $e->getMessage()
]); ]);
} }
} }
public function goto(Request $request, $id) { public function goto(Request $request, $id) {

View File

@ -6,6 +6,7 @@
"license": "MIT", "license": "MIT",
"require": { "require": {
"php": "^8.2", "php": "^8.2",
"guzzlehttp/guzzle": "^7.8",
"laravel/framework": "^11.9", "laravel/framework": "^11.9",
"laravel/tinker": "^2.9" "laravel/tinker": "^2.9"
}, },

2
laravel/composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "7e8c3c14ff33b199b4a0838993eb8423", "content-hash": "55d18cb1b7b1ab5b14edeb92768c4021",
"packages": [ "packages": [
{ {
"name": "brick/math", "name": "brick/math",