Jump to content

Jacques1

Members
  • Posts

    4,207
  • Joined

  • Last visited

  • Days Won

    209

Everything posted by Jacques1

  1. This is nonsensical. What are you trying to do? Is this some kind of homegrown CAPTCHA to stop bots? Then you should instead use a professional CAPTCHA (like Google's reCAPTCHA) together with PHP sessions. The session will keep the user “logged in” after they've solved the CAPTCHA. Or are you trying to authenticate users? Then you should instead implement a proper authentication system (e. g. password-based Basic Authentication). Whitelisting client IPs is usually a very bad idea, especially when you just pile them up in some poor man's database. Client IPs are constantly reused and shared, sometimes among thousands of unrelated users. If you keep adding those IPs to your “whitelist”, you'll quickly end up whitelisting half of the Internet population.
  2. If this library sucks, just use a different one. I've tried skleeschulte/php-base32, and it seems to work fine: <?php require_once __DIR__.'/Base32.php'; use SKleeschulte\Base32; $rawInput = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM); $encoded = Base32::encodeByteStrToCrockford($rawInput); echo "encoded: $encoded<br>"; $decoded = Base32::decodeCrockfordToByteStr($encoded); echo ($decoded === $rawInput) ? 'decoding successful' : 'decoding failed';
  3. Why on earth do you want non-ASCII filenames, anyway? This is user-hostile (most people don't even have that character on their keyboard), it's obviously a pain to implement (at least in your environment), and it essentially limits your website to a small geographical area forever. The point of a URL is to uniquely and permanently(!) identify a resource. That means it's definitely not the right place to play around with fancy characters.
  4. Getting strong random numbers is actually hard, especially when you're dealing with different operating systems. So for general applications which need to work everywhere it makes a lot of sense to pick a simpler, time-based approach whenever possible. Why UUIDs? Because it's a standardized format which a lot of applications can handle out-of-the-box. In your specific case, you do have access to a strong random number generator, so by all means, use it.
  5. Unpredictability isn't always a requirement, so non-secure random numbers like UUIDs do make sense in some cases. There are several libraries on GitHub like this one.
  6. UUIDs are definitely no safe choice when you need unpredictability. While a particular implementation might happen to use strong random numbers, it's also possible to implement UUIDs with simple time-based numbers. If you want human-friendly random numbers, consider using Crockford's Base32 encoding. It's optimized for readability (ambiguous symbols are already excluded) and relatively compact compared to hexadecimal encoding. A 128-bit random number fits into a 26-character Base32 string. You may append a check symbol for error detection, and of course can add hyphens to further increase readability. By the way, I'd use the new PHP 7 CSPRNG extension instead of Mcrypt to generate random numbers. If you don't have PHP 7 yet, there are several compatibility libraries. There's nothing wrong with mcrypt_create_iv(), but the underlying Mcrypt library has been abandoned back in 2007, and the PHP core developers have already considered removing the extension.
  7. No, it's not fine, because mysql_real_escape_string() is for quoted SQL string literals only (hence the name). It's completely useless for numbers. intval() is likely to truncate the number if it's too big to be represented by a PHP integer. As multiple people have said multiple times already: Use a prepared statement. That's the only sensible solution.
  8. You don't seem to understand that HTML markup is in fact output. So you have output all over the place, starting at line 1. The fact that PHP reports the first tag after the markup is just an implementation detail. Long story short: Your code is definitely broken. While it's theoretically possible to circumvent the issue with output buffering (which is what your test server does), I strongly recommend against that. Get rid of this awful spaghetti code and write your scripts properly, that is, separate the logic from the visuals. The best way to enforce clean separation is to use an actual template language like Twig. Or, if you insist on using PHP as a poor man's template engine, put the logic on top and keep the markup at the bottom.
  9. You can enable global autoescaping in the Twig environment options.
  10. To be honest, both examples are cumbersome and ugly. And that's not even usable code, because you've forgotten the HTML-escaping. The real code would look something like this: <div><?= htmlspecialchars($some_value, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8'); ?></div> And that's just one variable in one HTML element. When you're dealing with more complex output, you'll quickly end up with this terrible Wordpress-style spaghetti code. Personally, I very much prefer using a proper template engine like Twig or Smarty: <div>{{ some_value }}</div> This is clearly much more readable. And since Twig automatically escapes the output, you won't run into cross-site scripting vulnerabilities all the time.
  11. I strongly recommend that you stop writing this PHPHTMLCSSJavaScript mishmash. It will lead to errors and cross-site scripting vulnerabilities all over the place, and you'll quickly end up with an unreadable, unmaintainable mess of spaghetti code. Keep your languages separate. Style declarations belong into external CSS files, and JavaScript code belongs into external JavaScript files. Then use Ajax to load server-provided data (like the content of PHP variables) into your JavaScript functions. Alternatively, you can embed the data into a hidden HTML element and then parse it with JavaScript. In any case: Do not echo your PHP variables directly into a JavaScript context.
  12. What's wrong with this forum?
  13. I definitely would not try to fix this with some SQL hack job. A VARCHAR can contain absolutely everything, and nobody knows if the dates have been validated properly, so simply assuming that the original data is alright seems overly optimistic. I'd do this with a script which actually parses the original dates, validates them rigorously and then either inserts the reformatted date into the database or reports the input for manual correction. If it turns out that all dates could be reformatted automatically, that's great. But I wouldn't rely on it. Also note that the reliability of STR_TO_DATE() is dependend on the MySQL configuration. In less strict SQL modes, nonsense dates like “2015-02-31” are considered valid and will be accepted with no warning whatsoever.
  14. What are you even trying to do, lewashby? What's the purpose of this class? Besides the fact that almost everything about it is technically wrong (as already explained), what's the point of replacing one simple line of code (new PDO...) with 40 lines of code? Even worse: Your class cannot do anything, because it doesn't have any useful methods. All you can do with a Connection instance is somehow grab the underlying PDO connection and throw away the instance. I strongly recommend that you first come up with a sensible concept and then do the implemention. If you just want to pass a bunch of constants to the PDO constructor, you should use a plain function instead of this pseudo-OOP: <?php // put those constants into a separate configuration script, if you want const DB_HOST = 'localhost'; const DB_USER = 'the_username'; const DB_PASSWORD = 'the_password'; const DB_NAME = 'the_db_name'; const DB_CHARSET = 'utf8'; function connectToDatabase() { return new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.';charset='.DB_CHARSET, DB_USER, DB_PASSWORD, [ PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, ]); }
  15. Yes, you can theoretically just assign new values to the variables, since they're passed by reference. However, it's much, much clearer and less error-prone to explicitly bind each value to the prepared statement.
  16. No. I mean that you should create the prepared statement outside of the loop and then execute it with different values inside the loop: $configurationUpdateStmt = $db->prepare(' UPDATE config SET value = :value WHERE config = :key '); foreach ($post as $configKey => $configValue) { $configurationUpdateStmt->bindParam('key', $configKey, PDO::PARAM_STR); $configurationUpdateStmt->bindParam('value', $configValue, PDO::PARAM_STR); $configurationUpdateStmt->execute(); }
  17. You don't need any of this. When the script is terminated, PHP automatically closes the connection and frees all memory. By the way, you should move the prepare() call before the foreach loop. Prepared statements can be reused (that's pretty much the whole point), so you should create it once and then use it for every configuration item.
  18. Frankly, I doubt that it's a good idea to “disassemble” a full-blown web application in the hopes of learning web development from it. Modern applications often hide the inner workings behind a thick layer of fancy techniques (URL rewrites, asynchronous requests etc.), making it very difficult to understand what's going on. Even actual programmers would struggle with this, and the learning value is very low. In the end, you may know a bit about HTML5 and hashbang URLs (the #!m=Login stuff), but that doesn't really get you any closer to becoming a developer. The best approach is still learning-by-doing. Write your own application, preferably one that's actually useful to you. This allows you to learn the techniques in a much more practical and pragmatic way. Instead of wondering what the hell hashbang URLs are for, you'll be faced with concrete problems and concrete solutions.
  19. This also means you can get rid of the weird filter gymnastics, because what matters is whether the checkbox field has been sent or not. The actual value is entirely irrelevant and should simply be discarded. The PHP filters are generally very questionable and tend to damage your data rather than providing security. For example, the input “I <3 PHP” will be truncated to “I ”, because the “<” is misinterpreted as the beginning of an HTML tag (which is of course complete nonsense). Don't use the filter_* functions unless you know exactly what they're doing and why you need them. I also don't think that “yes” and “no” are appropriate configuration values. If you insist on stuffing everything into a text column, you should at least choose some kind of canonical representation so that you don't end up with dozens of variations (“yes”/“no” vs. “on”/“off” vs. “yea”/“nay” ...). Booleans are commonly represented by “true” and “false”.
  20. PHP 5.2 reached end of life back in 2011 and hasn't received any security updates ever since. Running this on a public webserver is just reckless and unprofessional. Get a hoster which actually cares about the servers and keeps them up-to-date. The currently supported PHP versions are 5.6 and 7.
  21. Sessions are not infinite by default, and there are actually two lifetime settings: The session.cookie_lifetime directive defines how long the session cookie is valid. It's typically set to “0”, which means the cookie is deleted when the user closes the browser. And the session.gc_maxlifetime directive defines how long the session file is considered valid. Note that expired files aren't cleared immediately. The session garbage collector which deletes the files is only executed with a certain probability, so the file may still exist for a while. Both settings together more or less determine the lifetime of the session.
  22. Trust me, it's not “just a wrapper”. Even the original author of the password API got it wrong a couple of times, because the crypt() function is weird as hell and had several bugs in different PHP versions. Unless you've actually inspected the C source code, read through the bugtracker and fully understand how bcrypt works, it's just dangerous to use crypt() directly. The salt is not an arbitrary string, and the manual is very misleading. What the crypt() function actually expects is a sequence of 128 random bits generated with a CSPRNG and encoded with a special Base64 variant (not the usual Base64). If you fail to provide a valid salt, pretty much anything can happen. And that was the easy part. How do you get a proper CSPRNG accross all PHP versions and operating systems? Are you aware of the bcrypt input limitations (no more than 56 bytes, no null bytes)? How do you enforce that? Note that strlen() may either return the number of bytes or the number of characters, depending on whether it has been overloaded by the Mcrypt extension. Are you aware of the various error representation and output bugs? How do you validate the resulting hash? How do you prevent timing attacks when you compare the calculated hash with the expected hash? ... I strongly recommend you use a library which has already gone through this like password_compat.
  23. I assume your “Hello World!” should actually be a dynamic string depending on $row? The easiest way to implement parallel iteration is to iterate one array with a foreach loop and the other with repeated each() calls: <?php $record = range(1, 26); // test data $letters = range('A', 'Z'); foreach ($record as $row) { $letterElement = each($letters); assert($letterElement !== false, 'Not enough letters for number of rows.'); $letter = $letterElement['value']; echo "$letter: $row<br>"; } For more complex scenarios, there are also iterator classes in the SPL extension.
  24. Just use the GET method instead of POST in your form, and all values will automatically transmitted as URL parameters. POST doesn't make sense anyway, because the form submission isn't supposed to change anything.
  25. Try possesive quantifiers: '/\\A\\d++(,\d++)*+\\z/'
×
×
  • 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.