-
Posts
4,207 -
Joined
-
Last visited
-
Days Won
209
Everything posted by Jacques1
-
The username should be indexed. Otherwise the database system has to perform a full table scan whenever somebody logs in. In fact, it sounds rather silly to omit the index and then use LIMIT 1 to “improve performance”. If you care about performance, use an index. This will be much, much more effective than any LIMIT hack.
-
Console I know, but the JSON data is HTML-escaped, so there are HTML entities which need to be translated. It looks like this is actually done by textContent, though. So either use textContent or the text() method of jQuery.
-
Sticky form help; PHP code is showing in HTML form
Jacques1 replied to ctapp's topic in PHP Coding Help
Open Firebug (or whatever developer tools you're using), remove one of the fields and submit the form. Without isset(), you'll get a stream of random errors messages and possibly all kinds of unwanted side-effects. The same can be achieved by sending an empty POST request with cURL. If the form is generated dynamically (which isn't the case here), missing fields can also be caused by template bugs or program errors. Don't make any assumptions about the input. -
Use console.log() instead of alert() for debugging. It will give you a detailed variable description in the JavaScript console. What's the “before” and the “after” now? How often is the atts[key] = membs[key]["name"]; line executed? Exactly once or in a loop? What are console.log(key) and console.log(membs[key]["name"]) ? The exact code would also be helpful. // And don't use innerText, because that's a nonstadard attribute which is actually wrong in this context. Use innerHTML.
-
Sticky form help; PHP code is showing in HTML form
Jacques1 replied to ctapp's topic in PHP Coding Help
You're hoping that all fields will be set, but that doesn't mean the client will do you that favor. And there can always be bugs in our own code (at least when it's more complex). One of the first things my teacher would have done is remove a field and see what happens. If the program starts spilling random PHP errors messages, then the underlying code is bad, because it cannot handle this situation. Sure, we could again hope that the teacher is incompetent and doesn't understand testing, but I wouldn't recommend that, especially when writing proper code only requires a few more keystrokes. I'd make the code as robust as possible (like QuickOldCar did). -
Sticky form help; PHP code is showing in HTML form
Jacques1 replied to ctapp's topic in PHP Coding Help
How is this supposed to work? The POST check doesn't tell you anything except that the client has made a POST request. So I'm afraid you can't leave out 50% of the code. Sure, you could just hope that nobody will recognize the lack of error checking, but I wouldn't recommend that, not even for a school project. Any halfway competent teacher will test the code with invalid input, and if that results in a stream of PHP errors, the OP has a problem. -
Sticky form help; PHP code is showing in HTML form
Jacques1 replied to ctapp's topic in PHP Coding Help
Each function has its own scope, which means it cannot “see” variables from the surrounding code (with a few exceptions), and the surrounding code cannot “see” the function's local variables. In other words, all those variables in your validation() function are killed as soon as the function returns, and the confirmation() function has no chance of ever getting the variable values. This is why functions have parameters and a return value. The parameters are for the input, the return value is for the output. In your case, the validation() function should return true if the validation was successful and false otherwise. Then the surrounding code can either display the “Thanks for submitting” message or not. The confirmation() function is unnecessary. -
Nobody said anything about PHP 7. PHP 5.6 is still actively supported and will reach end-of-life in late 2018. Sticking to PHP 5.2 is not an option and downright suicidal, because it was abandoned back in 2010/2011 and hasn't received any security fixes ever since. Even the dumbest company should understand that. The only exception would be that you get regular security updates through some kind of extended-support operation system (RHEL, CentOS, whatever).
-
How To Add Random Number Query String Within PHP Array Links?
Jacques1 replied to RonnieMac's topic in PHP Coding Help
The point of the query is to “fake” a new URL so that the browser won't use cached data. From the browser's perspective, /some/file?foo and /some/file?bar are two different entities, even when the query doesn't actually do anything. I'm fairly sure none of this makes any sense in the concrete case, but the OP insists on it. -
How To Add Random Number Query String Within PHP Array Links?
Jacques1 replied to RonnieMac's topic in PHP Coding Help
Why do you even want to prevent caching altogether? If you merely need the ability to change the images behind the URLs, simply store a version number for each image and append it to the URL: https://www.yoursite.com/gallery/image-1.png?v6 Then you won't be wasting traffic for data which can be cached. -
SQLSTATE[42000]: Syntax error or access violation: 1064
Jacques1 replied to lovephp's topic in MySQL Help
No, bro, I will not fix your code. I told you what's wrong and what to check, the rest is your job. You've been using PHP for at least 2 years now. It's time that you learn to think for yourself and solve your own problems, because there won't always be somebody to spoon-feed you. -
SQLSTATE[42000]: Syntax error or access violation: 1064
Jacques1 replied to lovephp's topic in MySQL Help
First off: Get rid of this try-catch nonsense. Then you'll see a proper error message with the actual location of the problem, and your production server won't clutter your site with PHP errors. Appearently your script has calculated a negative offset (-5). You can't have that in MySQL. You get a negative offset when, for example, there are no articles. The script isn't capable of handling this case. -
different div is result has value more than 1
Jacques1 replied to lovephp's topic in PHP Coding Help
We have CSS for this: :first-child -
How would I randomly get both values from this array?
Jacques1 replied to cloudll's topic in PHP Coding Help
So you want to select one of the three sub-arrays and then get both items of that array? <?php $strange_number_pairs = [ [200, 200], [250, 250], [425, 425], ]; $rand_pair = $strange_number_pairs[mt_rand(0, count($strange_number_pairs) - 1)]; echo $rand_pair[0].'<br>'.$rand_pair[1]; Of course I have no idea what those numbers mean and why you would store the same number twice. -
The problem is actually everywhere in your code. You cannot stuff random PHP values into HTML markup and expect this to work. All you'll get is plently of cross-site scripting vulnerabilities and other defects (like the one you happened to notice). Creating dynamic HTML must be done very carefully. The standard approach (which isn't always sufficient) is to HTML-escape the PHP value and always quote HTML attributes: function html_escape($unsafe_data, $encoding) { return htmlspecialchars($unsafe_data, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, $encoding); } $unsafe_input = 'test test'; // Wrong: code is vulnerable to XSS attacks and cannot handle spaces echo "<option value={$unsafe_input}>{$unsafe_input}</option>"; // Correct: escaped input, quoted attribute echo '<option value="'.html_escape($unsafe_input, 'UTF-8').'">'.html_escape($unsafe_input, 'UTF-8').'</option>'; Since manual escaping is extremely cumbersome, and since most programmers just cannot do it, I recommend you use a template engine like Twig which does it for you (and will also massively improve your overall code quality).
-
I understand that the field is required and must be validated, but deleting(!) the user input and not letting the user out of the field until they've gotten it right borders on violence. I've never seen a form do anything like this, not even when the data is very critical. Yes, forms may validate the input back and forth, but they don't punish the user for filling out the fields in the “wrong” order. As long as they don't submit the form, users are free to do whatever they want. If you insist on breaking this contract, you'll have to rely on hacks (like watching every keystroke and suppressing tabs).
-
Sticky form help; PHP code is showing in HTML form
Jacques1 replied to ctapp's topic in PHP Coding Help
You're trying to switch into PHP mode within a PHP string. This cannot be done, because you already are in PHP mode. A quick fix would be to either insert the variables directly into a double-quoted(!) string or use string concatenation: <?php $name = 'ctapp'; echo "Hello {$name}, how are you?<br>"; // or: echo 'Hello '.$name.', how are you?<br>'; The code in general is very difficult to read, because you're constantly switchting between PHP code and HTML markup. To make the script more readable (for others as well as yourself), keep things separate: Move the PHP code to the top and the HTML to the bottom: <?php // code goes here $name = 'ctapp'; // HTML below: ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title>Page title</title> </head> <body> <p>Hello <?= $name ?>, how are you?</p> </body> </html> The <?= ... ?> syntax is a shortcut for <?php echo ... ?>. -
Don't mess with core features of the browser. Many people rely heavily on tab navigation, especially when they're visually impaired. If your JavaScript silently swallows the key press, that's a problem. It's also the user's decision when to fill out which field. Simply mark the input as invalid and let them decide when they fix it.
-
--routines
-
For now, I'd stick to plain PDO and read the connection settings from an external configuration file while the application is initialized. You can then pass the PDO instance to the controller (or whatever part of the application is responsible for handling the current request). Plain PDO is far from perfect, because it can't be used with dependency injection and makes testing very difficult. But it's the easiest solution.
-
First off: Why do you want to capture fatal errors? When the application code is fudged up, there's obviously nothing you could do about that at runtime. Or do you just want to display a user-friendly error message instead of the infamous blank page? Then you should set up a custom error page in the webserver configuration. You cannot catch compile-time errors (like a duplicate declaration) by registering an error handler at runtime, because that code never gets executed. It's theoretically possible to register the handler before the script is compiled (e. g. through an auto-prependend file). But there's no reason to do that except for very exotic scenarios.
-
The user agent is commonly used as a “device” identifier. Or the IP address.
-
You can use any of those. The “&&” variant takes advantage of short-circuit evaluation: If $passwordHash is false, the whole boolean operation immediately evaluates to false. The password_verify() part is completely ignored, because it's not needed to determine the result. This is a common pattern. Just using password_verify() without the pre-check would be a bad idea, though, because then you rely on the function to behave “nicely” in case of invalid arguments. This is not guarenteed. You might get a warning or an exception or even trigger a bug. I wouldn't want to try that out in security-related code.
-
If the user doesn't exist at all, fetchColumn() will return false. It wouldn't make sense to pass this value as a “hash” to password_verify(). To prevent this situation, there's a pre-check if $passwordHash is even valid. This could also be written with an if statement, of course: if ($passwordHash) { $valid = password_verify($password, $passwordHash); } else { $valid = false; } return $valid;
-
Looks good. There's a problem with the return value of the check() method, though: If the username or password are incorrect, the method doesn't return anything (i. e. null), otherwise it returns the object instance. This violates the specification and is also very confusing. The method should return an actual boolean: $passwordHashStmt = $this->pdo->prepare(' SELECT password FROM users WHERE username = ? '); $passwordHashStmt->execute([ $username ]); $passwordHash = $passwordHashStmt->fetchColumn(); return $passwordHash && password_verify($password, $passwordHash); Logging out is a session feature, so it belongs into a separate Session class.