DEV Community

Imam Ali Mustofa
Imam Ali Mustofa

Posted on • Edited on • Originally published at darkterminal.prose.sh

1

Redirect When Not Authenticated in PHP + HTMX

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:

function handleAjaxOrRedirect(Response $response, string $path, int $code)
{
    if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
        $response->setStatusCode($code);
    } else {
        $response->redirect($path);
    }
    exit();
}
Enter fullscreen mode Exit fullscreen mode

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

$response = new Response();
if (!isAuthenticate()) {
    handleAjaxOrRedirect($response, '/', 401);
}
Enter fullscreen mode Exit fullscreen mode

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

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (1)

Collapse
 
darkterminal profile image
Imam Ali Mustofa

Give me slap if you have a better approach!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs