Redirect When Not Authenticated in PHP HTMX

· darkterminal's blog


Hello Punk!

Yes, I am again. Using HTMX as an isolated component and creating Hypermedia interactivity with less JavaScript code is my goal. (We not talking about Offline First, That's sound "Uuuuaagggrrrrh!" for me)

HTMX using xmlhttprequest when I use hx-{verbs} but in another side (the backend) I use PHP so, this function:

1function handleAjaxOrRedirect(Response $response, string $path, int $code)
2{
3    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
4        $response->setStatusCode($code);
5    } else {
6        $response->redirect($path);
7    }
8    exit();
9}

Really help me so much (thanks for myself) when I need to make sure is the request is valid / authenticated. Like...

1$response = new Response();
2if (!isAuthenticate()) {
3    handleAjaxOrRedirect($response, '/', 401);
4}

I use it inside each controller __constructor. Yes, That's it!