mythri Posted January 13 Share Posted January 13 I have a php script and i made it as pwa with web-push notifications. Whenever i re-open the app, it asks me to login, i want to keep it logged in. these are the files for pwa index.php in head section i have added <link rel="manifest" href="manifest.webmanifest"> end of the page this <script> document.getElementById('loginForm').addEventListener('submit', function(event) { if (document.getElementById('remember').checked) { document.cookie = "user_login=true; SameSite=Lax; Secure"; document.cookie = "userpassword=true; SameSite=Lax; Secure"; } }); </script> manifest.webmanifest { "name": "MyPhpScript", "short_name": "PHP", "start_url": "/myscript/Dashboard.php", "display": "standalone", "background_color": "#ffffff", "theme_color": "#007bff", "icons": [ { "src": "icon-192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icon-512.png", "sizes": "512x512", "type": "image/png" } ], "screenshots": [ { "src": "img.jpg", "sizes": "640x320", "type": "image/jpg", "form_factor": "wide", "label": "MyPhpScript" }, { "src": "img.jpg", "sizes": "640x320", "type": "image/jpg", "form_factor": "narrow", "label": "MyPhpScript" } ] } service-worker.js 'use strict'; /** * Received push */ self.addEventListener('install', function(event) { event.waitUntil( caches.open('my-cache').then(function(cache) { return cache.addAll([ '/script/', '/script/index.php', '/script/app.js' /** * here goes all my css and js files */ ]); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); self.addEventListener('activate', function (event) { // The service worker is now Active and functioning. console.log("sw Activate : ", JSON.stringify(event)); // Again, ensure that this is the only active service worker for this // page. event.waitUntil(self.clients.claim()); console.log("sw Activated: ", JSON.stringify(event)); navigator.serviceWorker }); self.addEventListener('push', function (event) { let pushMessageJSON = event.data.json(); let vibratePattern = pushMessageJSON.data && pushMessageJSON.data.vibrate ? pushMessageJSON.data.vibrate : [200, 100, 200]; self.registration.showNotification(pushMessageJSON.title, { body: pushMessageJSON.body, icon: pushMessageJSON.icon, vibrate: vibratePattern, data: { additionalData: pushMessageJSON.data ? pushMessageJSON.data.additionalData : null, url: pushMessageJSON.data ? pushMessageJSON.data.url : null, }, }); console.info("pushmessage::", event); }); /** * Click by push */ self.addEventListener('notificationclick', function(event) { let url = event.notification.data.url; event.notification.close(); // Android needs explicit close. if (!url) return; event.waitUntil( clients.matchAll({type: 'window'}).then( windowClients => { // Check if there is already a window/tab open with the target URL for (var i = 0; i < windowClients.length; i++) { var client = windowClients[i]; // If so, just focus it. if (client.url === url && 'focus' in client) { return client.focus(); } } // If not, then open the target URL in a new window/tab. if (clients.openWindow) { return clients.openWindow(url); } }) ); }); self.addEventListener('message', function (event) { // A message has been sent to this service worker. console.log("sw Handling message event:", event); }); self.addEventListener('pushsubscriptionchange', function (event) { // The Push subscription ID has changed. The App should send this // information back to the App Server. console.log("sw Push Subscription Change", event); event.waitUntil( self.clients.matchAll() .then(clientList => { let sent = false; console.debug("Service worker found clients", JSON.stringify(clients)); clientList.forEach(client => { console.debug("Service worker sending to client...", client); sent = true; client.postMessage({'type': 'update'}); }); if (sent == false) { throw new Error("No valid client to send to."); } }) .catch(err => { console.error("Service worker couldn't send message: ", err); }) ); }); in footer.php <script> if (!Notification) { console.log('*Browser does not support Web Notification'); } if ('serviceWorker' in navigator) { // Register a service worker hosted at the root of the // site using the default scope. navigator.serviceWorker.register('service-worker.js', { scope: './' }).then(function(registration) { console.log('Service worker registration succeeded:', registration); }, /*catch*/ function(error) { console.log('Service worker registration failed:', error); }); } else { console.log('Service workers are not supported.'); } navigator.serviceWorker.ready.then((reg) => { const subscribeOptions = { userVisibleOnly: true, applicationServerKey: 'xyz.......' }; reg.pushManager.subscribe(subscribeOptions).then((subscription) => { // Send subscription to server fetch('save_subscription.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(subscription) }).then((response) => { if (response.ok) { console.log('Subscription saved successfully.'); } else { console.error('Failed to save subscription.'); } }); }).catch((error) => { console.error('Failed to subscribe:', error); }); }); </script> Push notification i am using Web-push-php from git. Everything is working fine but i want to keep pwa logged in until i manually logs out. Quote Link to comment https://forums.phpfreaks.com/topic/326505-keep-logged-in-php-pwa-after-installation/ Share on other sites More sharing options...
Moorcam Posted January 13 Share Posted January 13 The provided code does not include any session management, which results in users being logged out upon closing the application. To keep users logged in until they manually log out, you can implement a session management strategy using cookies or local storage. Quote Link to comment https://forums.phpfreaks.com/topic/326505-keep-logged-in-php-pwa-after-installation/#findComment-1647883 Share on other sites More sharing options...
mythri Posted January 13 Author Share Posted January 13 in my login.php i set session like this ini_set('session.gc_maxlifetime', 315360000); session_set_cookie_params(315360000); session_start(); and in session.php, which includes in all the pages include('Connection.php'); if((isset($_SESSION['uid']))) { if (!empty($_SERVER['HTTPS'])) { define('RootPath', 'https://mywebsite'); } else { define('RootPath', 'http://mywebsite'); } $stmt = $con->prepare("SELECT * FROM users"); $stmt->execute(); $user = $stmt->fetch(); $_SESSION['name'] = $user['fname'].' '.$user['lname']; $_SESSION['fname'] = $user['fname']; $_SESSION['type'] = $user['type']; $_SESSION['Path'] = RootPath; } else if(!isset($_SESSION['uid'])) { header("location:index.php"); exit(); } ?> do i need to include this file in service-worker.js? Quote Link to comment https://forums.phpfreaks.com/topic/326505-keep-logged-in-php-pwa-after-installation/#findComment-1647889 Share on other sites More sharing options...
Moorcam Posted January 14 Share Posted January 14 11 hours ago, mythri said: in my login.php i set session like this ini_set('session.gc_maxlifetime', 315360000); session_set_cookie_params(315360000); session_start(); and in session.php, which includes in all the pages include('Connection.php'); if((isset($_SESSION['uid']))) { if (!empty($_SERVER['HTTPS'])) { define('RootPath', 'https://mywebsite'); } else { define('RootPath', 'http://mywebsite'); } $stmt = $con->prepare("SELECT * FROM users"); $stmt->execute(); $user = $stmt->fetch(); $_SESSION['name'] = $user['fname'].' '.$user['lname']; $_SESSION['fname'] = $user['fname']; $_SESSION['type'] = $user['type']; $_SESSION['Path'] = RootPath; } else if(!isset($_SESSION['uid'])) { header("location:index.php"); exit(); } ?> do i need to include this file in service-worker.js? The session parameters are set to a very high value (315360000 seconds, which is approximately 10 years). While this is not inherently a bug, it may lead to unexpected behaviour if not managed properly, especially in terms of security and session expiration. The code includes a file named Connection.php, but there is no error handling to check if the connection was successful. If the connection fails, the subsequent database operations will not work. The code checks if the session variable uid is set, but it does not handle the case where the session is not set, which could lead to unexpected behaviour. Quote Link to comment https://forums.phpfreaks.com/topic/326505-keep-logged-in-php-pwa-after-installation/#findComment-1647907 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.