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

    • There are no registered users currently online

All Activity

This stream auto-updates

  1. Past hour
  2. Thank you very much requinix for your quick reply and help. I changed the code to what is shown below and now it works. $sql = "UPDATE missionaries SET missionary=?, active=?, country=?, city=?, state=?, zip=?, street=?, phone=?,email=?, website=?, facebook=?, photo=? WHERE ID=?"; $stmt = $con->prepare($sql); $stmt->bind_param("ssssssssssssi", $missionary,$active,$country,$city,$state,$zip,$street,$phone,$email,$website,$facebook,$photo,$id); I definitely do not to change the ID. The ID input statement is type=hidden so it can't be changed. I thought I had to include it but I now see that I don't have to. This prepared statement programing is all new to me and you have helped me a lot. Thanks again.
  3. Today
  4. @requinix I see your points. Never got interested in Bootstrap primarily bc I didn't understand the reason to use something that was 'secretively' doing something that I could readily do and control. I agree with your points on CSS. I've seen design achievements where the same result was met with CSS as could be with JS (ie: flashing buttons or sliding boxes). Unless there is a compelling reason, I tend to gravitate to the CSS. I think it has something to do with early experiences where JS could be disabled (thereby leaving hours of dedicated design work inoperative) where CSS remains active. It took some research to understand: "I'm betting that Tea was developed through vibe coding..." From a literal perspective, I was conflicted as to whether you were implying that folks abandoned a laborious AI inclusive effort for such a simple task (of making tea) or that it began to take so much time that they required a respite (and made tea). I should have paid more attention to the capitalized T. I suppose it's because I haven't had my morning coffee. *wink*
  5. I'm betting that Tea was developed through vibe coding... 98% of inline CSS is bad and shouldn't be inline CSS, but IMO there are reasonable and not uncommon situations where inline CSS is the "correct" solution: Namely, when an amount of required styling for some element is just so damned specific and unique that it doesn't make sense to hoist it into CSS that exists Somewhere In The Project, and instead tightly coupling it to the element (ie. inline) actually makes understanding and maintaining it easier. Which isn't to say that it could/should never be promoted into a stylesheet, just that there's no apparent call to do so (yet). Off topic, just saying. (Even more off-topic is that Bootstrap is the worst thing to ever happen to the world of front-end development; I could write a VERY lengthy rant about how screwed up standard CSS practices are because of that nonsense.) That's the thing pro-vibe coding people leave out when they evangelize the idea: yeah, sure, the AI spit out a bunch of code much faster than a professional developer could have, but the amount of time spent screwing around with it afterwards because the output sucked offsets those gains by so, so much. As an old-school programmer, I avoid using Javascript for anything that regular HTML/non-Javascript practices can handle. Which means I hate React and its frenemies. But even setting that aside, there really is no good reason in remotely modern web development to be using Javascript to simulate CSS functionality. Back in the 2000s that was necessary because CSS was still young and web designers wanted to do much more than it was capable of (we didn't even have :hover back then), but nowadays CSS is capable of far more than many people give it credit for. Naturally there are still concepts that CSS can't do and that Javascript is required to "polyfill" - UIs will always want to be one step ahead of technology - but if CSS can do a thing then CSS should do the thing. Reasons vary: graceful degradation, requirements for technical know-how, browser performance, single-responsibility principle...
  6. @gizmola Septate playlists that could be reused. The DJ could have one playlist for Rock and Roll audiences, which would be different from the Rap and HipHop list, or the Oldies. There could be individual songs that appear on multiple playlists, but a single playlist could be defined for a given event based on either the event's or organization's target audience.
  7. I believe @requinix was right in his response to my recent Miscellaneous post regarding AI. So here I am, having (regrettably) relied on AI for help in building a webpage. But let me get to my question. The page was built with a pop-up modal that contains a short list of items which AI decided to create in hardcoded HTML with inline CSS. (This wouldn't have been my choice methodology and I tried to get the darn thing to loop through an array but this was ultimately the best working result provided. Ugggh!) Next came the fun part. *sarcasm* I wanted a second modal similar to the first. (For simplicity, think one for boys and the second for girls.) When I asked/told (I'm not quite sure who was 'in charge'... LOL) AI to make a second modal that resembled the first it took a lot of tweaking to reach my goal. Ultimately, functions and layouts became horribly fragmented and frustration ruled the day. I decided I needed to do this the ole fashion way and write MY code myself. Since I already achieved a partially working script, I decided to maintain uniformity to make progress. Well, as it turns out, the second modal was not hardcoded like the first. Instead, all the inline text and CSS is generated with JavaScript (ie: .. elementById).style.whatever= ) For uniformity, one of these approaches has to be replaced. The question: Is one more efficient? Beneficial? Effective? I've been accused in the past of not being up to date with modern methods, so I thought I'd ask.
  8. @Barand Yes, thanks. That's what I was thinking. And with the drop-down populated with data from a SELECT clause, it will be painless and 100% accurate. @gizmola Thanks for elaborating. I sometimes wonder how granular I need to be (mostly for database speed, right?) when it comes to these things. Nonetheless, thanks to my friends at phpfreaks, I've come a long way from my 84 column table that mimicked a spreadsheet. Although it worked, I imagine the database overlords were cursing my existence. LOL
  9. OK, but why make it dirty the global namespace? 2c2 < $count = 0; --- > //$count = 0; 5c5,6 < global $count; --- > //global $count; > static $count;
  10. You forgot the variable for the "WHERE ID=?" at the end of the query. And are you sure you really mean to try to update the ID? That would be weird...
  11. I wrote a php script to update information in an mysqli database table and and am getting the error: The number of variables must match the number of parameters in a prepared statement. This is the code snippet with the error line in bold red. I don't see anything wrong with it but hopefully some of you sharp eyed people can help me. include "churchdb_data.php"; $con=mysqli_connect('localhost',$username,$password,$database); if (mysqli_connect_errno()) { die ("Failed to connect to MySQL: " . mysqli_connect_error()); } $sql = "UPDATE missionaries SET ID=?, missionary=?, active=?, country=?, city=?, state=?, zip=?, street=?, phone=?,email=?, website=?, facebook=?, photo=? WHERE ID=?"; $stmt = $con->prepare($sql); $stmt->bind_param("issssssssssss", $id, $missionary,$active,$country,$city,$state,$zip,$street,$phone,$email,$website,$facebook,$photo); if ($stmt->execute()) { echo "Record updated successfully!"; } else { echo "Error updating record: " . $stmt->error; } $stmt->close(); $con->close(); ?>
  12. Yesterday
  13. Personally, I would have used an MVC framework so that I'd have separation of routing from Models/DAOs and Views/Templates/Markup. I'd most likely have some "services" and would be making use of quality component libraries whenever possible. Everything I create would be implemented in a way consistent with Dependency Injection, which would allow for use of a Dependency Injection Container. I prefer Symfony, so if it's my choice that is what I'd start with, which is going to dictate basic structure, and have a front controller pattern implementation. What you've done could be broken up into pieces and ported into an MVC framework, which would also help you see where you have reinvented the wheel, and you might also find that that framework has capabilities that could be handle some things you are doing in a more robust or elegant fashion. I also tend to make use of PHP Oop and if you do have classes stuffed inside your one giant script, then that's a dubious practice. While there is no fast rule on this, given PHP's page scope you are clearly having to load lots of unused code for every page request, but I don't want to overstate what currently even at 1500 lines of code, is not by any means overly large.
  14. Hello, I'm building a forum type thing in PHP , js , css etc. At the mo It all runs on just 1 page which is ATM 1500 lines long. Is this too much ? Should I change this to1 page for each Link ? Or just leave it as is ? What do you all think ? Thank-You Sid
  15. Last week
  16. You don't understand the problem as described, and this would not be a solution. The session is already going to be shared across browser tabs because the browser tabs share cookies. It's also not what the OP's stated problem is about.
  17. Hi, To restrict login sessions across browser windows in PHP, you can use a unique session token stored in the database and linked to the user ID. When a user logs in, generate a token, store it in both the session and the database. On every page load, verify if the session token matches the one in the database. If it doesn't, force a logout. This method ensures only one active session per user, preventing multiple logins from different tabs or browsers.
  18. 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>
  19. Hi all, I suspect that there may be a sample solution for my problem but after a week of trying various solutions I am still stumped. The code blow validates the two variables. This works if i do not send the details to form.php, so the line: <form name="form" action="" method="POST"> will validate the data and work fine. However if i want to send the details to form.php to send to my email: <form name="form" action="form.php" method="POST">. the validation stops working and I can put anything on the form and it arrives in my email with no validation Why would this be? Both coding below. this is validation code <?php $user = ['name' => '', 'age' => '', 'terms' => '', ]; $errors = ['name' => '', 'age' => '', 'terms' => false, ]; $message = ''; if ($_SERVER['REQUEST_METHOD'] == 'POST') { //if from submitted // 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 = filter_input_array(INPUT_POST, $validation_filters); // validate data //create error messages $errors['name'] = $user['name'] ? '' : 'Name must be 2-10 letters using A-z'; $errors['age'] = $user['age'] ? '' : 'You must be 16-65'; $invalid = implode($errors); if ($invalid) { $message = 'Please correct the following errors: '; } else { $message = 'Thank you, your data is valid'; } //Sanitize Data $user['name'] = filter_var($user['name'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); $user['age'] = filter_var($user['age'], FILTER_SANITIZE_NUMBER_INT); } ?> <?php include 'includes/header.php'; ?> <?= $message ?> <form name="form" action="form.php" method="POST"> Name: <input type="text" name="name" value="<?= $user['name'] ?>"> <span class="error"><?= $errors['name'] ?></span> Age: <input type="text" name="age" value="<?= $user['age'] ?>"> <span class="error"><?= $errors['age'] ?></span><br> <input type="submit" value="Submit"> </form> . This is form.php <?php $name = $_POST['name']; $age = $_POST['age']; $to = 'myemail.com'; $subject = 'Contact'; $msg = "Name: $name\n" . "Age: $age\n"; mail($to, $subject, $msg, 'from:' . myemail.com); ?> <br /> <?php echo 'Thanks ' . $name . ' We have your info!<br />'; echo "Details: <br />"; echo 'name: ' . $name . '<br />'; echo 'age: ' . $age . '<br />'; ?> <a href="validate-form-using-filters.php" > GO back to form</a> Apologies for all the code but at this point in time I think there must be something other than form action at play here. All help apricated.
  20. 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).
  21. mac_gyver as usual provided you with a clear answer. HTTP protocol is request/response. Without some other streaming protocol, once a client has received a response, the tcp connection(s) required to get all the assets for the page, and the building of that page are close and the rendering of the page and any interactivity is entirely client side. New requests can be initiated, or you can have some javascript (ajax) that makes requests using javascript that can then be used to update the page without having an entirely new HTTP request (GET/POST/PUT/DELETE). There are ways to have a client poll ajax calls, or alternatively to use websocket protocol. You often see websockets used to provide more real time functionality. Regardless, for every Request sent to the server, checking for authorization of the client must be done. In other words, it should not matter if someone has their browser open to your site, as a logged in user who has now had their account deleted/suspended etc. All that matters is that the deletion/suspension/logout is enforced on the CURRENT HTTP request.
  22. 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.
  23. from my last post I figured out how to logout users when they delete the accounts they're logged into and checking the sessions they're using, but it isn't automatic and needs a page refresh which means the user has time to delete other users on the admin page. I want to make it so the moment the account is deleted they're logged out without refresh... is that possible? this is the current code: <?php function pdo_connect_mysql() { $DATABASE_HOST = 'localhost'; $DATABASE_USER = 'root'; $DATABASE_PASS = ''; $DATABASE_NAME = 'phpticket'; try { return new PDO('mysql:host=' . $DATABASE_HOST . ';dbname=' . $DATABASE_NAME . ';charset=utf8', $DATABASE_USER, $DATABASE_PASS); } catch (PDOException $exception) { exit('Failed to connect to database!'); } } function getUser($email) { global $conn; if (empty($email)) { return null; } $stmt = $conn->prepare("SELECT id, username, email, role FROM users WHERE email = ?"); $stmt->bind_param("s", $email); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows > 0) { $userData = $result->fetch_assoc(); $stmt->close(); $user = new stdClass(); $user->id = $userData['id']; $user->username = $userData['username']; $user->email = $userData['email']; $user->role = $userData['role']; $user->isActive = true; return $user; } $stmt->close(); return null; } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ALnasser | Ticketing System</title> <link href="style.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> </head> <body> <nav class="navtop"> <div> <img src="alnasser_nobg.png"><h1><a href="index.php" style="color:white;font-size:25px;font-weight: normal;">AlNasser Help Desk</a></h1> <a href="index.php"><i class="fas fa-ticket-alt"></i>Tickets</a> </div> </nav> </body> </html> <?php include 'functions.php'; include "config.php"; $currentUser = getUser($_SESSION['email']); if (!$currentUser || !$currentUser->isActive) { session_destroy(); setcookie('remember_token', '', time() - 3600, "/"); setcookie('email', '', time() - 3600, "/"); session_start(); $_SESSION['login_error'] = 'Session has expired. Please log in again.'; $_SESSION['active_form'] = 'login'; header("Location: login&signup.php"); exit(); } <?php $host = "localhost"; $user = "root"; $password = ""; $database = "phpticket"; $conn = new mysqli($host, $user, $password, $database); if ($conn->connect_error) { die("Connection failed ". $conn->connect_error); }
  24. Great answer from Barand to your specific question. As for your initial question, start with your entities, and the relationships between them. You mentioned: A DJ Organizations Events Playlists I'm unclear if this means that an event could have multiple playlists, or just one. Implied entities are: artist album song/track So you want to start with the entities and determine which attributes they require. Every entity will become a table, and every table needs a primary key, which unless you have expertise and a strong reason not to, should be auto incremented unsigned "integer" types. You want to use the smallest reasonable type. Some "lookup" tables, you will know in advance will never have more than a handful of rows. Use a tinyint type. Use the smallest type you can get away with. Organizations is a good example here, where you can use a (with mysql for example) a smallint, which unsigned means you could have up to 64k rows in it. With little chance of ever having anything close to that number of orgs, stay with the 2 byte primary key instead of making everything and integer or worse yet a bigint. Once you have the entities ready, then relate them together, by determining the type of relationship needed (one to one, one to many, many to many) and at that point add foreign keys and add ables as needed. There are many ERD design tools that can help with the design process.
  25. @Strider64 my friend, lose the closing PHP tags -- as per https://www.php-fig.org/per/coding-style/. These days I'd recommend that you use mkcert for local development, and not have a configuration variable to get around the use of https only cookie settings. It's just inviting a mistake to be made. I don't know if you've started to make use of docker, but DDEV is a really nice wrapper for setting up docker based PHP development environments, and it integrates mkcert, so you don't even have to invest any time in figuring out mkcert yourself, as they've integrated that into DDEV. It's also a cli tool, which I like.
  26. Usually we would not allow promotion like yours, but in this case it's on topic, and also a helpful example, as the forum utilizes the very techniques your article covers.
  27. Thanks for the info about rel="nofollow". I made a guide showing how to use the <a> tag in HTML for SEO, using the word kedi as the anchor text. You can see it here: https://flatcoding.com/tutorials/html/html-a-tag-how-to-add-links-to-web-page-with-examples/
  28. I personally have `setcookie` setup up like this: // Set a secure cookie with the login token setcookie('login_token', $token, [ 'expires' => strtotime('+6 months'), 'path' => '/', 'domain' => $cookieDomain, // Adjusted for environment 'secure' => $cookieSecure, // Adjusted for environment 'httponly' => true, 'samesite' => 'Lax' ]); as it is easier to debut in my opinion. Here's my full login script for my personal website: <?php // Include the configuration file and autoload file from the composer. require_once __DIR__ . '/../config/clearwebconfig.php'; require_once "vendor/autoload.php"; // Import the ErrorHandler and Database classes from the PhotoTech namespace. use clearwebconcepts\{ ErrorHandler, Database, LoginRepository as Login }; // Create an ErrorHandler instance $errorHandler = new ErrorHandler(); // Set the exception handler to use the ErrorHandler instance set_exception_handler([$errorHandler, 'handleException']); // Create a Database instance and establish a connection $database = new Database(); $pdo = $database->createPDO(); // Create a LoginRepository instance with the database connection $login = new Login($pdo); $checkStatus = new Login($pdo); // Start session if not already started if (session_status() == PHP_SESSION_NONE) { session_start(); } // Redirect to dashboard if the user is already logged in if ($login->check_login_token()) { header('Location: dashboard.php'); exit(); } // Generate a CSRF token if it doesn't exist and store it in the session if (!isset($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // Detect environment $isLocal = in_array($_SERVER['REMOTE_ADDR'], ['127.0.0.1', '::1']); $cookieDomain = $isLocal ? '' : DOMAIN; $cookieSecure = !$isLocal; // Set to true on remote server // Process the login form submission if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Check if the submitted CSRF token matches the one stored in the session if (hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { // Sanitize the username and password input $username = strip_tags($_POST['username']); $password = $_POST['password']; // Verify the user's credentials if ($login->verify_credentials($username, $password)) { // Generate a secure login token $token = bin2hex(random_bytes(32)); // Store the login token in the database $login->store_token_in_database($_SESSION['user_id'], $token); // Set a secure cookie with the login token setcookie('login_token', $token, [ 'expires' => strtotime('+6 months'), 'path' => '/', 'domain' => $cookieDomain, // Adjusted for environment 'secure' => $cookieSecure, // Adjusted for environment 'httponly' => true, 'samesite' => 'Lax' ]); // Store the login token in the session $_SESSION['login_token'] = $token; // Redirect the user to the dashboard header('Location: dashboard.php'); exit; } else { // Log error message for invalid username or password $error = 'Invalid username or password'; error_log("Login error: " . $error); } } else { // Display an error message $error = 'Invalid CSRF token'; error_log("Login error: " . $error); $error = 'An error occurred. Please try again.'; } } // Generate a random nonce value $nonce = base64_encode(random_bytes(16)); ?>
  29. Your form for entering new events would contain a dropdown listing organisations for the user to choose. The value of each dropdown option would br the organisation's id. This id is posted (with the other event data) for insertion into the event resord.
  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.