Jump to content

All Activity

This stream auto-updates

  1. Today
  2. the simplest way would be to make the functional part of the count down code, into a function - <script> // produce count down given a date and the id of the display element function cd(date,display_id) { // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = date - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById(display_id).innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById(display_id).innerHTML = "EXPIRED"; } }, 1000); } </script> you can then dynamically create the desired number of display elements, a corresponding array of count down dates, and call the function for each count down to display - <p id="item_1"></p> <p id="item_2"></p> <p id="item_3"></p> <script> // Set the dates we're counting down to var countDownDate = []; countDownDate[1] = new Date("Feb 18, 2026 23:25:25").getTime(); countDownDate[2] = new Date("Feb 17, 2026 13:25:25").getTime(); countDownDate[3] = new Date("Feb 16, 2026 8:25:25").getTime(); cd(countDownDate[1],'item_1'); cd(countDownDate[2],'item_2'); cd(countDownDate[3],'item_3'); </script>
  3. Hello. Could I please enquire. How can I create a countdown then replicate it 6 times? What I'm trying to do is build and auction page, which has 6 items, and 6 different ending times. I've done it for 1 item (well I've copied the javascript from W3Scools site, then made up a date to test it). But, I'm unsure how to repeat the same process, another 5 dates and times. Could anyone please advise me? The copied countdown code, I've got is:- <!-- Countdown --> <p id="demo"></p> <script> // Set the date we're counting down to var countDownDate = new Date("Feb 18, 2026 23:25:25").getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 1000); </script> Thank You.
  4. Last week
  5. Earlier
  6. Yes, use the technique that @Barand demonstrated. What is missing, and very important is your html form, with the specific field you are using. With HTML5 you can for example utilize an input with type="date". I would recommend using that, as well as html5 in general for your html pages, which is the current standard. While you can never fully trust user input to be valid, at least with HTML5 you can program to the assumptiion that the format of the date string that PHP receives from the form will be in RFC 3339/ISO 8601 format, which is YYYY-MM-dd. The format the user sees in the form will match their localization settings. When I say that you can not trust it, I mean that there are tools that can be used to submit form data directly without going through the HTML page, and for this reason, you always need to do additional validation on the backend. So you might want to validate that the date that has been submitted is infact of the format of 9999-99-99, and not some other format that will probably not work correctly, like 12/01/2023 or any other "string". If the user submits the data using your form, it will be correct, and will also be a "real" date, thanks to the built in browser handling of the "date" input type. Knowing this, you can expect that the date strings will work as Barand demonstrated in his code snippet.
  7. Command line php has a linter (syntax checker) built into it. php -l /path/to/file.php Most PHP Integrated developer environments (IDE's) have a syntax checking built into it. The generally accepted best IDE for PHP is Jetbrains PHPStorm, but VSCode or Codium with the installation of https://intelephense.com/ plugin is a suitable free/low cost option. If you want to try it out, you should make sure to follow the installation instructions, which involves uninstaling a plugin that comes with vscode and will interfere with intelephense. These tools do numerous things to show you what syntax errors you have. Last but not least, there are numerous AI LLM's that you can point at the code and will diagnose problems.
  8. I suspect strtodate() doesn't like the format passed to it (it expects a date string like "1 Feb 2026" and returns a Unix timestamp. If it fails it returns false which is giving the 31 Dec 1969 date. The Unix timestamps start from 1970-01-01.. I'd avoid timestamps and work with datetimes... $ndays = 14; $date1 = new DateTime('2026-02-01'); $ndays = new DateInterval("P{$ndays}D"); $date1->add($ndays); echo $date1->format('Y-m-d'); // 2026-02-15
  9. Hi, I am pretty new to this but am trying to add a set number of days (selected from a drop down) to a date selected in another field. $date1 = $values["validfrom"]; $date2 = $values["validto"]; $ndays = $values["validlength"]; $newdate = strtotime ( $date1. '+' .$nDays. $date2); $values["validto"]= date('Y-m-d', $newdate); Problem is, when I set the date to 1st February, I get 31st December 1969 in my validto field Can anyone help? Thanks,
  10. What are the error messages telling you? You do have error reporting turned on?
  11. Hi Everyone, I'm Meenu Hinduja and my husband Dheeraj Sudan, run a business. I’m running into some syntax errors in my PHP code and I’m not sure how to fix them. I’ve double-checked my brackets, semicolons, and quotes, but the errors keep appearing. Could anyone share tips, common mistakes to look for, or methods to debug syntax issues in PHP? Examples of how you approach fixing syntax errors would be really helpful. Regards Dheeraj Sudan and Meenu Hinduja
  12. Sounds like a penny wise pound foolish exercise. Of course things will be slow if processes have to be started frequently. Of course there will be additional power usage. The question is: what is the expected average and peak usage? You state this is for a client. If the server PS is underpowered, then it's likely to fail. What will the cost be, when the server PS burns out, perhaps damaging the entire machine? Servers typically feature redundancy so that they don't die when a single component has a fault (ie. having multiple PS's, RAID controllers, RAID configuration and hot swappable drives.). Why would you use a box that isn't designed to be a server, as a server, and then attempt to micro optimize and skimp on the PS? If the usage of this environment is such that there is low to no usage during specific periods, then perhaps you can economize by configuring the box to sleep and wake on lan. You didn't provide any information on what services it will be providing. I don't have much else to offer other than that IIS is infamous for its instability, particular if you require additional IIS Modules. If you've gone through the exercise of trying to reduce overhead, and remove/turn off non essential services, then you've already optimized the server to reduce OS and cpu utilization, and if the box isn't doing anything then power consumption will already be low.
  13. Hey everyone, I’m hoping to get some advice from those of you who have been running IIS for a while. I’ve mostly been a Linux/Apache guy, but I’m currently setting up a small, dedicated Windows box for a client who insists on an ASP.NET environment. I’m working with a relatively low-profile setup—specifically a micro-server that’s running on a Server Power 200-Watt PSU. Because the power overhead is so tight, I’m trying to keep the hardware footprint as lean as possible. I’ve noticed that when I start layering on a few Application Pools, the worker processes (w3wp.exe) seem to spike in memory usage much faster than I anticipated. One specific point I'm curious about is the "Idle Time-out" setting in the App Pool advanced settings. I’ve read conflicting things about whether aggressive recycling actually helps with resource conservation or if the constant "cold starts" end up putting more strain on the CPU in the long run. Since I’m trying to keep this build efficient and cool, I don’t want to overwork the processor unnecessarily. In my personal experience, I’ve found that Windows Server can be a bit of a resource hog if you don't strip away the unnecessary roles and features right at the start. I spent all of yesterday just disabling services I knew we’d never touch, which felt like a win, but the IIS overhead still feels a bit heavy for this specific hardware. Has anyone else here managed to successfully optimize IIS for low-wattage or constrained hardware environments without hitting major latency issues? I’d love to hear how you handle App Pool management when you don't have infinite RAM to play with.
  14. I agree. I am open to simpler solutions if you have any. At the time, this was the only way I could figure out how to make it work. This ended up fixing the issue. It was caused by white space being added after a ?> tag. It never occurred to me that I could leave those out altogether. I learned PHP 20 years ago, maybe more. I only use it when I have specific problems I think it can solve. So it makes sense that I am out of date. Thanks for the resources; I am sure they will be a big help. I also removed the class and replaced it with a function. in hindsight that makes more sense.
  15. This is some confusing code -- you are creating a pdf purely to then create an image out of it. Since you are throwing away the pdf, I have to think there's a more direct way to do this, either with imagemagick directly or using some existing library designed for making graphs and charts. With that said, if it works on one machine and not the other, and everything else is the same, then you have to consider the environment settings and what might be different (error levels, permissions, etc.). A few comments: It's best not to have a php close tag in your scripts. This and other recommended coding standards are documented here: https://www.php-fig.org/per/coding-style/ I bring this up because whenever you are returning output, a closing tag with whitespace following can lead to to some strange and confusing behavior, and has long been one of the reasons people encounter the "output already sent" message. There is also little to no reason to have code that is trying to clean up resources -- especially in a script like this, when php garbage collects everything when the script ends. Having a script that defines a class only to use it in the same script in which it was defined is an anti pattern, you should try and avoid. PHP also has namespaces, composer as both a dependency manager and autoload builder. You are using php 8.5, yet creating and writing code the way people did it 15 years ago.
  16. getImageBlob() returns a string...
  17. Hey everyone, I am trying to load an image that I created from a string. It worked great on my staging site, but now that it's on my live site, it isn't working. Both pages are on php8.5 <?php $kcal = 500; require_once("fpdf.php"); class PDF extends FPDF{ // Simple table function BasicTable($header, $data, $kcal){ // Header $first = 45; foreach($header as $col){ $v = is_numeric($col) ? round($col) : $col; $this->Cell($first,7,$v,1,0,'C'); $first = 8; } $this->Ln(); // Data foreach($data as $row){ $first = 45; foreach($row as $col){ $v = (is_numeric($col)) ? near25($col/$kcal/112) : $col; $this->Cell($first,7,$v,1,0,'C'); $first = 8; } $this->Ln(); } } } $header = json_decode('["Category class)","1","1.5","2","2.5","3","3.5","4","4.5","5","5.5","6","6.5","7"]'); $row = json_decode('[["Activity",130,150,170,190,210,230,250,270,290,310,330,350,370]]'); // Data loading $pdf = new PDF(); $pdf->SetFont('Arial','',6); $pdf->AddPage(); $pdf->BasicTable($header,$row, $kcal); $output = $pdf->Output('S'); $im = new imagick(); $im->setResolution(300, 300); $im->readImageBlob($output); $im->setImageFormat('png'); $im->setImageCompression(imagick::COMPRESSION_JPEG); $im->setImageCompressionQuality(100); $im->borderImage("#ffffff", 20, 20); $im->trimImage(0.3); $im->setImagePage($im->getImageWidth(), $im->getImageHeight(), 0, 0); header("Content-Type: image/" . $im->getImageFormat()); $im->getImageBlob(); $im->clear(); $im->destroy(); ?> When I run the script I get a broken image icon. My first thought was that there is an issue creating the image. However, if I switch the following, it shows the image is made properly. <?php //header("Content-Type: image/" . $im->getImageFormat()); //echo $im->getImageBlob(); ?><img src="data:image/png;base64,<?php echo base64_encode($im->getImageBlob()); ?>" alt="" /><? ?> Any ideas?
  18. the apparent symptom you are having (do you actually see any Swal dialog?) is that of code that redirects to another page that then redirects back to the starting page. you should temporarily comment out the redirect statements and add console.log() statements so that you can uniquely determine which execution path the javascript code takes. do you have a session_start() statement on each page that sets or references a session variable? there is none in the posted code. if you are not seeing any Swal dialog, you will need to determine why. are there errors in the browser's developer console? what data is in $status? the posted code is not displaying any $errors data. if you cannot determine the cause of the problem, you will need to post all the code necessary to reproduce the problem. less anything like database connection credentials, api keys, ... some points for the posted code - the only piece of user data you should store in a session variable is the user id (auto-increment 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. you need to validate the trimmed input data, not the raw input data. by validating the raw value, then trimming and using it, the current code will accept any collection of white-space characters as a valid email address, but use an empty string in the rest of the code. after you determine that the trimmed email input is not an empty string, you need to validate that it is a properly formatted email address. see php's filter_var() with the FILTER_VALIDATE_EMAIL filter. don't change the name of a piece of data in the code. if the input is an email address, don't refer to it as anything else. if you set the default fetch mode to assoc when you make the database connection, you wont need to specify it in each fetch statement. you need to integrate the login operation on any page that needs it, rather than redirecting around on the site. this alone would help with debugging the problem and will simplify all the code. i didn't examine all the logic/possible execution paths in great detail to see if there were any 'holes' where the code wouldn't tell you when something went wrong. by determining what the execution path is and what data is being produced by the code, you should be able to pin down where the problem is occurring.
  19. I don't know where i am missing it. Instead of continue login process, it's validating the form again (asking for username and pasword.) I really don't know why the form is resetting. <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN'; $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN'; $newToken = bin2hex(random_bytes(32)); $errors = []; $forceLogin = isset($_POST['force_login']) && $_POST['force_login'] == '1'; if (empty($_POST['email'])) { $errors['username'] = "Username is required"; } else { $email = trim($_POST['email']); } if (empty($_POST['password'])) { $errors['password'] = "Password is required"; } else { $pass = $_POST['password']; } if (empty($errors)) { $stmt = $pdo->prepare("SELECT * FROM tbl_users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user) { $status = ['type' => 'error', 'message' => 'Invalid credentials.']; }elseif ($user['account_locked_until'] !== null && strtotime($user['account_locked_until']) > time()) { $status = ['type' => 'error', 'message' => 'Account is locked. Please try again later.']; }elseif (password_verify($pass, $user['password'])) { $sessionCheck = $pdo->prepare(" SELECT * FROM tbl_user_session WHERE user_id = ? AND is_active = 'yes' AND expires_at > ? ORDER BY id DESC LIMIT 1 "); $sessionCheck->execute([$user['user_id'], time()]); $activeSession = $sessionCheck->fetch(PDO::FETCH_ASSOC); $haltLogin = false; if ($activeSession && $user['role'] === 'admin' && $forceLogin) { $killSessions = $pdo->prepare(" UPDATE tbl_user_session SET is_active = 'no', expires_at = ? WHERE user_id = ? AND is_active = 'yes' "); $killSessions->execute([time(), $user['user_id']]); $haltLogin = false; }elseif ($activeSession) { if ($user['role'] === 'student') { $haltLogin = true; echo "<script>var showAlert1 = true;</script>"; } if ($user['role'] === 'admin' && !$forceLogin) { $haltLogin = true; echo "<script>var showAlert2 = true;</script>"; } } $reset = $pdo->prepare(" UPDATE tbl_users SET failed_attempts = 0, account_locked_until = NULL, last_login_at = NOW() WHERE user_id = ? "); $reset->execute([$user['user_id']]); $stmt = $pdo->prepare(" INSERT INTO tbl_login_log (admin_id, email, action, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, ?, NOW()) "); $stmt->execute([ $user['user_id'], $user['email'], 'LOGIN_SUCCESS', $ip_address, $userAgent ]); $_SESSION['user'] = [ 'user_id' => $user['user_id'], 'email' => $user['email'], 'role' => $user['role'] ]; $_SESSION['active_id'] = $user['user_id']; $_SESSION['session_token'] = $newToken; $status = ['type' => 'success', 'message' => 'Login successful! Redirecting...']; if (!$haltLogin) { $idleTimeout = 30 * 60; $expiresAt = time() + $idleTimeout; $insertSession = $pdo->prepare(" INSERT INTO tbl_user_session (session_token, user_id, ip_address, user_agent, last_activity, expires_at, is_active, created_at) VALUES (?, ?, ?, ?, NOW(), ?, 'yes', NOW()) "); $insertSession->execute([ $newToken, $user['user_id'], $ip_address, $userAgent, $expiresAt ]); } }else { $failed = $user['failed_attempts'] + 1; $lockTime = null; if ($failed >= 3) { $lockTime = date("Y-m-d H:i:s", strtotime("+15 minutes")); $status = [ 'type' => 'error', 'message' => 'Account locked after 3 failed attempts. Try again in 15 minutes.' ]; } else { $status = [ 'type' => 'error', 'message' => "Invalid credentials. Attempt {$failed} of 3." ]; } $update = $pdo->prepare(" UPDATE tbl_users SET failed_attempts = ?, account_locked_until = ? WHERE user_id = ? "); $update->execute([$failed, $lockTime, $user['user_id']]); $stmt = $pdo->prepare(" INSERT INTO tbl_login_log (admin_id, email, action, ip_address, user_agent, created_at) VALUES (?, ?, ?, ?, ?, NOW()) "); $stmt->execute([ $user['user_id'], $user['email'], 'LOGIN_FAILED', $ip_address, $userAgent ]); } } } ?> <script> Swal.fire({ icon: '<?= $status['type'] ?>', title: '<?= $status['message'] ?>', showConfirmButton: false, timer: 2500 }).then(() => { <?php if ($status['type'] === 'success'): ?> const role = '<?= $_SESSION['user']['role'] ?>'; if (role === 'admin' || role === 'staff') { window.location.href = '../admin/index.php'; } else if (role === 'student') { window.location.href = '../student/dashboard.php'; } <?php endif; ?> }); if (typeof showAlert1 !== 'undefined' && showAlert1) { Swal.fire({ icon: 'warning', title: 'Warning', text: 'You are logged in on another device.', }); } if (typeof showAlert2 !== 'undefined' && showAlert2) { Swal.fire({ icon: 'warning', title: 'Warning', text: 'You are logged in on another device. Continue and log out the other session?', showCancelButton: true, confirmButtonText: "Yes, Continue", cancelButtonText: "Cancel" }).then((result) => { if (result.isConfirmed) { document.getElementById('force_login').value = '1'; document.getElementById('loginForm').submit(); } }); } </script>
  20. Welcome to the world of PHP development. It is unfortunately the case that for some reason, most people new to php development, particularly using Windows, still default to the installation of Xampp. My first comment is that Wamp/Mamp/xampp etc. are all projects that haven't been used by professional developers in a long time. This change in approach to local development was hastened by the commodity support of virtualization built into intel and amd cpu's. Every PC that is more powerful than a potato supports virtual environments. Developers first started developing with or within virtualized environments using software like Vmware workstation and Virtualbox in the mid to late 2000's. It's important to understand virtualization, and how it is the basis for cloud and vps servers. This was an evolution that began close to 20 years ago at this point. Many professional developers were developing PHP apps within virtualized linux systems back in 2007-2008. The orchestrator "Vagrant" was released in 2010 with a 1.0 version in 2012 and was for a time, the favored approach for many developers and development teams as a way to harness the virtualbox and VMware hypervisors to build simplify and orchestrate virtual linux based environments. I might add that Windows now includes it's own microsoft provided hypervisor - hyper-v, so the option to run fully virtualized servers within windows is still an option for development on a windows workstation. Xampp is an antiquated approach to php development with many drawbacks including: It's based on LAMP (Linux, Apache, MySQL, PHP) in a particular configuration that few websites use anymore for various reasons The once popular apache/mod_php integration has been superceded by the use of the php_fpm server component other http servers/proxies are often used, with nginx being a common choice. It's a wrapper for windows native ports of the components. PHP apps aren't deployed to windows servers -- they are deployed to Linux servers 99.9% of the time It makes no sense to develop your application in an environment you won't be deploying to, and there are also OS specific differences which means that some php code that works in a linux environment won't work under windows and vice-versa Developers are often unaware that they have installed local server components which are running (unless they proactively start/stop them) all the time. These projects (xampp, wampserver, easyphp, mamp..... and many others) have been dying off due to lack of interest, and have to be updated frequently, requiring re-installation. It's old, and ugly, and people have been coming up against problems with them for over a decade, or finding that their favorite environment package has fallen behind or been abandoned entirely. Windows based developers should prefer the use of windows application installation through package managers (Chocolatey, Scoop, Winget etc.) just as Mac users prefer homebrew, and linux users utilize distro specific package managers (apt, yum/dnf, flatpak, etc). Again these windows package tools utilize a cli environment, rather than the old "find a website, download a .exe setup, run it and hope this new program does what you need it to do." The setup of tools and disconnect in how apps can or should be deployed from development to product leads to confusion The configuration files that are used to configure apache and php is hidden from the user competent professional php development involves learning the basics of cli tools, use of git, and the composer cli tool. Xampp is intended to "simplify" by hiding the cli, and thus discourages and sends the message to a new developer that they don't need to use the cli, which is counterproductive Windows users have a variety of far better options with the main 2 being: use WSL to install a linux distro integration, and work within WSL fast, performant and makes the development experience closer to what osx and linux developers do use Docker based environments Provides the ultimate degree of project by project flexibility and can provide a local development environment that includes an orchestrated set of server components that would be extremely difficult to set up locally using any alternative approach. Easily switch between php versions/databases/http servers on a project by project basis Is supported by multiple projects that simplify the use of docker (DDEV, Lando, Docksal -- others) I advise most people to install DDEV now The only thing Xampp is going for windows based developers now, is teaching old mostly obsolete development. If a tutorial or article starts with the use of Xampp, it almost always provides bad advice and techniques and code samples that no experienced developer would use. There are numerous resources that can be used to study and learn modern PHP development, and anyone running windows can find numerous existing resources (tutorials, guides, articles, free and paid online courses) that will show you how to use wsl or docker/ddev. This will also lead you to understand and become proficient in the use of component libraries and frameworks. These things tend to come together once you start to understand the use and purpose of composer, which should be the first step (after making a project directory) you should be using (unless a tool like DDEV or the symfony cli tool has run done that setup for you).
  21. My query worked fine for me... mysql> select DATE_FORMAT( STR_TO_DATE('Mar-2026', '%b-%Y'), '%m-%Y'); +---------------------------------------------------------+ | DATE_FORMAT( STR_TO_DATE('Mar-2026', '%b-%Y'), '%m-%Y') | +---------------------------------------------------------+ | 03-2026 | +---------------------------------------------------------+ To better simulate what you are doing... CREATE TEST TABLE: mysql> CREATE TEMPORARY TABLE test1(datestr VARCHAR(8)); mysql> INSERT INTO test1 VALUES('Jan-2026'), ('Feb-2026'),('Mar-2026'); QUERY AND REFORMAT: mysql> SELECT datestr -> , DATE_FORMAT( STR_TO_DATE(datestr, '%b-%Y'), '%m-%Y') as formatted -> FROM test1; +----------+-----------+ | datestr | formatted | +----------+-----------+ | Jan-2026 | 01-2026 | | Feb-2026 | 02-2026 | | Mar-2026 | 03-2026 | +----------+-----------+ Then what are you really trying to achieve?
  22. thank you @Barand for your help, don't know why but your SQL return NULL value. I tried further, below is my solution which returns exact value what I needed. if it is not appropriate please help to correct it because only end result is not complete solution may be there are several things in my SQL statement which require correction(s). select SUBSTRING( CAST( DATE_FORMAT( STR_TO_DATE('Mar-2025-01', '%b-%Y-%d'), '%m-%Y-%d') as CHAR), 1,7) AS result; thank you again.
  23. There are a couple of errors in your SQL statement... The specified format should be in quotes (it's a string) The format code for a short month name id "%b" (%m is month number) Try select STR_TO_DATE('Mar-2026', '%b-%Y'); -- > 2026-03-00 Note the function returns a date. To output your required "03-2026" you need to use DATE_FORMAT() on the returned date select DATE_FORMAT( STR_TO_DATE('Mar-2026', '%b-%Y'), '%m-%Y'); | | input output format format Easiest is always to store dates as DATE TYPE ie 2026-03-01 instead of Mar-2026.
  24. hi all respected members, I am new to PHP & MySQL, created working environment on Windows machine with XAMPP. my question is I want to write an SQL in which I want to include a string conversion for Feb-2026 -> 02-2026 I wrote below example after getting help (googling) but it return null in phpMyAdmin console select STR_TO_DATE('Mar-2026', %m-%Y) from mytable; and it returns null ... what's wrong here in my SQL? I am much curious how to resolve it? please note: i knew this is not a FIELD from table instead it is just a hard coded value, posted it just to show what value table column contain.
  25. You use the word "file" a lot. I'm going assume that you mean Database "Tables" and not actual, operating system files. What you're describing is Row Level Security. For that to work, you have to have a Column in each and every Table that you want to restrict access to that holds the identifier of the "owner" of that Row. That might be an email address but those tend to be quite long (increased storage need) and, potentially, might change (bad Key candidate, can't be easily/efficiently updated), so it would be better to use the surrogate, numeric User ID (Primary Key) value from the MEMBERS table. UserID Email 1 [email protected] 22 [email protected] UserId - small storage requirement, never changes. Email - larger storage requirement, potential to change over time; poor choice for a Key. Yes. ID Owner Posting_TS Message 777 22 -5000/01/14 09:00:00 Message from Barney ... 888 1 -5000/01/14 09:05:00 Reply from Fred ... When you insert a row into one of these tables, you set the "owner" column to the value of the User ID (or Email) that you hold in the Session. Whenever you query any of these tables, you filter by the "owner" column, again using the value that you hold in the Session. Bear in mind that this may also affect the Indexes that you create on these tables, which should include the "owner" column, because you're going to be specifying it on every query. Regards, Phill W.
  26. As I understand it, PHPRunner is a PHP Code generator. Most of the people who frequent this forum are or have been PHP Developers, and I doubt seriously that anyone has ever used PHPRunner. Just speaking generally, PHP Sessions are basically containers for a set of variables on a server that are associated with a user. Sessions are not a database. Technically, they are just PHP variables that PHP will "serialize" and "deserialize" for you. A running script can add, remove and change session variables, and PHP will load the contents of those variables each time the same user makes a new HTTP request, which the server does based on a cookie value. Usually for something like a member/user system, you would have a database table called user or member, that has the email field and a password field, and that table will also have a primary key, which is usually a sequentially assigned integer. The specifics of this depend on the database being used. It looks to me like PHPRunner can support a number of different databases. Typically, a new visitor to the site, with no existing session cookie will be assigned one, whether or not they have logged in. Once they do login successfully, many systems will read the email and user_id value from the database and set a session variable like $_SESSION['is_logged_in'] = true. The system can then use this as well as the user's unique id value, and can use this to "guard" any screen that requires login, including a form that allows the user to add or update data associated with them. That data will typically use the user's user_id to "relate" the user's data to their user table row. As this id number is kept on the server and never accepted as user input, there is no way for someone to change or add data that doesn't belong to them, unless you create code that is incompetent. The specifics of this have to do with relational database design which is a entire subject line of its own. Beyond this conceptual description, I can't really help you any further as I have no idea how PHPRunner creates code that supports these standard ideas, but I have to assume that it is designed to generate code that does once you understand it. My best advice to you is to seek support from the company that makes it, or try their forums. Best of luck!
  27. It would help if you stated what your problem is. It's not clear at all, exactly what issue you are having. In general setting the From address to be someone who filled out a form, is spoofing, and not the way to handle this. You can not send mail to yourself on behalf of another user, without that looking like you are spoofing. You also can't "open relay" mail on behalf of others, which is another common mis-configuration issue which will get you blacklisted, and in some cases dropped by your hosting company. In other words, when you send mail, if you want it to be delivered, you either have to work within what your hosting company allows (which will disallow both spoofing and open relaying) or you need to set up your mail sending so that it neither spoofs nor relays mail. Using SMTP (which exists for direct mail server to mail server transfer). The email you are attempting to drop off needs (and ultimately will) come from an email server that will accept it. The email should come from a fixed legitimate user authorized to send email from your server, and there are many ways for that to happen and potential complexities that are connected to the configuration of your server and hosting. Your code is attempting to use the SMTP protocol, but it can't send mail directly to another user without having support for all the things that email servers require (SPF, DKIM, DMARC, MX, Valid Reverse DNS entries) if you want to avoid blacklists/and spam or outright rejection of the email. Looking at what it appears you are trying to do, I would suggest that you modify things to that you utilize the configured MAIL_FROM_ADDRESS constant, and change the toAdmin method so that it sets the reply to as the user. You should stop spoofing the from address, for the reasons I already mentioned. Unfortunately the poorly written Mailhelper wrapper class is in the way of the PHPMailer class method you need to call which is: $mailhelperObj->addReplyTo($inputs['email', $inputs['name']); The way the MailHelper class is written you would need to alter public function handleMail(string $subject, string $body, string $to_address, string $to_name, string $from_address, string $from_name): PHPMailer And add a new parameter which would probably be "?string $reply_to" -- like so: public function handleMail(string $subject, string $body, string $to_address, string $to_name, string $from_address, string $from_name ?string $reply_to = null ): PHPMailer Inside the handleEmail method you would want to have something like this: if ($reply_to) { $this->mail->addReplyTo($reply_to, $from_name); $from_name = MAIL_FROM_NAME; } The reason I'd reset the $from_name here, rather than adding the user provided name, is that I think it's probably a bad idea with any mail client to have the same email address associated with a revolving door of different names, so once the reply to is set, I'd reset it so the actual mail sender did not include the <some name> label, which produces that disconnect. In other words you don't want an email from "[email protected] <some person>" and then the next time someone uses the contact form, having an email that is "[email protected] <different person>". When you reply to the person, your email client will use the reply to using their actual email address, which is the reason you were trying to spoof the from email in the first place. With these changes as a basis, changing the "toAdmin()" method should be fairly obvious, and I already did more refactoring for a question like this, than I like to do for questions from "non php developers" who just want someone to fix their code for them.
  28. Hello I have a website for a private event organisation where people can signup or contact me using forms. Those forms are sent to me via email. I did not create this forms, a colleague did, since my PHP knowledge is poor. Currently, I have set up an email account only for sending. The recipients mail address (mine) is definied as global variable in a config file. The senders mail address is set as sender in that email I get for the reason that I easily can reply to that mail and it reaches the sender. And this might be a problem for envelope-to. The senders mail address normally is not part of my email addresses hosted by that provider 🙂 The colleague who made the code for me, used a mail tool called mailHelper which is built up this way: <?php declare(strict_types=1); use PHPMailer\PHPMailer\Exception; use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\SMTP; class MailHelper { private PHPMailer $mail; private string $ErrorInfo; public function getErrorInfo(): string { return $this->ErrorInfo; } public function hasErrorInfo(): bool { return !empty($this->ErrorInfo); } public function __construct() { $this->mail = new PHPMailer(true); $this->mail->CharSet = PHPMailer::CHARSET_UTF8; $this->mail->isHTML(false); } /** * @throws Exception */ public function toUser(string $subject, string $body, string $to_address, string $to_name, ?string $from_address = null, ?string $from_name = null): PHPMailer { if (!$from_address) { $from_address = MAIL_FROM_ADDRESS; } if (!$from_name) { $from_name = MAIL_FROM_NAME; } // Validate to address if (!filter_var($to_address, FILTER_VALIDATE_EMAIL)) { throw new Exception('Invalid to address "'.$to_address.'" for user'); } // Validate from address if (!filter_var($from_address, FILTER_VALIDATE_EMAIL)) { throw new Exception('Invalid from address "'.$from_address.'" for user'); } return $this->handleMail( subject: $subject, body: $body, to_address: $to_address, to_name: $to_name, from_address: $from_address, from_name: $from_name ); } /** * @throws Exception */ public function handleMail(string $subject, string $body, string $to_address, string $to_name, string $from_address, string $from_name): PHPMailer { try { /** For SMTP, change the following */ if (USE_SMTP) { $this->mail->isSMTP(); if (DEBUG) { $this->mail->SMTPDebug = SMTP::DEBUG_SERVER; } $this->mail->Host = SMTP_HOST; $this->mail->SMTPAuth = true; $this->mail->Username = SMTP_USERNAME; $this->mail->Password = SMTP_PASSWORD; $this->mail->SMTPSecure = SMTP_ENCRYPTION; $this->mail->Port = SMTP_PORT; } else { $this->mail->isMail(); } /** Add the BCC in case there are some given */ if (count(BCC_RECIPIENTS) > 0) { foreach (BCC_RECIPIENTS as $bcc) { // Validate BCC address if (filter_var($bcc, FILTER_VALIDATE_EMAIL)) { $this->mail->addBCC($bcc); } } } $this->mail->setFrom($from_address, $from_name); $this->mail->addAddress($to_address, $to_name); $this->mail->Subject = $subject; $this->mail->Body = $body; return $this->mail; } catch (Exception $e) { $this->ErrorInfo = $e->getMessage(); } } /** * @throws Exception */ public function toAdmin(string $subject, string $body, ?string $from_address = null, ?string $from_name = null): PHPMailer { if (!$from_address) { $from_address = MAIL_FROM_ADDRESS; } if (!$from_name) { $from_name = MAIL_FROM_NAME; } // Validate to address if (!filter_var(MAIL_TO_ADDRESS, FILTER_VALIDATE_EMAIL)) { throw new Exception('Invalid to address "'.MAIL_TO_ADDRESS.'" for admin'); } // Validate from address if (!filter_var($from_address, FILTER_VALIDATE_EMAIL)) { throw new Exception('Invalid from address "'.$from_address.'" for admin'); } return $this->handleMail( subject: $subject, body: $body, to_address: MAIL_TO_ADDRESS, to_name: MAIL_TO_ADDRESS_NAME, from_address: $from_address, from_name: $from_name ); } } That is the complete MailHelper.php file. The sending of an email works in this way: $mail = new MailHelper(); $mail->toAdmin( subject: '*subject*', body: $body, from_address: $inputs['email'], from_name: $inputs['name'] )->send(); I hope, you see clear what I am asking for and I hope more that there is a soulution 🙂 Thanks a lot.
  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.