Jump to content
  • Who's Online   0 Members, 1 Anonymous, 98 Guests (See full list)

    • There are no registered users currently online

All Activity

This stream auto-updates

  1. Today
  2. 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.
  3. Yesterday
  4. Most people use Cloudflare for the proxy and edge caching. DNS registration is a commodity. There are plenty of other registrars like Cheapdomains you could look at purely for DNS registration. You can always make a free Cloudflare account and explore their offerings. They provide a lot of useful features in their free account.
  5. Never mind. Reapplied the logic and resolved the issue.
  6. Last week
  7. It seemed like a simple idea for a snowy day, but now I've lost my way in the forest. The plan: I have a landing page that will connect to either page 1, 2, or 3. These pages all flow to page A. On page A, I decided (big mistake) to say "I hope you enjoyed visiting our page X." My idea was to create a $_SESSION['page] variable in each of pages 1,2,3 and provide the appropriate value accordingly. When a user why to page A, the variable would follow and populate the sentence çorrectly. If they went to page A directly or from the landing page, the variable would be blank bc there is no session value associated. My first steps seemed to be okay, but then I couldn't clear the session from the landing page. Is my implementation completely off?
  8. I have some top level domains (50+ domains) and am still using godaddy. And the godaddy's recent renewal prices are like 22-24 US dollars which is quite high. So I'm planning to transfer all my domains to cloudflare (yes I know DNS can not be changed which will not be a problem for me since I have dedicated hosting (static ip) and using cloudflare's DNS too) I guess the renewal prices there are cheaper in cloudflare. So I have two questions; 1) For the cloudflare users (for domain registration), are you happy with it? How much is the renewal fee? Would it be reasonable to transfer all my domains there? 2) If I have transferred all my domains to cloudflare and after some years I didn't like it, is it possible to transfer all my domains to another registrar like porkbun etc? Thanks in advance
  9. First and foremost, the mysql_* functions were removed from PHP quite some time ago. Look into PDO for all your database needs. That having been said, a lot of old code still exists on the internet, so don't blindly copy and paste. The good aspect of the code you're using is that it's using PHPMailer instead of php's native mail function. Not to be rude, but the rest of it is dusty and shouldn't be used.
  10. I use the `Intervention` library as it make handling images easier. Here's how to rotate an image use Intervention\Image\ImageManager; $image = (new ImageManager())->make('public/image.jpg')->rotate(45)->save('public/rotated_image.jpg'); and here's an upload script from my website that might help? <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/clearwebconfig.php'; require_once "vendor/autoload.php"; use Intervention\Image\ImageManagerStatic as Image; // Import the ErrorHandler and Database classes from the clearwebconcepts namespace. use clearwebconcepts\{ ErrorHandler, Database, ImageContentManager, LoginRepository as Login }; $errorHandler = new ErrorHandler(); // Register the exception handler method set_exception_handler([$errorHandler, 'handleException']); $database = new Database(); $pdo = $database->createPDO(); $checkStatus = new Login($pdo); // To check for either 'member' or 'sysop' if ($checkStatus->check_security_level(['sysop'])) { // Grant access } else { // Access denied header('location: dashboard.php'); exit(); } function is_ajax_request(): bool { return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'; } $save_result = false; if (($_SERVER['REQUEST_METHOD'] === 'POST') && isset($_FILES['image'])) { $data = $_POST['cms']; $data['content'] = trim($data['content']); $errors = array(); $exif_data = []; $file_name = $_FILES['image']['name']; // Temporary file: $file_size = $_FILES['image']['size']; $file_tmp = $_FILES['image']['tmp_name']; $thumb_tmp = $_FILES['image']['tmp_name']; $file_type = $_FILES['image']['type']; $file_ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION)); /* * Set EXIF data info of image for database table that is * if it contains the info otherwise set to null. */ if ($file_ext === 'jpeg' || $file_ext === 'jpg') { $exif_data = exif_read_data($file_tmp); if (array_key_exists('Make', $exif_data) && array_key_exists('Model', $exif_data)) { $data['Model'] = $exif_data['Make'] . ' ' . $exif_data['Model']; } if (array_key_exists('ExposureTime', $exif_data)) { $data['ExposureTime'] = $exif_data['ExposureTime'] . "s"; } if (array_key_exists('ApertureFNumber', $exif_data['COMPUTED'])) { $data['Aperture'] = $exif_data['COMPUTED']['ApertureFNumber']; } if (array_key_exists('ISOSpeedRatings', $exif_data)) { $data['ISO'] = "ISO " . $exif_data['ISOSpeedRatings']; } if (array_key_exists('FocalLengthIn35mmFilm', $exif_data)) { $data['FocalLength'] = $exif_data['FocalLengthIn35mmFilm'] . "mm"; } } else { $data['Model'] = null; $data['ExposureTime'] = null; $data['Aperture'] = null; $data['ISO'] = null; $data['FocalLength'] = null; } $data['content'] = trim($data['content']); $extensions = array("jpeg", "jpg", "png"); if (in_array($file_ext, $extensions, true) === false) { $errors[] = "extension not allowed, please choose a JPEG or PNG file."; } if ($file_size >= 58720256) { $errors[] = 'File size must be less than or equal to 42 MB'; } /* * Create unique name for image. */ $image_random_string = bin2hex(random_bytes(16)); $image_path = 'assets/image_path/img-entry-' . $image_random_string . '-2048x1365' . '.' . $file_ext; $thumb_path = 'assets/thumb_path/thumb-entry-' . $image_random_string . '-600x400' . '.' . $file_ext; move_uploaded_file($file_tmp, $image_path); move_uploaded_file($thumb_tmp, $thumb_path); // Load the image $image = Image::make($image_path); // Resize the image $image->resize(2048, 1365, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); // Save the new image $image->save($image_path, 100); // Load the image with Intervention Image $image = Image::make($image_path); // Resize the image while maintaining the aspect ratio $image->resize(600, 400, function ($constraint) { $constraint->aspectRatio(); $constraint->upsize(); }); // Save the thumbnail $image->save($thumb_path, 100); $data['image_path'] = $image_path; $data['thumb_path'] = $thumb_path; /* * If no errors save ALL the information to the * database table. */ if (empty($errors) === true) { // Save to Database Table CMS $timezone = new DateTimeZone('America/Detroit'); // Use your timezone here $today = new DateTime('now', $timezone); $data['date_updated'] = $data['date_added'] = $today->format("Y-m-d H:i:s"); $cms = new ImageContentManager($pdo, $data); $result = $cms->create(); if ($result) { header('Content-Type: application/json'); echo json_encode(['status' => 'success']); exit(); } } else { if (is_ajax_request()) { // Send a JSON response with errors for AJAX requests header('Content-Type: application/json'); echo json_encode(['status' => 'error', 'errors' => $errors]); } } }
  11. Please edit your post and put your code using the code icon in the menu above (<>). It formats the the code properly making it easier to read and remove all the excess spaces.
  12. After the customer fills the form, the form data is sent to mysql and an email gets sent to me with the last form data that the customer submitted. But, the email "last mysql data" is not going as inline text. Please help me. Sample code is given below. <?php define('DB_NAME', 'XXXXXXX'); define('DB_USER', 'XXXXXXX'); define('DB_PASSWORD', 'XXXXXXX'); define('DB_HOST', 'localhost'); $link = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD); if (!$link) { die('Could not connect: ' . mysql_error()); } $db_selected = mysql_select_db(DB_NAME, $link); if (!$db_selected) { die('Can\'t use ' . DB_NAME . ': ' . mysql_error()); } //Start Posting the data in Mysql database from Form Input $value = $_POST['input1']; $value2 = $_POST['MAmount']; $sql = "INSERT INTO demo (input1, MAmount) VALUES ('$value', '$value2')"; if (!mysql_query($sql)) { die('Error: ' . mysql_error()); } //start print the database $data = mysql_query("SELECT * FROM demo ORDER BY ID DESC LIMIT 1") or die(mysql_error()); Print "<table border cellpadding=3>"; while($info = mysql_fetch_array( $data )) { Print "<tr>"; Print "<th>ID:</th> <td>".$info['ID'] . "</td> "; Print "<th>Input1:</th> <td>".$info['input1'] . "</td> "; Print "<th>MAmount:</th> <td>".$info['MAmount'] . " </td></tr>"; } Print "</table>"; mysql_close(); //end print the database on form processing page //start emailing the data date_default_timezone_set('Asia/Kolkata'); require_once('class.phpmailer.php'); //include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded $mail = new PHPMailer(); //$body = "gdssdh"; //$body = preg_replace("[\]",'',$body); $mail->IsSMTP(); // telling the class to use SMTP $mail->Host = "ssl://XXXXXXX.XXXXXXX.org"; // SMTP server $mail->SMTPDebug = 1; // enables SMTP debug information (for testing) // 1 = errors and messages // 2 = messages only $mail->SMTPAuth = true; // enable SMTP authentication $mail->SMTPSecure = "ssl"; // sets the prefix to the servier $mail->Host = " https://www.astaguru.com/ "; // sets GMAIL as the SMTP server $mail->Port = 465; // set the SMTP port for the GMAIL server $mail->Username = "XXXXXXX.com"; // GMAIL username $mail->Password = "XXXXXXX"; // GMAIL password $mail->SetFrom('[email protected]', 'HAL'); //$mail->AddReplyTo("XXXXXXX', 'First Last"); $mail->Subject = "XXXXXXX"; //THE PROBLEM IS HERE WHEN I WANT TO SEND THE DATA AS INLINE TEXT TO EMAIL FROM MYSQL IT IS NOT WORKING. ONLY "PRINT THE DATA" IS SENDING TO EMAIL. $body = 'Print the data'; mysql_connect("localhost","XXXXXXX","XXXXXXX"); @mysql_select_db("XXXXXXX"); $query["SELECT * FROM demo ORDER BY ID DESC LIMIT 1"]; $result = mysql_query($query); //while ($row = mysql_fetch_array ($result)) { // $mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test $mail->MsgHTML($body); $address = "XXXXXXX"; $mail->AddAddress($address, "user2"); //$mail->AddAttachment("images/phpmailer.gif"); // attachment //$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment if(!$mail->Send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } ?>
  13. When I use high resolution image (5712X4284) and resize using this function for very lower size (136x136). I rotates image to 180 degree. Any solution for it ?
  14. It does sound like mac_gyver had the solution. I'm going to assume that your solution was something like: "SELECT * FROM descriptions WHERE `item` IN ('rolls', 'baguettes', 'croissant')". You should have an index on the 'item' column as well, if you don't. I'm a stickler for data consistency, and perhaps this was just an arbitrary example you created, but if you are going to use plurals (rolls, baguettes) then all of these should be pluralized, and you shouldn't have singulars like 'croissant' or 'donut'. My main comment, is that there is no benefit to using LIKE unless you are using wildcards. LIKE works fine when you actually need it as in: WHERE name LIKE "sm%" finding "Smith", "Smith Jr." and "Smeely", etc. If however, you attempt to find a substring as in: WHERE address LIKE "%main$" This defeats the ability of the database to use indexing. The queries will work, but assuming this is the primary criteria, will need to tablescan the entire table looking for addresses that have 'main' somewhere in them. If the dataset is relatively small, these types of "% ... %" or "% ..." queries are acceptable, but if the dataset is large, you may find you are having significant issues.
  15. This is typically where a pub-sub solution helps. As you mentioned, the old school ways of hacking ajax to do this involved polling. Websockets were introduced to provide a better solution, but have the downsides of being an entirely different protocol, requiring a websocket server. Some people get somewhat around this by utilizing a websocket PAAS, at least for me, the best known of which is Pusher. When I last utilized it, the economics were very reasonable, and for a site with known relatively low traffic there's a free tier. There are alternatives, but if you really need bi-directional communication, websockets are the best solution. If however, this is simply a "push" requirement to "publish" to the "subscribers" then there is now a standard feature you can use known as "server sent events (SSE)". Support for this is very good at this juncture as you can see here: https://caniuse.com/eventsource SSE sounds tailor made to solve your problem here, as your updates can be pushed out to all your clients. Here's the MDN page for the feature. I know of a few php libraries that that have all the serverside plumbing taken care of: https://github.com/hhxsv5/php-sse https://github.com/clue/php-sse-react I will caution that there is no free lunch. SSE's are better than (long) polled ajax, but they still require a dedicated socket connection per client. Anything like this requires significantly more resources, but if it is an essential feature of your application, SSE could be tailor made for what you want, although you should also evaluate using Pusher as an alternative.
  16. I have done a bit of research on this and i fear the answer is no... but is it possible to update a page on a node/express application without needing to look at websockets socket.io? It feels like such a standard thing to want to do but my research is saying that it is not possible. An example is: In my application, i hit an API and display stuff on the page. I just want to hit the api externally and update stuff on the page. I know i can use polling, but i have always turned my nose up at that - feels very brute force. Any pointers here would be lovely. Thanks All
  17. Not a lot. "It doesn't work" tells us nothing. What is ir doing that it shouldn't or what is it not doing that it should? If element_5 contains a price, why not call it "price". Same goes for element_6 (option_id). I can't see what do_query() is doing but as you're passing an array of parameters I assume you are trying to use a prepared statement - but you have no placeholders in the query string for those parameters. If $filter_keyword contains a column name that could be the cause - you can only pass values as parameter. If any of your joins match more than 1 row in any of the tables, the resultant sum would be multiplied by the number of rows. If you need more help, a dump of the structures and data for those tables would enable me to recreate the problem at my end a get you a working query.
  18. Hello all I have 3 tables to join but only want to sum one column from one table my tables are forms, filters, and options the column i want to sum is in the forms table and is named element_5 the column in the filter table is filter_keyword and the column in the options table is option_id so element_5 in the forms table is a price. I have a filter to choose what I want to see, ie, service type, truck used, date, and a few others that populate the filter table when I apply the filter. then I just want to sum the price for that filter. Making any sense? let me know here is the code im trying, but it doesn't work $query = "SELECT * from form_10556 INNER JOIN element_options ON form_10556.element_6 = element_options.option_id INNER JOIN form_filters ON element_options.option_id = form_filters.filter_keyword"; $params = array($element_5,$element_6,$option_id,$filter_keyword); $sth = do_query($query,$params,$dbh); while ($row = do_fetch_result($sth)) { $totalPrice += $row['element_5']; }
  19. Going on what mac_gyver said, which is spot on, First, you need to define the roles that your application will support. For example, you might have roles like admin, editor, and viewer. $roles = [ 'admin' => ['create', 'edit', 'delete', 'view'], 'editor' => ['edit', 'view'], 'viewer' => ['view'] ]; Next, you will need to assign these roles to your users. This can be done in your database. For simplicity, let's assume you have a user array that includes their role. $users = [ 'user1' => ['role' => 'admin'], 'user2' => ['role' => 'editor'], 'user3' => ['role' => 'viewer'] ]; Before allowing access to a specific page or functionality, you should check if the user has the required permissions based on their role. Here’s a simple function to check permissions: function hasPermission($userRole, $action) { global $roles; return in_array($action, $roles[$userRole]); } Now, you can use the hasPermission function to control access to different parts of your application. For example: session_start(); $currentUser = $_SESSION['user_id']; // Assume the user_id is stored in session $userRole = $users[$currentUser]['role']; if (hasPermission($userRole, 'edit')) { // Allow access to edit functionality echo "You have access to edit."; } else { // Deny access echo "Access denied. You do not have permission to edit."; } Hope this makes sense and may help you somewhat.
  20. Thank you much appreciated
  21. You need to unserialise the data. $dbdata = 'a:5:{s:16:"WPFormsDB_status";s:6:"unread";s:4:"Name";s:13:"Lional Hewitt";s:14:"Contact Number";s:10:"0763229844";s:5:"Email";s:22:"[email protected]";s:18:"Comment or Message";s:5:"test2";}'; $data = unserialize($dbdata); echo "Name : {$data['Name']}<br>"; echo "Contact : {$data['Contact Number']}<br>"; // etc Alternatively $dbdata = 'a:5:{s:16:"WPFormsDB_status";s:6:"unread";s:4:"Name";s:13:"Lional Hewitt";s:14:"Contact Number";s:10:"0763229844";s:5:"Email";s:22:"[email protected]";s:18:"Comment or Message";s:5:"test2";}'; $data = unserialize($dbdata); foreach ($data as $key => $value) { echo "<b>$key</b> : $value<br>"; }
  22. Hi I have this entry in a database from wpforms a:5:{s:16:"WPFormsDB_status";s:6:"unread";s:4:"Name";s:13:"Lional Hewitt";s:14:"Contact Number";s:10:"0763229844";s:5:"Email";s:22:"[email protected]";s:18:"Comment or Message";s:5:"test2";} From this I want to extract Lional Hewitt, 0763229844, [email protected], and test2 into separate variables. I see each form is referenced by s:13, s:10, s:22, and s:18. Is there someway to splat the string with those values Thank you
  23. I have no idea, insufficient information. You need to show the code that executes that query and checks for the number of rows returned
  24. Not sure if PHP or SQL problem. Why does my $query = "SELECT * FROM `HAusers` "; give me a record read count of minus 1 when I have 24 records in the BD Table? There are no error messages.
  25. I am trying to use ChatGPT as the chatbot for my Magento 2 website, and I want to pass product data to it. To do this, I collected all the products and stored them in a JSON file, which I then read to embed the data in the `systemRoleContent` of the system role. However, the issue I am facing is that the JSON file is quite large. { "bot_response": "Error: ChatBot Error: Unexpected API response structure: {\n \"error\": {\n \"message\": \"Request too large for gpt-4o on tokens per min (TPM): Limit 30000, Requested 501140. The input or output tokens must be reduced in order to run successfully. Visit https://platform.openai.com/account/rate-limits to learn more.\",\n \"type\": \"tokens\",\n \"param\": null,\n \"code\": \"rate_limit_exceeded\"\n }\n}\n" } I noticed that there is a function that needs to be added to the API configuration, which allows you to run a query to select products based on keywords found in their names or descriptions that match keywords in the user’s message. The challenge is that users initially may not know the names of the products; they come to the chatbot to discover them. How can I address this issue? This is the code that I am working with right now: <?php namespace MetaCares\Chatbot\Model; use Magento\Framework\App\ObjectManager; class ChatBot { private $authorization; private $endpoint; private $conversationHistory = []; private $productsFile; private $fetchingDateFile; private $didFetchProducts = false; public function __construct() { $this->authorization = 'sk-proj-'; $this->endpoint = 'https://api.openai.com/v1/chat/completions'; $this->productsFile = __DIR__ . '/products.json'; $this->fetchingDateFile = __DIR__ . '/fetching_date.json'; $currentTime = time(); $timeDifferenceSeconds = 24 * 3600; if (!file_exists($this->fetchingDateFile)) { file_put_contents($this->fetchingDateFile, json_encode(['last_fetch_time' => 0])); } $fetchingData = json_decode(file_get_contents($this->fetchingDateFile), true); $lastFetchTime = $fetchingData['last_fetch_time'] ?? 0; if ($currentTime - $lastFetchTime > $timeDifferenceSeconds) { $products = $this->fetchProductsUsingModel(); $productsJson = json_encode($products); file_put_contents($this->productsFile, $productsJson); $fetchingData['last_fetch_time'] = $currentTime; file_put_contents($this->fetchingDateFile, json_encode($fetchingData)); $this->didFetchProducts = true; } $jsonSampleData = file_get_contents($this->productsFile); $systemRoleContent = <<<EOT Nom: Meta Cares Bot Description BOT Meta Cares répond aux questions sur les produits du site et fournit des conseils santé fiables. Tu aides les clients de Meta Cares à faire des choix éclairés tout en offrant un accompagnement personnalisé, sécurisé et adapté à leurs besoins. catalogue Meta Cares {$jsonSampleData} Liste des Sites Référencés : - PubMed : [https://pubmed.ncbi.nlm.nih.gov/](https://pubmed.ncbi.nlm.nih.gov/) - ScienceDirect : [https://www.sciencedirect.com/](https://www.sciencedirect.com/) --- - Génération d’images DALL·E : Désactivée EOT; $this->conversationHistory[] = [ 'role' => 'system', 'content' => $systemRoleContent ]; if (session_status() == PHP_SESSION_NONE) { session_start(); } if (isset($_SESSION['chat_history'])) { $this->conversationHistory = $_SESSION['chat_history']; } } public function fetchProductsUsingModel(): array { return $products; } private function getCategoryNames(array $categoryIds): array { return $categoryNames; } public function sendMessage(string $message): array { try { $this->conversationHistory[] = [ 'role' => 'user', 'content' => $message ]; $data = [ 'model' => 'gpt-4o', 'messages' => array_map(function ($msg) { return [ 'role' => $msg['role'] === 'bot' ? 'assistant' : $msg['role'], 'content' => $msg['content'] ]; }, $this->conversationHistory) ]; $response = $this->makeApiRequest($data); $arrResult = json_decode($response, true); if (json_last_error() !== JSON_ERROR_NONE) { throw new \Exception('Invalid API response format'); } if (!isset($arrResult['choices']) || !isset($arrResult['choices'][0]['message']['content'])) { throw new \Exception('Unexpected API response structure: ' . $response); } $assistantResponse = $arrResult['choices'][0]['message']['content']; $this->conversationHistory[] = [ 'role' => 'bot', 'content' => $assistantResponse ]; $_SESSION['chat_history'] = $this->conversationHistory; return [ "conversationHistory" => $_SESSION['chat_history'], 'didFetchProducts' => $this->didFetchProducts, 'response' => $assistantResponse, ]; } catch (\Exception $e) { throw new \Exception('ChatBot Error: ' . $e->getMessage()); } } private function makeApiRequest(array $data): string { $ch = curl_init(); curl_setopt_array($ch, [ CURLOPT_URL => $this->endpoint, CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($data), CURLOPT_HTTPHEADER => [ 'Content-Type: application/json', 'Authorization: Bearer ' . $this->authorization, ], CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => 0 ]); $response = curl_exec($ch); if (curl_errno($ch)) { $error = curl_error($ch); curl_close($ch); throw new \Exception('API request failed: ' . $error); } curl_close($ch); return $response; } }
  26. Earlier
  27. the only user data you should store in a session variable upon login should be the user id, to identify WHO the logged in user is. this will either be set or it won't be. you should query on each page request to get any other user data, such as a username, permissions, or role. this is so that any changes made to this other user data takes effect on the very next page request. this will allow you to promote or demote a user without requiring them to logout and back in for the change to take effect. do you really want a situation where you have demoted or banned a user and they can still access a page because their session data says they can? i recommend that you simplify the logic and separate the login test from the user role test. also, to test if a variable is in a set of values, define an array of the permitted values and use in_array() to perform the test. using these suggestions, the logic would become - $page_roles = ['Member','Secretary']; // roles permitted for the current page $user_role = 'Guest'; // default value for a non-logged in user // is there a logged in user if(isset($_SESSION['user_id'])) { // query here to get any other user data, such as the user role, and store it in a regular variable // fake a value $user_role = 'Member'; // $user_role = 'Secretary'; // $user_role = 'Other'; } // logic to determine if the current user can access something on this page if(in_array($user_role,$page_roles)) { // access permitted echo 'permitted'; } // logic to determine if the current user cannot access something on this page if(!in_array($user_role,$page_roles)) { // access denied echo 'denied'; }
  28. Think I just solved it by changing a line to the following if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member' && $_SESSION["account_role"] != 'Secretary') {
  29. I have two different user roles, one is Member and the other is Secretary and I need to be able to allow access to a php page if either Member or Secretary is logged in. I originally had the code below which worked if a Member role was logged in <?php session_start(); // If the user is not logged in redirect to the login page... if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member') { include('includes/baseurl.php'); $title = "Show Diary - The British Rabbit Council"; $pgDesc=""; include ( 'includes/header.php' ); ?> I added the Secretary role to the code but it won't allow me to access the page, I think it's because I'm not logged in as a Member role and am logging as the Secretary role but I need access to the php page if I am logged in as either Member or Secretary The current code I have is below <?php session_start(); // If the user is not logged in redirect to the login page... if(!isset($_SESSION["account_loggedin"]) || $_SESSION["account_loggedin"] !== true || $_SESSION["account_role"] != 'Member' || $_SESSION["account_role"] != 'Secretary') { include('includes/baseurl.php'); $title = "Show Diary - The British Rabbit Council"; $pgDesc=""; include ( 'includes/header.php' ); ?> Can anyone help please, thank you in advance
  1. Load more activity
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.