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

    • There are no registered users currently online

All Activity

This stream auto-updates

  1. Today
  2. Yesterday
  3. Unfortunately, your proposed solution has exactly he same flaw as the original post in this thread (Hands up everyone who isn't here!. You can't just do a simple count what isn't there.) Read the whole thread before posting and learn.
  4. Late to the party, but you can get those counts in one simple query. Something like: select rating, count(*) as total from ratings group by rating order by rating desc; If you already have the ratings in an array in PHP, array_count_values works too. Curious how you planned to display the summary once you had the numbers?
  5. Last week
  6. So here's one of the options that's incredibly easy: use Symfony's HttpFoundation component, which across the PHP world is one of the most used Component libraries: See here for a partial list. It provides a formal OOP interface to HTTP Requests and Responses, Cookies, sessions and anything else that people get from the primary cgi-bin superglobals. This can add value to any php based web app, but at minimum you could use it to handle setting partitioned cookies. It's as easy as adding to your project using composer composer require symfony/http-foundation creating your HTTP response object and using it's fluent setcookie method call. <?php use Symfony\Component\HttpFoundation\Cookie; $cookie = Cookie::create('foo') ->withValue('bar') ->withExpires(strtotime('Fri, 20-May-2011 15:25:52 GMT')) ->withDomain('.example.com') ->withSecure(true) ->withPartitioned(); I've found that if you don't have classes to handle Request and Response, you end up cobbling together something that is redundant and less well designed and tested, so the other classes included in the component are well worth looking into. More Documentation here.
  7. Yup. Five solutions, in fact. Did you read the comments on that page?
  8. I am on PHP 8.4. Any solution here? https://github.com/php/php-src/issues/12646
  9. If you're unlucky enough to be on PHP 8.5, support for Partitioned was added. Otherwise, besides manually setting the header yourself, I believe the cookie settings are still "vulnerable" to injection by way of the other settings. Like, you could set the path to be "/; Partitioned" and PHP wouldn't even give it a second thought.
  10. I recently noticed the console error message: Cookie “__cf_bm” will soon be rejected because it is foreign and does not have the “Partitioned“ attribute. The only cookie I'm using is being created by PHP Sessions. Does anybody know how to add this attribute going forward?
  11. You should not be trying to programmatically determine whether to call session_start. You should simply be calling it at the start of your index.php file. if it "loads" everything else, there is no need to have session_start calls anywhere but the index.php. The session will already be available to any of the include/required scripts. Remember that $_SERVER is a superglobal, and is always available globally.
  12. Earlier
  13. It's been a while since I've dealt with sessions manually (been in Laravel land for the last 7 or so years), but according to the docs: As far as I can remember as long as you're piping everything through your front loader, a call to session_start() in that file should be sufficient. If you're using index.php as the front loader on some routes and page.php on others, try adding the session_start() call to page.php?
  14. When the web page is messed up, what does the 'view source' in the browser show?
  15. I have a problem with session start. It messes up my site a bit too ******. This is a hybrid CMS/SPA site that fetches pages via slugs. Pages fetched via slugs fetch their content and data from the database. The problem is: Check if session is already active before starting. if (session_status() === PHP_SESSION_NONE) { session_start(); } Index.php is the page that opens everything, page_home.php is one of the files that is included in the CMS. page_home.php is the main file, and the file in the CMS that opens and navigates the CMS/SPA I thought that as long as I had: if (session_status() === PHP_SESSION_NONE) { session_start(); } ... Then I could have session_start on multiple pages, but it crashes and breaks my site. It looks like a mess. The reason I want the session_start control is because it seems like a single session_start is not able to keep the session going throughout the website. Can anyone tell me if they have encountered this before, and tell me what I am doing wrong? I am almost out of hair as I am scratching my head so much about this problem!
  16. Right. It's an annoying issue with web development, but user input can never be trusted, and input validation must always be placed in both places. My approach has long been to start with the backend and insure that you are validating raw submission. This is where tools like postman are helpful. Once the backend is locked down, you can then move to validation in the HTML and javascript. You can get by without validation or HTML5 forms in the front end, but you can't get by without the backend validation.
  17. This comes down to some basic advice, particularly where databases are concerned (assuming you are using a sql database): Always use the right datatype. Money is a particular problem for floats, so depending on the database, you can either hack the use of an integer or if there's a datatype like the mysql DECIMAL type, something already designed to handle money without the potential for rounding errors. This also should tell you, that to support flexibility, your database should also include an indicator of the "type" of currency. If you implement a type table, your application will be able to know the difference between an amount that is stored in pounds or euros, or US dollars. Once you realize that floating point datatypes aren't good for handling calculations involving money, you then want to look into possible approaches. Even if you are using a DECIMAL field in the database, that doesn't insulate you from rounding errors if you read the values into PHP Floats and start doing calculations with those values. This is a few years old, but I think it's a good starting point for considering how your code works now, and potential ways to address currency and calculations that involve currency. In general, the display of data formatted in a way that is standard for an end user is referred to as "locale" and when you setup a personal workstation or server, you are asked questions that then configure the OS, typically using locale specific standards. So the presentation of a "currency" number and the actual currency that number represents should be a presentation issue. Unless you have a system that is actually storing values in multiple currencies (which would then add an entire extra layer of complexity that's probably beyond the scope of what you are currently working on), you should not be accepting strings that may or may not include a currency character, and then trying to manipulate them. That is all presentation logic, that should be separate, and essentially invisible to the inner workings of your application. Don't accept character fields in your form, and this problem goes away. If you want to add some intrinsic UI functionality that allows you to cut/paste a value, handle that in javascript and just strip out any non numeric characters.
  18. It's a little painful, but not too complicated if you treat the input as being one of two things: a number starting with a ".", or a number starting with a digit and optionally containing a fractional portion. ^(\.\d+|\d+(\.\d*)?) The separation because there has to be at least one digit in there somewhere, but it could be before the decimal or after. If you run that through preg_match, $1 (and $0 for that matter) is the leading numeric portion of the string it matched. Then you can also do a quick strlen check to see if anything got lost. However, floatval/cast to float will implicitly drop any trailing non-numeric portion as it is, so there's no need to try to remove it manually. Minor downside that exponential numbers, like "1.23e45" are acceptable, but IMO it doesn't matter enough to prohibit it in the backend if someone the frontend allowed it.
  19. I agree 100% with @requinix about setting the type of the field to a numeric input. However, I am a belt and suspenders type of programmer. UI constraints are great for helping the user to avoid common data entry errors, but I believe all such validations should have server-side controls (what if the user POSTed a form outside the UI?). The problem is you are making the problem harder than it needs to be. Why do you only care about '£' character? Just because you are accidentally copy/pasting that character doesn't mean you wouldn't have issues with other characters. So, rather than trying to exclude only that specific, arbitrary character - you should remove all characters that would create an invalid number. Or, conversely, you could detect that the value is not a valid number and return the user back to the input page showing an appropriate error. The choice would be a business decision. Taking the first approach, here is one way to do it: function forceToNumber($value) { //Remove everything that is not a digit or decimal point $value = preg_replace('/[^\d.]/', '', $value); //Check if there is more than one decimal point if(substr_count($value, '.') > 1) { //Remove everything from the 2nd decimal $value = substr($value, 0, strpos($value, '.', strpos($value, '.')+1)); } //Retur4n value as a float return (float) $value; } I'm sure there is a more elegant way to deal with possible multiple decimal points (possibly with a single regex), but I've not worked with Regex for quite a while.
  20. These models describe how the relational database engine handles concurrency. You don't DO anything. The Database does things for you, using various algorithms and whatever concurrency model you've configured it to use. These differ from RDBMS to RDBMS. This particular optimization is intended to deal with the processing of timestamped transactions in a transaction log that is being used to actually write out data. So by definition, this involves multiple "user/connections" that are trying to operate on the same row of data at close to/near the same time so that the transaction log is likely to have these read/write pairs of operations that could end up being in conflict with each other , and those scenarios are specific to an application and typically few/far between. In your case, for a banking transaction where you might need to debit/credit, you would wrap the changes inside a transaction, perhaps having issued a SELECT FOR UPDATE if the transaction would be updating a balance field. I'm not sure what the value of focusing on Minutiae like this provides, without any practical application or testing on your part. To examine how this all works, and what ramifications it would have, you would need to: Have a database that implements the Thomas's write rule Set up a database/tables Simulate the different scenarios (which is non-trivial as these would need to be separate sessions)
  21. http://www.csc.villanova.edu/~enwafor/database/lectures/Lecture_14_concurrency.pdf Slides taken from here. Transaction could be a banking transaction. If I am ignoring a write of an operation and continuing forwards, would not that hamper the transaction? I am pretty confused.
  22. Why even consider Javascript when all you have to do is use a number input?
  23. Yes the form does have a pound sign to the left. It's just me copying and pasting that has happend. However if there is a way of escaping hitting a pound sign then how do I do that without some kind of javascript? And yes there are other dorm of using the £. I have this in the code. $Comment = str_replace ( "£", "&#163;", $_SESSION["DE_Comment"] ) ;
  24. If the input is supposed to be numbers then help yourself by using an input with type=number so the user can't accidentally type non-digits. Also, it would help to give a visual indication of the currency being implied - typically this looks like a little £ symbol to the left of the input area. The actual problem you're having is 99% likely to be character encoding. There are multiple possible byte encodings of the character "£", and PHP only cares about bytes. So if the £ coming from the form is encoded one way and the £ written in your code is encoded another way, the substitution doesn't happen. Make sure you're using UTF-8 encoding (or some other specific encoding) for absolutely everything - your webpages, your database, your code files, everything. Then you won't have problems with bytes not matching up.
  25. Hi. I have 2 text boxes where I add money in to an account and money out. This works. But if I accidently put a £ into the text box which is not needed, I get an error. I decided to do a string replace but get an error if I put the £ symbol in. Surley this should be simple? It works fine when I leave the '£' out. $Comment_Name = $_SESSION['COMMENT_NAME']; $_SESSION['DE_MyReason'] = $_POST['Reason']; // Keep the default regardless $_SESSION['DE_Money_In'] = $_POST['MoneyIn']; $_SESSION['DE_Money_In'] = str_replace ("£","",$_SESSION['DE_Money_In']); $_SESSION['DE_Money_Out'] = $_POST['MoneyOut']; $_SESSION['DE_Money_Out'] = str_replace ("£","",$_SESSION['DE_Money_Out']); $_SESSION["DE_DD_Entry"] = $_POST['DD_Entry']; $_SESSION["DE_MM_Entry"] = $_POST['MM_Entry'];
  26. Honestly, the comments give a good overview of the whole thing. Did you have any specific questions about what they said? There's a big class containing all the code, an inner class that handles just the animation portion, and a static main. The big class's start() initializes things and then tells JavaFX to start executing the animation. The animation happens by executing handle() at ~60 calls/second (aka Hz). The code for handle, which is the only method in that class, calculates a couple X,Y coordinates and draws then a line on the canvas...
  27. package RandomWalk; import javafx.animation.AnimationTimer; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; //========================================================================================== //A class that uses JavaFX must extend javafx.application.Application //========================================================================================== public class JavafxRandomWalk extends Application { private static final int DRAW_WIDTH = 600; private static final int DRAW_HEIGHT = 600; private static final double NANO = 0.000000001; private Animation myAnimation; //Reference to an inner class that gets called at 60Hz private Canvas canvas; //Area on which to draw graphics items. private GraphicsContext gtx; //Drawing methods for the Canvas. private int x=DRAW_WIDTH/2; private int y=DRAW_HEIGHT/2; private int frameNumber = 0; private int distance = 1; private double timeOfLastDraw = 0; @Override //========================================================================= //start(Stage stage) //This is a JavaFX callback method. It is called by JavaFX after JavaFX // has created a window. The parameter, Stage stage, is a pointer to // the part of the window where the programmer can add widgets, such as // buttons, menus and canvases. //========================================================================= public void start(Stage stage) throws Exception { //Set the window's title in its title bar. stage.setTitle("Random Walk"); //A Canvas is an area that supports graphics drawing //To get this to work, there is a hierarchy of objects that is needed: // 1) The canvas is placed in a new instance of VBox. // 2) The instance of VBox is placed in a new instance of Scene. // 3) The instance of Scene is placed in the given instance of Stage. canvas = new Canvas(DRAW_WIDTH, DRAW_HEIGHT); //A GraphicsContext, gtx, is a pointer to a set of drawing tools // that can be performed on an instance of a Canvas, canvas. gtx = canvas.getGraphicsContext2D(); //All lines drawn after this setLineWidth(3) is called will have a // width of 3 pixels. This effect lines drawn until changed by another // call to setLineWidth(int width). gtx.setLineWidth(1); gtx.setFill(Color.DEEPSKYBLUE); //gtx.fillRect(left, top, width, height) will fill an axis-aligned rectangular // area with the current fill color. The rectangle is defined by the 4 // parameters: // left (x-coordinate in pixels of the left corner of the rectangle). // top (y-coordinate in pixels of the top corner of the rectangle). // width (width in pixels of the rectangle). // height (height in pixels of the rectangle). gtx.fillRect(0, 0, DRAW_WIDTH, DRAW_HEIGHT); VBox vBox = new VBox(); vBox.getChildren().addAll(canvas); Scene scene = new Scene(vBox, DRAW_WIDTH, DRAW_HEIGHT); stage.setScene(scene); stage.show(); //At this point, the an empty, white window is created. //Now, we create an new AnimationTimer and start it running. // this will tell JavaFX to call the AnimationTimer's handle method // at a rate of 60 times per second. //Each time the handle method is called, a new image can be drawn. //Each new image is called a "frame". Thus, this will **attempt** to // draw at 60 frames per second (fps). myAnimation = new Animation(); myAnimation.start(); } //=========================================================================================== // Animation is an inner class of our JavafxRandomBox class. // Animation is an "inner class" because it is inside the JavafxRandomBox class. // Since Animation extends AnimationTimer, the Animation class MUST implement // public void handle(long now), a callback method that is called by JavaFX at 60Hz. //=========================================================================================== class Animation extends AnimationTimer { @Override //========================================================================================= //handel is a callback method called by JavaFX at 60Hz. // now - The timestamp of the current frame given in nanoseconds. // This number is not useful by itself, but when subtracted to from another saved now // gives the difference in nanoseconds between the two times. //========================================================================================= public void handle(long now) { double currentTimeInSec = now*NANO; if (currentTimeInSec - timeOfLastDraw < 0.005) return; timeOfLastDraw = currentTimeInSec; gtx.setLineWidth(1); gtx.setStroke(Color.BLACK); int x2 = x; int y2 = y; double r = Math.random(); // [0, 1) if (r < 0.25) { x2 = x + distance; } else if (r < 0.5) { y2 = y - distance; } else if (r < 0.75) { x2 = x - distance; } else { y2 = y + distance; } gtx.strokeLine(x,y, x2, y2); x = x2; y = y2; frameNumber++; } } //This bracket ends Animation, the inner class. //=========================================================================================== // Every Java program must have public static void main(String[] args). // In a JavaFX program, main starts JavaFX by calling: // javafx.application.Application.launch(String[] args) //=========================================================================================== public static void main(String[] args) { launch(args); } } This code simulates self avoiding random walk in java. My concern is not the logic of the program, but the structure of the program. And the javafx way of displaying stuffs on screen. It just does not come to me instantly or lately
  28. That is just another way of saying you can create a responsive web application: viewport
  29. Can you please mention which language, framework required to use viewport? What is the exact process of using viewport??
  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.