Jump to content

Jacques1

Members
  • Posts

    4,207
  • Joined

  • Last visited

  • Days Won

    209

Everything posted by Jacques1

  1. First off, you need to fix your data types. Unix timestamps and strings like “y”/“n” instead of actual booleans are amateurish, break type safety (the database system can no longer check if the values are even valid) and make the queries unnecessarily complex. Timestamps are stored in DATETIME fields. Booleans are stored in BOOLEAN fields. When that's done, you can do proper date calculations like in Psycho's post.
  2. The session behavior is normally determined by the PHP configuration, but you're changing those settings at runtime. You're overriding the default session name, cookie parameters etc. The fourth line of your function even says ini_set(...). When each script has its own runtime configuration, there's a big risk of incompatible behavior, which is exactly what happened. You may hope that you've fixed it now, but how can you be sure? You'd have to scan your entire project for uses of session_start() vs. sess_start(). Maybe there's even a third variant. A much cleaner solution is to not override the settings on a per-script basis. If you want different parameters, create an application-specific ini file and use that to define your session behavior.
  3. To make it short: Virtual paths like /items/p/ and relative physical paths like search.php don't go well together. The browser will end up trying to access nonsense URLs like /items/p/search.php, because it assumes it's actually within the directory /items/p/. Use absolute paths instead. For example, if your PHP script is directly below the document root, that's /search.php In the long run, you should also consider switching to virtual (“pretty”) URLs altogether. Then you can completely decouple the physical script paths from the URLs.
  4. So are you going to ignore the solution and keep working on this non-problem just for fun? Seems a bit stupid, but good luck.
  5. Scripts shouldn't mess with the PHP configuration at all. When you have custom settings, create a .user.ini file for your application (or whatever your webserver accepts). Overriding settings at runtime is not only notorious for creating incompatibilities like the ones you have. It also makes it very difficult to pinpoint the actual configuration; I can't just look at the .ini settings, because anything might be overridden somewhere deep inside the code.
  6. What a beauty! And figuring out which <?php } ?> belongs to which statement makes this so much more fun. It's “Where's Waldo?” for programmers! Who needs technological advancements when they can have PHP?
  7. Buddy, you've been told three times how to properly ask questions. If you still don't get it, go somewhere else.
  8. First off, you need to escape all HTML input and use proper semantic markup instead of this <br> stuff. To avoid the kind of PHPHTML spaghetti code you currently have, it's also a good idea to use a template engine like Twig. The Twig version: {% for eid, cdata in data %} <tr> <td class="eid">{{ eid }}</td> {% for content in cdata %} <td> <ul> {% for file in content %} <li><a href="#">{{ file }}</a></li> {% endfor %} </ul> </td> {% endfor %} </tr> {% endfor %} Output: <tr> <td class="eid">E1234</td> <td> <ul> <li><a href="#">A.pdf</a></li> <li><a href="#">B.pdf</a></li> <li><a href="#">C.xlsx</a></li> </ul> </td> </tr> The PHP version: foreach ($data as $eid => $cdata) { $trows .= ' <tr> <td class="eid">'.html_escape($eid).'</td> '; foreach ($cdata as $content) { $trows .= ' <td> <ul> '; foreach ($content as $file) { $trows .= '<li><a href="#">'.html_escape($file).'</a></li>'; } $trows .= ' </ul> <td> '; } $trows .= ' </tr> '; } Pretty, eh?
  9. Several things: Don't show your internal database errors to your visitors. It's very irritating for legitimate users, and it helps attackers gain information about your system. Instead, enable exceptions, so that error messages are automatically sent to the right device according to your PHP configuration (an error log in production, the developer's screen during development). Your database structure is broken. Whenever you find yourself numbering table names or columns, there's something wrong. SQL is not Excel. It's a database system with specific rules how to store data. Don't use SELECT *. Always select specific columns. Don't copy every item of the $row array into an extra variable. Just access the array items whenever you need them: $row['index_of_the_item']. You'll want a more meaningful name than $row, though. Stylistic HTML attributes like align, width, color etc. are dead since 1997. We have CSS now. If this is the entire script, you're also failing to output a complete and valid HTML document. Create a function for your database connection so that you can reuse this code in all your scripts: database.php <?php /** * Establishes a MySQL database connection using mysqli * * @param $host string the hostname or IP address of the database server (e. g. "localhost") * @param $user string the name of the database user * @param $password string the password of the database user * @param $database string the database name * @param $charset string the character encoding of the connection (e. g. "utf8) * * @return mysqli the connection * * @throws mysqli_exception if the connection failed */ function connect_to_database($host, $user, $password, $database, $charset) { // make mysqli throw an exception whenever it encounters a problem $mysqli_driver = new mysqli_driver(); $mysqli_driver->report_mode = MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT; $database_connection = mysqli_connect($host, $user, $password, $database); // specify the character encoding of the database connection $database_connection->set_charset($charset); return $database_connection; } Then create a configuration script to hold the connection parameters: configuration.php <?php const DATABASE_HOST = 'localhost'; const DATABASE_USER = '...'; const DATABASE_PASSWORD = '...'; const DATABASE_NAME = '...'; const DATABASE_ENCODING = 'utf8'; Fix your database structure. For example: TABLES quizzes - quiz_id questions - question_id - question answers - question_id - answer - is_correct quiz_questions - quiz_id - question_id
  10. There's no need to invent your own file extension function. This is a standard PHP feature: $file_extension = pathinfo($file_name, PATHINFO_EXTENSION); This is both correct and readable, so it's always preferrable over the end() hack.
  11. All that does is make the site inefficient by preventing the client from caching the images. It's also disastrous in terms of usability and accessibility, because if the user is visually impaired or simply has JavaScript disabled, the whole <i> stuff makes no sense whatsoever. I can only imagine how that works with a screenreader: “Here's empty text, no, wait, now it's an image.” If you don't reserve the image space, the layout will also jump around wildly as the images are loading. And again: As long as we don't know what the user wants, this is all just speculation.
  12. I would reject passwords with non-printable characters, though: <?php /** * Regular expression for validating passwords * * Only printable characters (including whitespace) are allowed, because all other characters were probably sent * erroneously and may cause problems with the underlying hash algorithm. */ const PASSWORD_PATTERN = '/\\A[[:print:]]+\\z/u'; $password = "foo\0bar"; if (preg_match(PASSWORD_PATTERN, $password)) { echo 'Valid password'; } else { echo 'Invalid password'; } Unfortunately, the current de-facto standard for hashing (bcrypt) is rather fragile in terms of input processing, so this either requires extra validation or pre-hashing with a more robust algorithm like SHA-2: <?php $password = "\0".str_repeat('A', 56); // not safe for bcrypt /* * Pre-hash password with SHA-256 * * bcrypt cannot handle long passwords (> 56 bytes) and passwords containing null bytes. To get around this issue, the * input is hashed with SHA-256, and the Base64-encoded hash is then passed to bcrypt. This makes sure both the length * and the characters are bcrypt-safe. */ $binaryPrehash = hash('sha256', $password, true); $encodedPrehash = rtrim(base64_encode($binaryPrehash), '='); $hash = password_hash($encodedPrehash, PASSWORD_BCRYPT, ['cost' => 14]); var_dump($hash);
  13. In other words, you rather want us to tell you a comfortable lie than the nasty truth? That's not exactly the best attitude for a programmer, not even for a hobbyist. The code you've found is riddled with security vulnerabilities, bad design decisions and hopelessly outdated techniques. If it were at least your code, I'd happily give you feedback. But you've copied and pasted it from some random website, and now you're asking others to fix it for you. That's getting you nowhere. You won't learn anything, everybody will spend a lot of time on useless bugfixes, and you'll still end up with bad code. If you want to learn, either write your own code (crazy, right?) or take it from good sources (like a properly managed GitHub project). You cannot learn from websites where the people know less about PHP than you do. For the write-for-scratch case, see mac_gyver's concept.
  14. The empty() function is usually a bad idea, because it's triggered by all kinds of values: The integer 0, the float 0.0, the string "0" and much more. It's easy to see how this can lead to all kinds of nasty bugs. A missing parameter is also something entirely different than a value which just happens to be falsy. Missing parameters indicate serious bugs (probably server-side, possibly client-side), so they should be logged and clearly indicated to the user. Falsy values are perfectly normal.
  15. It doesn't matter what kind of ad this is. It's garbage.
  16. If you want help, you'll have to be a lot more specific than “It doesn't work”. Are you getting an error message? If so, which one? A blank page? Something else? What's the content of $_REQUEST after you've received the form parameters? var_dump($_REQUEST); Note that using $_REQUEST is generally a bad idea, because it's a mixture of many different sources (form parameters, URL parameters, cookies, ...). If the sources happen to share some names, the parameters will overwrite each other, which can lead to bugs and even security vulnerabilities. What you should do instead is use specific sources like $_POST. Also note that you have a syntax error in your HTML markup: <form method="post" action="testy.php"searchform"> The closing form tag is also incomplete (but maybe that's just a copy-and-paste error). In any case, let's not play hide-and-seek. Tell us what your problem is, and we'll try to help you.
  17. Nonsense. The mysqlnd driver is the default since PHP 5.4. If it's not available, that's because your hoster has explicily disabled it during installation. If you can't get a PHP version with mysqlnd, you or your developer should be able to easily replace mysqli_stmt_get_result(). If the PDO extension is available, that's an even better alternative to mysqli.
  18. Have you read the suggestions in #2? Nobody said you should use a large framework. There are all kinds of frameworks in all kinds of sizes.
  19. First off: Please don't post your question into multiple forums. Pick one forum. We can always move your thread if that's necessary. A good way to untangle spaghetti code is to put all the business logic (i. e. the actual code) on top of the script and keep all the HTML markup at the bottom: <?php // PHP code goes here $foo = 1; ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Title</title> </head> <body> <!-- HTML markup goes here --> <!-- Use the PHP template syntax for simple PHP actions (variable insertions, if statements etc.) --> <?php if ($foo == 1): ?> <p>bar</p> <?php else: ?> <p>baz</p> <?php endif; ?> </body> </html> Like benanamen said, avoid mixing languages whenever possible, otherwise you'll quickly end up with an unreadable mess of PHPSQLHTMLJavaScriptCSS.
  20. I'm talking about this specific file, not your site in general. If the code isn't executed, that's clearly not fine.
  21. Are you sure the file has a “.php” extension? Are you sure the webserver is configured to execute PHP scripts in this directory?
  22. I've read your post a couple of times, and I'm still not sure what exactly you're asking for. First: If you want to immediately stop the script (e. g. after a redirect), you use an exit statement. However, organizing your router is a different problem and mostly comes down to personal taste. There are essentially three ways how to map URLs to pages: inside your code (not necessarily with a long switch statement, most modern routers use registration functions or methods), inside configuration files (example) or automagically by deducing the filename from some part of the URL (this can be dangerous if done naively). The “pages” themselves can again by implemented in different ways: as separate scripts (the classical way), as controller classes (like in modern frameworks), as functions, as inline code etc. In general, it's a good idea to see how others do it, go through many different options and then pick the one you like best. For example, CakePHP isn't the only framework. If you find it too heavy, there are several “micro frameworks” which you may like better. Or you can write your application from scratch, of course.
  23. What makes you think that creating a prepared statement and reusing it for multiple updates is inefficient? What time did you measure? What time do you target?
  24. On a side note: It's generally a good idea to assemble URL query strings with http_build_query(). This ensures all data is properly encoded, it's easier to add new parameters, and it's more readable (at least in my opinion). $url = 'https://api.eveonline.com/corp/CorporationSheet.xml.aspx?'.http_build_query(['corporationID' => $id]);
  25. How about you use code that isn't complete garbage? I have no idea where you got this stuff from, but it's unfixable, and I don't think anybody is masochistic enough to even try. If you're unable or unwilling to write your own code, use a proper implementation from people who know what they're doing. There are shopping applications all over the place.
×
×
  • 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.