Skip to main content

Session-Based Authentication (PHP)

This guide covers secure, persistent authentication across app sessions for Giftme MiniStores using PHP, cookies, and the JS bridge.

In your login controller (e.g., POST /login), after verifying user credentials:

<?php
$sessionToken = generateSessionToken($userId); // your logic

setcookie(
'giftme_session',
$sessionToken,
[
'expires' => strtotime('+30 days'),
'path' => '/',
'domain' => '.example.com', // subdomain-safe
'secure' => true, // HTTPS only
'httponly' => true, // Inaccessible to JS
'samesite' => 'Lax' // Allows top-level GETs
]
);

header('Content-Type: application/json');
echo json_encode(['success' => true]);

In your layout or page controller:

<?php
$sessionValid = isset($_COOKIE['giftme_session']) &&
isValid($_COOKIE['giftme_session']);

Inject into HTML:

<script>
window.giftmeHasSession = <?= $sessionValid ? 'true' : 'false' ?>;
</script>

3. Frontend: Call JS Bridge Only If Needed

if (!window.giftmeHasSession) {
await giftmeGetAuthCode({ miniStoreId: 'ABC123' });
}

4. If Using fetch() to Log In (SPA or JS login)

Backend Headers:

<?php
header('Access-Control-Allow-Origin: https://mini.example.com');
header('Access-Control-Allow-Credentials: true');

Frontend Fetch:

const res = await fetch('https://auth.example.com/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password })
});

Summary

StepAction
Set CookieUse setcookie('giftme_session', ...) securely
Detect SessionCheck $_COOKIE['giftme_session'] in PHP
Expose to JSInject window.giftmeHasSession = true/false
Call JS BridgeOnly if window.giftmeHasSession === false
SPA LoginUse fetch(..., credentials: 'include') and proper CORS headers