Leaderboard
Popular Content
Showing content with the highest reputation since 07/13/2025 in all areas
-
One thing that might be helpful is to use the declare to wrap the block of code you want to have evaluated for statement processing. $count = 0; function statements() { global $count; $count++; echo "Statement Count: $count\n"; } register_tick_function('statements'); declare(ticks=5) { for ($x = 0; $x < 10; $x++) { echo "\$x = $x \n"; } } And you get: $x = 0 $x = 1 $x = 2 $x = 3 $x = 4 Statement Count: 1 $x = 5 $x = 6 $x = 7 $x = 8 $x = 9 Statement Count: 22 points
-
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.1 point
-
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.php1 point
-
you are using ajax to load the content into the sections. what you are seeing is whatever /ajax/latest_news.php returns.1 point
-
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.1 point
-
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.1 point
-
Right, so the error is telling you that the CA is untrusted. Aside from that, you should not be using the same cert for the client and the server. You need to generate a client cert for the client, and the CN's for each cert should be different. The MySQL manual has a walk through of process: https://dev.mysql.com/doc/refman/5.7/en/creating-ssl-files-using-openssl.html1 point
-
browses cache content by default. on your development system, you must tell the browser to not cache the content of file types that you will be changing often during the development process. your web server likely/should already have a setting that outputs headers for .php files that tell the browser to not cache the content for the request. you need to add the .js and possibly .css/.html file extensions to this. for an apache web server, there would be an entry in the .htaccess file that looks like - <IfModule mod_headers.c> <FilesMatch "\.(php|js|css|html)$"> Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0" Header set Pragma "no-cache" </FilesMatch> </IfModule>1 point
-
It appears that writing PHP event handlers is simple and works well, and people have been using fullcalendar with PHP for some years now without issue. It's a fairly standard approach to wiring together js UI with PHP backend. Hopefully it's clear that you send and receive data in json format.1 point
-
Thanks... it worked! One thing that needed to be changed was the, '$headers 'From:..... the 'From' was not, obviously, part of the email address.1 point
-
If you have specific refactoring questions or want some advice, consider making new threads. The community here is full of experienced professional developers who are generous with their time and knowledge.1 point
-
Thank-You I think , I shall re-build , into many pages :~/ Might take me sometime :~? But what you have said makes sense :~) So Thank-You Best Regards Sid1 point
-
The validation fails because the file containing the validation logic is never executed when the form is submitted. The standard and most effective solution is to handle everything in one file. The form page should be responsible for: Displaying the form. Receiving the submitted data. Validating the data. If invalid, re-displaying the form with errors. If valid, performing the final action (like sending an email). You just need to move the email-sending logic from form.php into the else block of your validation file. Here is the corrected and combined code. You can replace the entire contents of your first file with this. You will no longer need form.php at all. <?php // 1. SETUP $user = ['name' => '', 'age' => '']; $errors = ['name' => '', 'age' => '']; $message = ''; $form_submitted_successfully = false; // A flag to know when to hide the form // 2. PROCESS FORM IF SUBMITTED if ($_SERVER['REQUEST_METHOD'] == 'POST') { // Validation filters $validation_filters['name']['filter'] = FILTER_VALIDATE_REGEXP; $validation_filters['name']['options']['regexp'] = '/^[A-z]{2,10}$/'; $validation_filters['age']['filter'] = FILTER_VALIDATE_INT; $validation_filters['age']['options']['min_range'] = 16; $validation_filters['age']['options']['max_range'] = 65; $user_input = filter_input_array(INPUT_POST, $validation_filters); // Create error messages $errors['name'] = $user_input['name'] ? '' : 'Name must be 2-10 letters using A-z'; $errors['age'] = $user_input['age'] ? '' : 'You must be between 16 and 65'; // Sanitize the original POST data to redisplay it safely in the form $user['name'] = filter_var($_POST['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); $user['age'] = filter_var($_POST['age'], FILTER_SANITIZE_NUMBER_INT); // Check if there are any errors by joining all error messages $invalid = implode($errors); // 3. DECIDE WHAT TO DO NEXT if ($invalid) { // If there are errors, show an error message $message = 'Please correct the following errors:'; } else { // If data is valid, SEND THE EMAIL $to = '[email protected]'; // Use a real email address $subject = 'Contact Form Submission'; $msg = "Name: {$user['name']}\n" . "Age: {$user['age']}\n"; $headers = 'From: [email protected]'; // It's good practice to set a From header // The mail() function returns true on success, false on failure if (mail($to, $subject, $msg, $headers)) { $message = 'Thank you, your data has been sent!'; $form_submitted_successfully = true; // Set flag to true } else { $message = 'Sorry, there was an error sending your message. Please try again later.'; } } } ?> <?php // include 'includes/header.php'; // Assuming you have this file ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Validation Form</title> <style> .error { color: red; font-size: 0.8em; display: block; } body { font-family: sans-serif; } input { margin-bottom: 10px; } form { border: 1px solid #ccc; padding: 20px; max-width: 400px; } .message { padding: 10px; background-color: #e0e0e0; margin-bottom: 15px; } </style> </head> <body> <h1>Contact Us</h1> <?php if ($message): ?> <p class="message"><?= $message ?></p> <?php endif; ?> <?php // Only show the form if it hasn't been submitted successfully if (!$form_submitted_successfully): ?> <form name="form" action="" method="POST"> Name: <input type="text" name="name" value="<?= htmlspecialchars($user['name']) ?>"> <span class="error"><?= $errors['name'] ?></span><br> Age: <input type="text" name="age" value="<?= htmlspecialchars($user['age']) ?>"> <span class="error"><?= $errors['age'] ?></span><br> <input type="submit" value="Submit"> </form> <?php endif; ?> </body> </html>1 point
-
I'd like to add my two cents on this as well. Having a process that automatically logs a user out is a nice to have feature. Ensuring that all service calls check the current status and permissions of the user making a request is a must have feature. You specifically asked about "users when they delete the accounts they're logged into", but that should also include other users that may be logged on who are deleted by a different user. The former would be a fairly trivial task, but the latter would require some type of polling or websocket functionality (as gizmola stated) which, in my opinion, adds unnecessary complexity. If you have all your other value add features then, sure, add that ability. But you would still need to add server-side validation for every request anyway. For an edge case scenario where a user is "deleted" while they are logged in I would be OK with some unhandled errors in the UI as long as I was confident their calls were not being accepted/completed. Not saying there shouldn't be error handling - only that it is not as important as blocking the requests. I would suggest the following: Create a single process/function that validates that a user is "Active" (or whatever that means for your application) and returns the permissions they have (assuming there are distinct permission) Every page load should run that common process. If the user is not active or does not have the requisite permissions for the page being loaded, redirect them to an appropriate error page I assume you have various AJAX driven features. All back-end AJAX calls should call the same common process and if the user is not active or does not have the requisite permissions for the process being called, have the AJAX response return an appropriate error. The client-side implementation will need to check for such errors and react accordingly (I'd redirect to the same error pages as noted above).1 point
-
the code for every page (http request) must enforce what the current user can do or see on that page. if you do what i wrote in one of your recent threads - the code performing the admin actions will find that the current user is either not logged in, doesn't exist, or no longer has a role that allows access to the code on that page and the user will be prevented from performing any action.1 point
-
here are some implementation practices - the form processing code and form should be on the same page. by putting them on separate pages, you are creating a lot of extra code. by only validating one input at a time and not having the form fields 'sticky', you are providing a poor User eXperience (UX). by storing the 'login_attempts' and 'lockout_time' in session variables, a nefarious user/bot can get unlimited new login attempts by simply not propagating the session id cookie between requests. you must store this data persistently on the server in a database table. the only user related value 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 the user data will take effect on the very next page request, without requiring the user to log out and back in again. the way a 'remember me' operation should be implemented is that if the remember me checkbox is checked, at the point of successfully verifying the user's credentials, generate a unique token, store that in a cookie and in a database 'remember me' table that also includes the user id, and the current datatime, for a determining token expiration. on any page request, if the remember me token cookie is set, query to find a matching row in the remember me table. if there is a row and the token is not timed out, use the user id from that row to set the session variable that identifies who the logged in user is. the rest of the code then uses this value in the session variable, just like it was set in the login form processing code. the registration process, unless being performed by an administrator, which your code is not doing, should not include the role. the role should not be something that the user can decide when they register. modern php (8+) uses exceptions for database statement errors by default - connection, query, prepare, and execute. any discrete logic you currently have testing the result of these statements should be removed since it will never get executed upon an error. both the username and email must be unique or you should only use the email and forget about a separate username. the correct way of determining if a unique value already exists in a database table is to define the column(s) as a unique index, just attempt to insert the data, and detect in the exception catch logic for the insert query if a duplicate index error (number) occurred. any form processing code should keep for the form data as a set, in an array variable, then operate on elements in this array variable throughout the rest of the code. i.e. don't write out a line of code copying every $_POST variable to a discrete variable. you need to trim ALL the user supplied inputs, mainly so that you can detect if all white-space characters were entered, before validating the data. you need to use an array to hold user/validation errors, and validate all the inputs at once, storing the errors in the array using the field name as the array index. after the end of the validation logic, if there are no errors (the array will be empty), use the submitted form data. in the login validation logic, all you really care about is that the required inputs are are not empty strings, after being trimmed. by providing additional feedback to a nefarious user/bot, you are helping narrow down the values they need to try.1 point
-
the above line is missing any { }, so the only line of code that gets executed for an is_dir() is the - echo '<strong>'.$directory .'</strong> <br>'; all the rest of the lines get executed regardless of what $directory is. i recommend that you always format your code so that you can see when it is actually doing.1 point
-
if you use a cookie or the session to hold this data, it can be bypassed by simply deleting the cookie or not propagating the cookie or session id cookie between requests. you must store this data persistently on the server, in a database table. next, you are not trying to lock the account, you are preventing login attempts for an account, from a device (client type) and its location (ip). if you actually lock the account, it will allow someone to log out and lock out a legitimate user, by just making a bunch of bad login attempts for an account. once you have stored the data in a database table, on each login attempt, you would query to find if, how many, and how long ago the bad login attempts were for the account, for the device (client type) and its location (ip). If the current time is greater than the time limit you have chosen from the last bad attempt, you would process the login attempt.1 point
-
"Revolution"? lol. It's another Whatever from the tech world. It's not the first fad used to pump up stock prices, and it won't be the last. The current state of glorified autocomplete systems AI contributes just about as much value to the world as The Blockchain does. You remember that whole thing? Wasn't that long ago when The Blockchain was being called a "revolution" too... The next Whatever will happen in a few weeks, or months, or years, and every publicly-traded company will jump on that as fast as they can too. (Make sure you're not still holding onto all of your NVDA when that happens.) And I'm sure that'll bring its own "revolution" too.1 point
-
Understand that this is a completely different problem than the one you asked for. Specifically, this is a great example of the X/Y problem: asking about your solution of "how to restrict window/tab sessions in PHP" as a means of accomplishing "we want to run some performance testing using multiple independent Chrome windows". Chrome is capable of running an instance (of the version installed on the computer) using a specific profile directory. It takes a little more setup since you need to create multiple profile directories, but that can be done mostly automatically with appropriate automation. If you're searching the internet for answers then look in the direction of automated UI testing: that universally involves scripting a browser to perform actions, which is what you want to do.1 point
-
Firefox has an extension called Multi-Account Containers that allows you to basically sandbox each tab and prevent communication. Much like using private windows, but in tabs.1 point
-
PHP can't tell the difference between one tab/window or another. The only option is to restrict all browsing such that the user never even leaves the page at all: by rewriting your site from the ground-up into a single-page application ("SPA"), meaning you're going to set aside a lot of PHP and do the majority of work in Javascript with frameworks like React. And by the way, this is a bad idea.1 point
This leaderboard is set to New York/GMT-04:00