Jump to content

requinix

Administrators
  • Posts

    15,229
  • Joined

  • Last visited

  • Days Won

    427

Everything posted by requinix

  1. It's not just a coding style issue. isset($_POST["button"]) and $_SERVER["REQUEST_METHOD"] == "POST" do two different things: one checks for the presence of a field/button in POSTed data, and the other checks simply that the request was sent using the POST method (which means it likely contains a request body). There's some overlap as to which is more appropriate for a given situation, but neither one nor the other is strictly "better". In the case of a form with only one action, you know logically that if the form was submitted then it is supposed to perform that one action. The presence of a button tells you that the form was submitted using that button, but technically speaking you don't need to require that the button was used. If the form was submitted via AJAX then the button is likely not present, yet the form should still be processed normally because you care that the form was submitted at all. In the case of a form with multiple actions, such as Save or Cancel (and you choose to handle Cancel as an action rather than implement it using, eg, a link back to the previous page), then obviously you need some way to determine which action was requested. Looking at the REQUEST_METHOD will not be enough for that, and named buttons are the easiest solution. You can still do the former as a sort of sanity check, but like I said before I believe $_POST is only filled for POST methods so the presence of a button automatically implies a POST action; missing both buttons means you can't tell what action to perform and you're free to do whatever you want (like redisplay the form). The REQUEST_METHOD matters a lot more with a RESTful API design. It's quite likely, and arguably it should be, that a particular URI will receive multiple actions determined according to the REQUEST_METHOD. For example, a POST to /user/1234 is a different action than a PUT to /user/1234 and most certainly different from a GET. Here there is no submit button, but the "multiple actions" thing still applies: the "page" can perform multiple actions and you determine which by looking at the REQUEST_METHOD, and simply testing for a $_POST field is not appropriate. That overlaps with regular webpages, where you have one serving both as the location of the form as well as the code that processes the form. If you don't look for a submit button then you definitely need to know whether you're supposed to display the form (GET) or process data (POST). Your "design style" argument raises a good point too: if you need to test for a field in $_POST then there's no need for an additional check of the REQUEST_METHOD. It goes towards reducing code complexity. if ($_SERVER["REQUEST_METHOD"] == "POST") { if (isset($_POST["save"])) { // ... } else if (isset($_POST["cancel"])) { // ... } else { // redisplay form } } else { // redisplay form } Given that "$_POST is only populated for POST requests", the code can be reduced to if (isset($_POST["save"]) /* which implies REQUEST_METHOD=POST */) { // ... } else if (isset($_POST["cancel"]) /* which implies REQUEST_METHOD=POST */) { // ... } else if ($_SERVER["REQUEST_METHOD"] == "POST") { // redisplay form } else { // redisplay form } and then to the obvious conclusion of if (isset($_POST["save"]) /* which implies REQUEST_METHOD=POST */) { // ... } else if (isset($_POST["cancel"]) /* which implies REQUEST_METHOD=POST */) { // ... } else { // redisplay form } Thus there is no need to test the REQUEST_METHOD.
  2. "Should" is debatable. IIRC $_POST will only be filled for POST methods, so if the button is present then you know the form was POSTed. What I think he's getting at is that you can not check for buttons (which requires naming the button) and look for a POST method instead. It's also possible to AJAX a form without including a submit button, so testing the request method is immediately compatible with that.
  3. A refresh alone will not make your site stop working. Too many people refreshing at once, that could be part of it: each refresh is just another request to the server, so if you figure there are 10 actual people visiting your site every minute then really it's effectively 20 (each person loads the page normally at first then it refreshes a minute later).
  4. Okay, that makes things a little bit clearer, but... What's your code?
  5. What? What result? Turn what red? Replace what text with HTML?
  6. $value is never an array. It's always a SimpleXMLElement object. Even if the XML node does not have children. Try count()ing to see how many children the element has.
  7. Oh, you put the form in the email? As HPierce said that's definitely not a portable solution, but I agree that it could be the cause of the problem. I also saw Content-Type mentioned somewhere as a potential source of the problem. Try removing that. But you really should get the form out of the email. Typically this means a link, probably styled as a button, going to a webpage with a real form. I definitely recommend that approach.
  8. Is it the actual string "net err cache miss" and not like "net::ERR_CACHE_MISS"? And you say the rest of the process is working fine? As you've probably seen it's apparently an issue with Chrome, but one that should have been resolved in 2014 or so. What version of the browser is the phone using, and are there any updates for it?
  9. The complex syntax in $url2 is more or less universally recommended.
  10. Just an example. It just clicked with me what the code is doing and that it has to do with those point whatever things the two types and the composite/custom one stuff. Looking up the custom stuff probably involves a database hit, in which case there's no real point making the procedure more complicated just to make the PHP code non-recursive. So forget all that stuff I said.
  11. You could build a key like "10,30" if you wanted. You're just using it to determine uniqueness while processing data - that's not quite the same as trying to generically represent a composite key in code. Myself, since there's only two pieces to the key I might go for nested arrays. array(10 => array(30 => array(/* 0, 3, N-1 */)))
  12. Yeah, but do they have any reasons other than "because they can be misused"? Not really. Static variables, global variables, singletons... They can also be used badly, and sometimes they kinda lend themselves to it, but there are good uses for them too. Not if you consider the variable to be part of the "unit". And in this case, before and after the first non-recursive call to that method the static variable should be the same; now it's a bit harder to test that specific aspect, but testing the method as a whole (or other units which use that method) covers it too. The method is unaffected. The "static" in the term "static variable" (in this context) has nothing to do with the "static" that comes with static methods. It just means that the variable persists between calls to the function. Basically, yeah. Here's how the code looks the way I do it: $stack = array(array(/* initial state */)); while ($stack) { $state = array_shift($stack); // pop off $stack[0] // do whatever $state tells you to do // if you need to add more states to the stack then $stack = array_merge($array_of_new_states, $stack); // prepend }Having had my morning coffee* I realized this isn't hard to do this to implement a linear version of the recursive Fibonacci algorithm. $accum is equivalent to a return value from a recursive call and $stack represents the nth Fibonacci numbers that need to be calculated.You can see the recursive structure represented here: the check for $n is the base case and the merging into $stack is the recursion. function fibonacci($n) { $accum = 0; $stack = array($n); echo "stack = ", json_encode($stack), "\n"; while ($stack) { $n = array_shift($stack); if ($n <= 2) { $accum += 1; echo "accum = {$accum}\n"; } else { $stack = array_merge(array($n - 1, $n - 2), $stack); echo "stack = ", json_encode($stack), "\n"; } } echo "final result: accum = {$accum}\n"; } fibonacci(7); stack = [7] stack = [6,5] stack = [5,4,5] stack = [4,3,4,5] stack = [3,2,3,4,5] stack = [2,1,2,3,4,5] accum = 1 accum = 2 accum = 3 stack = [2,1,4,5] accum = 4 accum = 5 stack = [3,2,5] stack = [2,1,2,5] accum = 6 accum = 7 accum = 8 stack = [4,3] stack = [3,2,3] stack = [2,1,2,3] accum = 9 accum = 10 accum = 11 stack = [2,1] accum = 12 accum = 13 final result: accum = 13* Hot chocolate.
  13. Why not? I would have mentioned it. As long as you manage its state and value correctly - eg, adding to it when going deeper and removing from it when returning - you should be fine. But see my fourth thing below. I wouldn't do it for a public or protected method, but for a private method that can only be called from within this class it's not that bad an option. Use defaults so the caller doesn't have to care. I wouldn't want to do that for myself: I don't like the idea of a class specifically designed to have only one (external) method. However if it turns out to be the most reasonable solution, considering things like clarity and maintainability, then... eh. Without me going through the code to confirm, it may be possible to implement this non-recursively. The basic approach to that is to use a loop with an array as a state stack: add state onto it for the next iteration to process, remove when finished. For example... I don't know, I'm blanking on a simple example of a situation where the average person uses recursion that could instead be implemented with a stack.
  14. A form field will be sent even if it is not visible to the user. Because you have the inputs named "link" you will always receive something like link=hariciLink&link=black&link=or link=dahiliLink&link=black&link=Örnek:%20http://www.websayfam.comThe hariciLink value overwrites the dahiliLink value because it is later in the form. Easy solution: don't name everything "link". Very easy. Also a good idea. Otherwise you have to worry about enabling and disabling inputs so that only the right ones get submitted with the form. <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="hariciLink"){ $(".box").not(".hariciLink").hide(); $(".hariciLink").fadeIn(300); } if($(this).attr("value")=="dahiliLink"){ $(".box").not(".dahiliLink").hide(); $(".dahiliLink").fadeIn(300); } }); }); </script>That code is what you use to show and hide the different link inputs. To make it enable/disable you can <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ if($(this).attr("value")=="hariciLink"){ $(".box").not(".hariciLink").hide(); $(".box").not(".hariciLink").find(":input").prop("disabled", true); $(".hariciLink :input").prop("disabled", false); $(".hariciLink").fadeIn(300); } if($(this).attr("value")=="dahiliLink"){ $(".box").not(".dahiliLink").hide(); $(".box").not(".dahiliLink").find(":input").prop("disabled", true); $(".dahiliLink :input").prop("disabled", false); $(".dahiliLink").fadeIn(300); } }); }); </script>or simply <script type="text/javascript"> $(document).ready(function(){ $('input[type="radio"]').click(function(){ $(".box").not("." + this.value) .hide() .find(":input").prop("disabled", true) ; $("." + this.value + " :input").prop("disabled", false) $("." + this.value).fadeIn(300); }); }); </script>Keep in mind that enabling/disabling the inputs comes with a visual change (stuff turns gray) so you should enable inputs before showing them and disable inputs after hiding them; .hide() is instant but if you changed to .fadeOut() then you'd have to disable after the fade out animation finished.
  15. Personally, I'm still a fan of using Wireshark to inspect the request packet so you can tell what's wrong with it.
  16. Short answer: no. Shopping carts work by using cookies and your site cannot set a cookie for a different site. Longer answer: It could be possible if a particular website had their "add item to cart" button thing programmed in a way that it really shouldn't have been. Which is by using a link to a page like "/addtocart.php?item=4252603765" that you could copy/paste into another computer and have work. So no.
  17. Whether you use exceptions or not has nothing to do with where data comes from. It's about the architecture of the code and execution flow of the application. I strayed a bit from the exception stuff because the sun is coming up and I'm tired and I ramble when I'm tired. - I'm feeling meh about your use of exceptions here. "getValidatedData" sounds like it's doing two jobs: validation and getting data. Which is really only one job because you told it the data to begin with. Instead I would use a method to validate what's in $_POST and return a list of problems (if any). - USERException, which should really be called UserException, which should really be called something more useful than that, would go in its own file to be autoloaded. Like every other class. - WhateverItGetsCalledException would benefit from storing which field was invalid too. - Validate class, which again should be called something more useful, shouldn't be a class if all you're doing is putting one method on it like that. If you're not going to reuse the logic anywhere then it should just go alongside the rest of the input processing code. If you would reuse it then it would be better served as just a regular function - there is nothing "object oriented" about it so it doesn't make sense as a class. If you would reuse it as a sort of validator that might get passed around to other places in an arbitrary manner that isn't hard-coded into whatever processing logic is at work, then it should observe some sort of interface and you better have at least two more classes like it to do other types of validation. - Throwing an exception as a way of returning error information is... less than optimal, but IMO acceptable. It would make more sense if you skipped the validation at this point, blindly passed it along to whatever will perform the action (the //insert record), and that performs the validation and throws the exception if invalid. - Exceptions are about exceptional behavior, that is to say behavior that is unexpected or abnormal or otherwise not what typically should happen when the code executes. Validation is a normal step, getting errors is normal enough to not be considered "unexpected" or "abnormal", and so I wouldn't use exceptions for that. A simple "getValidationErrors(array $data): array" would suffice. - So then if //insert record calls the validation, what happens is the validation returns normally (validation failure is not unexpected behavior) whatever information to it, and then if there's a validation error it throws the exception itself (as the failure is "not what typically should happen"). Again, there's wiggle room there about whether exceptions could be considered appropriate or not.
  18. He's clearly not going to be surfing porn sites or downloading torrents with it. Sitting behind a proper firewall and without my grandmother using it to download wallpapers of cats, it'll be fine.
  19. Short of learning the packet structure, I'd fire up Wireshark (on a modern machine, of course) and run that code to see exactly how the packet is being sent. And compare with what something like nslookup or dig does. Because it seems to be parsing responses correctly, which means the problem must be in the request.
  20. Chaining is a matter for coding style. Some people like it. Some people don't. You need to decide whether you like it or not and then write your code consistently accordingly. As for returning an object/array: It depends. Thus why abstract examples aren't very helpful for us. If getStuff() does not mutate (alter) the object and really does have multiple values to return then sure, return an object/array with the values. If setStuff() does mutate the object and a/b/c are all attributes of the object which you may want to access then it makes sense to have getter functionality, and whether that's ->a or getA() is another matter for coding style.
  21. public function newPdfPedido($atividade, $id_turma, $local, $dataAula, $inicio, $fim, $fundamentacao, $observacoes, $id_professor){newPdfPedido() has 9 parameters. You need to pass 9 values to the function.
  22. Why the heck would someone try to manually write and read DNS UDP packets by hand when there's already a perfectly good function to do it? Don't bother with that function and just use getmxrr like a sane person. As for the explanation, I don't know. There's a chr(15) in there which could represent an MX query, but my first guess would have been that the query didn't have it.
  23. It would match fine if you didn't use the ^ and $ anchors that force the regex to test the entire string at once. And by the way, a slightly cleaner version: #/([ahi]?)\w+)#- # delimiters so you don't have to escape the /s (you can use just about anything as a delimiter and / # ! ~ are the most common)- [ahi] so you don't need | alternation - [ahi]? inside the capturing group so it always captures something (even if it is just an empty string) - \w is equivalent to [A-Za-z0-9_]
  24. But what about a case like /search/xbox[/category/:category[/subcategory/:subcategory]]This becomes a problem of balanced brackets - simply checking for [] on either side isn't enough. Two suggestions for how to handle this: a) Don't allow optional variables and force the user to make additional routes. I've done this and it helps if you can give the user a way to configure routing in a recursive way, like <route path="/search/xbox"> route information here... <route path="/category/:category"> additional overriding information here... </route> </route>The routing system matches as much as it can, gathers all the information along the way, and decides what to do. You could also support <route path="/search"> route information... <route path="/xbox"> route information... <route path="/category/:category"> route information... </route> </route> </route>where the route information gathered for just "/search" isn't enough to serve a page and thus results in some 404-type behavior. b) Use regular expressions to turn the route pattern into another regular expression. I've done this one too. With your simple example you could have something like $route = "/search/xbox[/category/:category]"; // escape any regex metacharacters already present $regex = preg_quote($route, '#'); // if using # as the pattern delimiters // note that it will escape any of . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - // or you can make this much simpler by not escaping characters and trusting the user to write mostly-regex-safe patterns // transform escaped brackets $regex = preg_replace('/\\\\\[/', '(?:', $regex); $regex = preg_replace('/\\\\\]/', ')?', $regex); // transform variables $regex = preg_replace('/\\\\\w+)/', '(?P<$1>[^/]+)', $regex); // replace [^/]+ with whatever you think matches a variable var_dump($regex); // "/search/xbox(?:/category/(?P<category>[^/]+))?"then if (preg_match('#^' . $regex . '$#', $url, $matches)) {gives you stuff like Array ( [0] => /search/xbox ) Array ( [0] => /search/xbox/category/consoles [category] => consoles [1] => consoles )The route gets [0] for the full match, and both named (useful) and numeric (useless) captures matching the assorted variables (if present). Why did I just say all that? Because at 4:30am I'm not seeing a "nice" way of solving your particular problem of dealing with the []s.
  25. So what has changed since last time? I thought this was from a URI, but if that's true then where are these brackets coming from?
×
×
  • 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.