Jump to content

All Activity

This stream auto-updates

  1. Past hour
  2. this is unnecessary and is hiding simple typo mistakes. except for unchecked checkbox/radio fields, all other fields will be set/will exist after a form has been submitted. after you have detected that a post method form has been submitted, these 'always set' fields will be set, regardless of what they contain. you only need check if a field is set for checkbox/radio fields. your post method form processing code should - detect if a post method form was submitted - if($_SERVER['REQUEST_METHOD'] === 'POST'). detect if there is $_POST (or $_FILES) data. there may not be if the total size of the submitted form data is greater than the post_max_size setting. keep the form data as a set in a php array variable, then operate on elements in this array variable throughout the rest of the code. trim all the input data, mainly so that you can detect if all white-space characters were entered. validate all inputs separately, storing user/validation errors in an array using the field name as the array index. after the end of the validation logic, if there are no errors (the array holding the user/validation errors is empty), use the submitted form data. after using the form data, if there are no errors, redirect to the exact same URL of the current page to cause a get request for that page. this will prevent the browser from trying to resubmit the form data should that page get browsed back to or reloaded. if you want to dynamically validate and process form data, and dynamically produce the corresponding form, create an array with the expected form fields, using the field name as the array index, with an array for each field with a label element, field data type, validation rules, and processing rules. you can then loop over this defining array and call general-purpose code to handle each field.
  3. I am getting an Illegal Redirection error trying to redirect to an absolutely valid URL. I can't seem to fix this problem, and I know that there is no whitespace causing this issue to fail. <?php if (!array_key_exists('token', $_SESSION) || !isset($_POST['token']) || is_null($_POST['token']) || $_SESSION['token'] !== $_POST['token']) { $msg = ERROR_MESSAGE . ' tokencheck.php ' . date('Y-m-d H:i:s') . ' Illegal redirection from "' . $_SERVER['HTTP_REFERER'] . '"'; toLogDB($msg); error_log($msg); header('Location: ' . ERROR_FULL_URL); die(); } ?> <?php ini_set('session.gc_maxlifetime', 60 * 10); session_start(); require('./globals/constants.php'); require('./globals/functions.php'); require('./globals/crypto.php'); require('./feedback/includes/constants.php'); require('./feedback/includes/globals.php'); require('./feedback/includes/functions.php'); require('./feedback/includes/delivery.php'); require('./feedback/includes/validation.php'); require('./feedback/includes/tokencheck.php'); // REST OF THE CODE ?>
  4. Sigh. Way too easy and I completely missed it
  5. if (!is_null($elem) || !$isValidName($elem)) { ^ ???
  6. Today
  7. I have no idea why I am getting this error, but I am constantly getting this error when I am trying to do a default set onto $elem based on whether or not $_POST['firstName'] exists or not. Error: Code: $elem = (array_key_exists('firstName', $_POST) && isset($_POST['firstName']) && !is_null($_POST['firstName'])) ? $_POST['firstName'] : ''; if (!is_null($elem) || !$isValidName($elem)) { $isValid = false; array_push($erroredIDArray, 'firstName'); array_push($erroredIDIndexArray, $i); } Entire function: function isValidByCase($isValid, $i) { global $erroredIDArray; global $erroredIDIndexArray; $elem = ''; switch ($i) { case 0: // FIRST NAME $elem = (array_key_exists('firstName', $_POST) && isset($_POST['firstName']) && !is_null($_POST['firstName'])) ? $_POST['firstName'] : ''; if (!is_null($elem) || !$isValidName($elem)) { $isValid = false; array_push($erroredIDArray, 'firstName'); array_push($erroredIDIndexArray, $i); } break; case 1: // LAST NAME $elem = (array_key_exists('lastName', $_POST) && isset($_POST['lastName']) && !is_null($_POST['lastName'])) ? $_POST['lastName'] : ''; if (is_null($elem) || !$isValidName($elem)) { $isValid = false; array_push($erroredIDArray, 'lastName'); array_push($erroredIDIndexArray, $i); } break; case 2: // EMAIL $elem = (array_key_exists('email', $_POST) && isset($_POST['email']) && !is_null($_POST['email'])) ? $_POST['email'] : ''; if (!is_null($elem) || strlen(trim($elem) === 0 || strlen(trim($elem)) > EMAIL_MAX_LENGTH || !$isValidEmail($elem))) { $isValid = false; array_push($erroredIDArray, 'email'); array_push($erroredIDIndexArray, $i); } break; case 3: // SUBJECT $elem = (array_key_exists('subject', $_POST) && isset($_POST['subject']) && !is_null($_POST['subject'])) ? $_POST['subject'] : ''; if (!is_null($elem) || !is_numeric($elem) || !isValidSubject($elem)) { $isValid = false; array_push($erroredIDArray, 'subject'); array_push($erroredIDIndexArray, $i); } break; case 4: // QUESTION $elem = (array_key_exists('question', $_POST) && isset($_POST['question']) && !is_null($_POST['question'])) ? $_POST['question'] : ''; if (!is_null($elem) || !isValidQuestion($elem)) { $isValid = false; array_push($erroredIDArray, 'question'); array_push($erroredIDIndexArray, $i); } break; default: break; } return $isValid; } I am checking for everything I can think of: 1) Is the key in $_POST? 2) Is $_POST[key] set? 3) Is $elem null? 4) Does $elem pass the sniff test in every single individual function which nominally checks for null + emptiness? I don't know what else to do, and the error is persistent. Please help Thanks
  8. While the Ubuntu server is free, it is not freely offered on my GoDaddy production environment for me to use, so I'm having to use what they provide, which, in this case, is IIS. But thanks for letting me know
  9. Yesterday
  10. Totally unsolicited advice here but if you have to choice to move off IIS with php, I highly recommend doing so. While it's true that php can run on IIS, unless MS has made some massive changes since the last time I tried it there are so many tiny little hoops like this you're gonna have to jump through that it's likely to end up counter-productive. Ubuntu server is free, the download is easy to install and maintain, and it's support of php (while admittedly not always the most up-to-date) is quite good.
  11. Solved it; I used too old of a version of encryption/decryption, and the solution was simpler than I thought: <?php /** * Using most recent versions of PHP Sodium functions for PHP 8.3.8. Remember to do the following when requiring this file: * * <b> * require('./globals/constants.php'); * require('./globals/functions.php'); * require('./globals/crypto.php'); * </b> */ function decrypt($encText, $nonce, $key) { try { if (empty($encText) || empty($nonce) || empty($key)) { throw new Exception('You must provide text, a nonce, and a key'); } return sodium_crypto_secretbox_open($encText, $nonce, $key); } catch (Exception $e) { $msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage(); toLogDB($msg); error_log($msg, 0); throw $e; } } function encrypt($text, $nonce, $key) { try { if (empty($text) || empty($nonce) || empty($key)) { throw new Exception('You must provide text, a nonce, and a key'); } return sodium_crypto_secretbox($text, $nonce, $key); } catch (Exception $e) { $msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage(); toLogDB($msg); error_log($msg, 0); throw $e; } } /** * Wrapper for {@see sodium_crypto_secretbox_keygen} */ function getKey() { try { return sodium_crypto_secretbox_keygen(); } catch (Exception $e) { $msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage(); toLogDB($msg); error_log($msg, 0); throw $e; } } /** * Wrapper for {@see random_bytes} */ function getNonce() { try { return random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); } catch (Exception $e) { $msg = ERROR_MESSAGE . ' hasSecCode() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage(); toLogDB($msg); error_log($msg, 0); throw $e; } } ?> <?php require('./globals/constants.php'); require('./globals/functions.php'); require('./globals/crypto.php'); $key = getKey(); $str = 'Lorem ipsum dolor sit amet. The quick brown fox jumped over the lazy dog. Lorem ipsum dolor sit amet'; $nonce = getNonce(); $encStr = encrypt($str, $nonce, $key); $decStr = decrypt($encStr, $nonce, $key); if ($decStr === false) { echo ' was not decrypted<br />'; } ?> <!DOCTYPE html> <html> <head> <title>Blah</title> </head> <body> <p> Original string: <?php echo $str ?><br /><br /> Encrypted string: <?php echo $encStr ?><br /><br /> Decrypted string: <?php echo $decStr ?><br /><br /> </p> </body> </html>
  12. I am trying to learn how to use encryption and decryption using the built-in libsodium.dll module I have for PHP 8.3.8 and IIS 10+, however, I am unable to get it to work; I am getting this error: Here is the code: <?php // PECL libsodium 0.2.1 and newer /** * Found at <a href="https://stackoverflow.com/questions/3422759/php-aes-encrypt-decrypt"> * https://stackoverflow.com/questions/3422759/php-aes-encrypt-decrypt</a> */ /** * Encrypt a message * * @param string $message - message to encrypt * @param string $key - encryption key * @return string */ function safeEncrypt($message, $key) { $nonce = \Sodium\randombytes_buf( \Sodium\CRYPTO_SECRETBOX_NONCEBYTES ); return base64_encode( $nonce. \Sodium\crypto_secretbox( $message, $nonce, $key ) ); } /** * Decrypt a message * * @param string $encrypted - message encrypted with safeEncrypt() * @param string $key - encryption key * @return string */ function safeDecrypt($encrypted, $key) { $decoded = base64_decode($encrypted); $nonce = mb_substr($decoded, 0, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, '8bit'); $ciphertext = mb_substr($decoded, \Sodium\CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit'); return \Sodium\crypto_secretbox_open( $ciphertext, $nonce, $key ); } ?> <?php require('./globals/crypto.php'); $key = \Sodium\random_bytes(\Sodium\CRYPTO_SECRETBOX_KEYBYTES); $str = 'Lorem ipsum dolor sit amet. The quick brown fox jumped over the lazy dog. Lorem ipsum dolor sit amet'; $encStr = safeEncrypt($str, $key); $decStr = safeDecrypt($encStr, $key); ?> <!DOCTYPE html> <html> <head> <title>Blah</title> </head> <body> <p> Original string: <?php echo $str ?><br /><br /> Encrypted string: <?php echo $encStr ?><br /><br /> Decrypted string: <?php echo $decStr ?><br /><br /> </p> </body> </html> What else should I be doing to ensure encryption and decryption works? Thanks
  13. Last week
  14. The general principles involved in mac_gyver's valuable comments to you, when applied to classes, include the idea of dependency injection (aka "inversion of control"). If you consider your function, what are the dependencies? The first thing to look for would be objects you are creating internally using new keyword. In your code that is this line: $conn = new PDO(DB_CONNECTION_STR, MYSQL_DB_USER, MYSQL_DB_PASSWORD, MYSQL_DB_PDO_OPTIONS); Rather than creating objects inside the function, you should pass them as parameters. Objects and resources are automatically passed by reference, so you are able to use the class inside the function without limitation, including calling methods that mutate the object. Here's a short video that explains Dependency Injection further. While Dependency injection is an OOP specific design pattern, the philosophy can still be applied to your functional code in most cases. You won't have a DI Container, but you can work around that as long as you understand the idea. So to begin to address many of the things brought up by mac_gyver, I'd expect your function signature to look more like this: function calculateResults(PDO $conn, Poll $pollObj, Array &$resultsCalcArray) { // implementation } You are also using the $_SESSION superglobal. A strong argument can be made that you should also pass the superglobal into your function, rather than simply relying on it's superglobal property. Most frameworks have their own session wrapping class, but you could simply use a parameter like $session, and pass $_SESSION into your function. One reason to do that, is that you can then create unit tests for your function, which would not be possible normally, because $_SESSION only exists in the web context and doesn't exist in the CLI environment. So an alternative would be to do this: function calculateResults(PDO $conn, Poll $pollObj, Array &$session, Array &$resultsCalcArray) { // implementation //... at some point $session['total'] = $total; } Here's a small test script you should be sure you understand now and in the future: <?php /* Illustrating PHP Function parameters. */ class o { private $v = 0; public function inc() { $this->v++; } public function getV() { return $this->v; } } function testParams(o $obj) { for ($x=0; $x < 10; $x++) { $obj->inc(); } return $obj->getV(); } function testParams2($fp, $text) { $text = "1." . $text . PHP_EOL; fwrite($fp, $text); } // Pass Array by Reference function testParams3(Array &$globArray) { array_push($globArray, 'grape'); } // Globally scoped variables $globArray = ['apple', 'banana', 'peach']; $obj = new o(); $r = fopen("/tmp/resource.txt", "w+"); $text = "This is some text."; // $retVal = testParams($obj); echo $retVal . PHP_EOL; echo $obj->getV() . PHP_EOL; echo PHP_EOL; echo "text before testParams2: \n"; echo "\t$text" . PHP_EOL; testParams2($r, $text); rewind($r); $fileData = fgets($r, 4096); echo "File Data:\n"; echo "\t$fileData"; echo "text After testParams2::\n"; echo "\t$text" . PHP_EOL; echo PHP_EOL; echo "Array Before testParams3:\n"; var_dump($globArray); echo PHP_EOL; testParams3($globArray); echo "Array After testParams3:\n"; var_dump($globArray); I posted it to 3v4l so you could experiment with it if you choose.
  15. the anonymous function has local variable scope, like any php function. you can add use ($total) to the definition to make the variable available inside the function - $resultsCalcArray = array_map(function($votes) use ($total) { as to the posted code - the input call-time parameter should only be the $id and you should only call this function after you have validated the $id. this function should also have an existing pdo connection as an input call-time parameter. it is the wrong responsibility for this function to make a database connection. there's no point is defining and initializing $conn, $stmt, and $rs. don't use the global keyword to get data into or out of a function. this is not general purpose and results in spaghetti code that is hard to debug problems in. all input data to a function should be supplied as call-time parameters and the function should return the result it produces to the calling code. if you set the default fetch mode to assoc when you make the database connection, you won't need to specify it in each fetch statement. fetchAll() won't ever return a null, so the !is_null() test will never fail and should be removed. since you are only operating on the 'kount' column, that is the only thing the query should SELECT. if you have some reason to select other columns, you can build (or add to) the $resultsCalcArray from just the 'kount' column by using array_column(). you can directly get the total of the $resultsCalcArray 'kount' values by using array_sum(). no in-line code after the throw $e; statement will ever get executed and should be removed. there's generally no point in freeing up result sets, closing prepared query handles, or closing database connections in your code, at all, and there's certainly no point in doing this inside a function, since all those things get destroyed when the function call ends.
  16. To include a variable that is defined externally to the map function you need "use()" $calcArray = [ 34, 56, 82 ]; $total = 10; $calcArray = array_map ( function($v) use ($total) { return round($v / $total); }, $calcArray ); echo '<pre>' . print_r($calcArray, 1) . '</pre>'; Alternatively, you can use this syntax... $calcArray = [ 34, 56, 82 ]; $total = 10; $calcArray = array_map ( fn($v) => round($v / $total), $calcArray ); echo '<pre>' . print_r($calcArray, 1) . '</pre>'; See https://www.php.net/manual/en/functions.arrow.php
  17. I am getting the exact same error over and over again, and I have no idea why: Consider the code function calculateResults($pollObj) { $conn = null; $stmt = null; $rs = null; $total = 0; global $resultsCalcArray; try { $pollId = stripHTML(cleanXSS($pollObj->id)); $conn = new PDO(DB_CONNECTION_STR, MYSQL_DB_USER, MYSQL_DB_PASSWORD, MYSQL_DB_PDO_OPTIONS); $stmt = $conn->prepare(RESULTS_SQL); $stmt->execute([$pollId, $pollId, $pollId]); $rs = $stmt->fetchAll(PDO::FETCH_ASSOC); if (!is_null($rs)) { foreach ($rs as $row) { if (!empty($row['kount'])) { $total += (int) $row['kount']; array_push($resultsCalcArray, $row['kount']); } } } $_SESSION['total'] = $total; if ($total > 0) { // TO PREVENT DIVIDE BY ZERO ERROR $resultsCalcArray = array_map(function($votes) { return round($votes / $total) * 100; }, $resultsCalcArray); } } catch (Exception $e) { $msg = ERROR_MESSAGE . ' calculateResults() ' . date('Y-m-d H:i:s') . ' ' . $e->getMessage(); toLogDB($msg); error_log($msg, 0); throw $e; $hasErrors = true; } finally { if (!is_null($rs)) { $rs = null; } if (!is_null($stmt)) { $stmt = null; } if (!is_null($conn)) { $conn = null; } } } I honestly don't know what I did wrong here, but it is completely failing the entire code within the function inside array_map(), and I have no idea why. Help appreciated and needed. Thanks
  18. Earlier
  19. @LeonLatex This is one of the reasons it is highly advisable that you have scripts that are called via ajax, return json data rather than html markup in most cases. It allows you to separate the data from the markup (which remains in the calling script with the rest of the markup). It also makes it much easier to modify and test your application, as you can focus the php script on returning the data in a structured format that the calling site requires, which can be tested easily with api testing tools like Postman. These days many editors have support for these types of tests through plugins like Thunder client
  20. Hi mac_gyver, Thanks again for your help earlier. I just wanted to give you a quick update: the issue is now resolved! As you pointed out, the content in the section was being loaded via AJAX from /ajax/latest_news.php. The problem was that this file was returning unexpected output – specifically, some CSS – instead of the HTML content we intended. To debug it, I added this at the top of latest_news.php: header('Content-Type: text/html; charset=utf-8'); echo '<p>AJAX test: latest_news.php is working</p>'; That confirmed the AJAX request was working and that the file was being loaded correctly. From there, I was able to clean up the file and ensure it returned proper HTML for the frontend to display. Turns out the root cause was that latest_news.php was either misconfigured or returning the wrong content type, which confused the JavaScript handler. Appreciate your guidance – it helped point me in the right direction! Thanks😊🎁👍☕🍪 Best regards, Leon
  21. you are using ajax to load the content into the sections. what you are seeing is whatever /ajax/latest_news.php returns.
  22. Here is a link to the site: Matsnakk so you can se the problem by your self
  23. Hi everyone 👋 I'm running into a strange issue where my CSS styles are being displayed as raw text inside a specific <section> on my site, rather than being properly applied. The affected area is my "Latest News" section, which pulls content dynamically using a PHP foreach loop. Here’s what’s going on: My project structure uses index.php, which includes /inc/main.php. In main.php, I have the section: <section id="latest-news"> <h2>Latest News</h2> <div class="news-thumbnails"> <?php foreach (hentNyheter() as $nyhet): ?> <!-- news card markup --> <?php endforeach; ?> </div> </section> The function hentNyheter() is defined in /db/db.php and returns rows from the news table in MySQL. Each row has columns like id, title, summary, image, published_at. Problem: Instead of rendering styled cards, the CSS itself is being printed as raw text inside the .news-thumbnails area on the front page – almost as if a CSS file was pasted into the page as content. It's appearing in a vertical column inside the section. Things I've confirmed: CSS is loaded via proper <link href="/css/styles.css" rel="stylesheet"> in <head>. I'm not using .css.php files anymore. There is no accidental echo or misplaced <style> inside the HTML section. All variable names used (like $nyhet['title'], $nyhet['summary'], etc.) match the database columns. Function h() is used to escape HTML properly: function h(?string $v): string { return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } ------- Here is the databasetable: -- MySQL dump 10.13 Distrib 8.0.42, for Win64 (x86_64) -- -- Host: sql11.hmg9.webhuset.no Database: 204088_matsnakk -- ------------------------------------------------------ -- Server version 8.0.36 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `news` -- DROP TABLE IF EXISTS `news`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `news` ( `id` int NOT NULL AUTO_INCREMENT, `title` varchar(200) COLLATE utf8mb4_unicode_ci NOT NULL, `slug` varchar(220) COLLATE utf8mb4_unicode_ci NOT NULL, `summary` text COLLATE utf8mb4_unicode_ci, `content` mediumtext COLLATE utf8mb4_unicode_ci, `image` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `published_at` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `slug` (`slug`), KEY `published_at` (`published_at`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `news` -- LOCK TABLES `news` WRITE; /*!40000 ALTER TABLE `news` DISABLE KEYS */; INSERT INTO `news` VALUES (1,'Norsk eplesesong i gang','norsk-eplesesong','Slik bruker du epler i alt fra salater til kaker.','Langt nyhetsinnhold...','news1.jpg','2025-08-06 08:04:35'),(2,'Trend: Fermentering hjemme','fermentering-hjemme','Kimchi og kombucha er i vinden.','Langt nyhetsinnhold...','news2.jpg','2025-08-04 08:04:35'); /*!40000 ALTER TABLE `news` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2025-08-06 18:09:21 ----------------------------------------------- Here is the db.ph database connection: <?php // /db/db.php declare(strict_types=1); $configFile = __DIR__ . '/config.php'; if (is_file($configFile)) { require_once $configFile; } else { // Fallback til miljøvariabler eller feilmelding define('DB_HOST', getenv('DB_HOST') ?: ''); define('DB_NAME', getenv('DB_NAME') ?: ''); define('DB_USER', getenv('DB_USER') ?: ''); define('DB_PASS', getenv('DB_PASS') ?: ''); define('DB_CHARSET', 'utf8mb4'); if (!getenv('DB_HOST')) { die('Mangler /db/config.php. Kjør installasjonen via /install.php.'); } } function db(): PDO { static $pdo = null; if ($pdo instanceof PDO) return $pdo; $dsn = 'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, PDO::MYSQL_ATTR_INIT_COMMAND => "SET sql_mode='STRICT_ALL_TABLES'", ]; try { $pdo = new PDO($dsn, DB_USER, DB_PASS, $options); } catch (PDOException $e) { die('Databasefeil: ' . h($e->getMessage())); } return $pdo; } function hentNyheter(int $limit = 6): array { $pdo = db(); $stmt = $pdo->prepare("SELECT id, title, summary, image, published_at FROM news ORDER BY published_at DESC LIMIT :limit"); $stmt->bindValue(':limit', $limit, PDO::PARAM_INT); $stmt->execute(); return $stmt->fetchAll(); } function h(?string $v): string { return htmlspecialchars((string)$v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); } ------ My suspicion is that either: Something is going wrong in how the loop outputs data (possibly empty or malformed values). I'm accidentally printing something unexpected into the HTML (like a full CSS string from the database?) Or perhaps h() is escaping CSS markup that was accidentally inserted into the wrong database column? Has anyone experienced this behavior before, where CSS appears in-page like raw text rather than being interpreted? Let me know if you'd like to see the full files — I can post excerpts from index.php, main.php, and db.php.
  24. this is apparently the previous related thread - https://forums.phpfreaks.com/topic/321226-pdo-error-on-function-since-a-migration-to-pso at that time, the "Statement.php Lines 14-17" were in a file being included before the session_start() and would never have found the session variable set. i'm going to guess that the "fetch() on null error" was occurring on every page request? you have since moved these lines to statement.php. after reviewing the code you posted previously, if this problem is only occurring occasionally, it is likely due to some auto logout logic, a page auto reload occurring exactly at the point of being logged out, and a timing/race condition in the logic, due to all these session variables. at the risk or repeating myself. the only piece of user related data you should store in a session variable upon successful login is the user id (autoincrement primary index.) you should query on each page request to get any other user data, so that any changes made to this other user data take effect on the very next page request. if you cannot determine the cause of this problem, you will need to post all the current code for statemnt.php, everything being included (you should use require for things your code must have) by statement.php, everything those files are including, and index.php (and everything it includes and everything those files include) since it is involved in the redirects and could be redirecting back to statement.php, less any database credentials or sensitive site information (which should be in a configuration .php file), for anyone here to be able to help.
  25. obviously it is not. you must determine what the non-printing value actually is and find where in your code it's being set to that value. you either have an assignment, instead of a comparison, like i already wrote, or you have some code that's running, such as after a redirect, where you didn't stop php code execution, and it's assigning a value that when echoed is an empty value.
  26. On log in depending on the user the session can only be set to 1 of the 4 valuse. Show, Show+, Database or Total. So if it is set it will have one of them. By default it is set to Show. Also it is stable for quite some time before it errors on an auto refresh. Either way it will contain a valid string.
  27. Now that you've confirmed the string is what you expect (I assume), you need to remove that line. Because it's getting in the way of your script outputting valid JSON.
  28. I'm calling PHP from a webpage and I want to pass the resulting JSON back to the webpage with this $jsonString = json_encode($generationResponse); print_r($jsonString); echo $jsonString; According to print_r($jsonString); the json string is '{"code":200,"msg":"success","data":{"taskId":"91a5c1544dba3ceb0c84f9b96300938c"}}' which is OK and valid JSON. But my webpage gives an error Error generating audio: SyntaxError: Unexpected token 'A', "Array ( "... is not valid JSON Can anybody help me with this
  29. $_SESSION['CounterValue'] may be set, but doesn't contain what you think. either use var_dump() on $view to display what it is or use var_export(), with the 2nd parameter set to true, when you supply it to the StoreData() call to cause it's value (empty string '', null, false, or true) to be used. best guess is you have some code assigning a value to it, using one =, instead of testing the value in it using two == or three ===.
  30. Hi, I am still having problems with a web page. I have talked about this before and nobody could help. I have done more research into this. The webpage Statement.php displays a bank statement within certain dates and how this information is to be displayed using a session variable $_SESSION['CounterValue']. This page gets auto refreshed. I very occasionally get a null error on the function. Uncaught Error: Call to a member function fetch() on null Statement.php Lines 14-17: $View = 'Show'; if (isset($_SESSION['CounterValue'])) $View = $_SESSION['CounterValue']; Statement.php Line 131: $stmt = GetAllData($Date,$View); Session variables do time out but the code should default to = 'Show'. I have been capturing the data before calling the function GetAllData() Data table entries 35, '2025-08-01', '1754065485', '86.1.133.80', '2025-07-31-Show', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36', 'N'), (36, '2025-08-01', '1754079812', '86.1.133.80', '2025-07-31-', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36', 'N'), (37, '2025-08-01', '1754079819', '86.1.133.80', '2025-07-31-Show', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36', 'N'), Entry 36 has '2025-07-31 -' the variable is missing in the call to the function GetAllData. Here is the function in a seperate functions file. Function in separate file function GetAllData($StartDate, $View) { StoreData($StartDate ."-" . $View); // *** Store data to trap this error *** $pdo = connectDB(); if($View == 'Show' or $View == 'Show+' ) { $sqlAllData = "SELECT * FROM Bank_Data WHERE EntryDate > ? AND EntryDate <= DATE_ADD(?, INTERVAL 6 WEEK) ORDER BY EntryDate ASC, Output"; $stmt = $pdo->prepare($sqlAllData); $stmt->execute( [ $StartDate, $StartDate] ); return $stmt; } if($View == 'Total' or $View == 'Database' ) { $sqlAllData = "SELECT * FROM Bank_Data ORDER BY EntryDate ASC, Output"; $stmt = $pdo->prepare($sqlAllData); $stmt->execute(); return $stmt; } } Can anyone find out what is happening to my ($_SESSION['CounterValue'] and why is it not defaulting to $View = 'Show' This is driving me mad now as it has been going on ever since I upgrades this to PDO last year.
  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.