Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Everything posted by Jacques1

  1. Just use a database already. You've now spent three days on this trivial task, you constantly get stuck, and it will be even worse when you have to do complex tasks. So why continue this route? The entire thread could be boiled down to a single SQL query: $media = $databaseConnection->query(' SELECT title, content, category, creation_time FROM media ORDER BY creation_time DESC -- add LIMIT if needed '); foreach ($media as $medium) { // parse and display $medium } That's it. No glob(), no uasort(), no array_slice(), no filectime(), no file_get_contents(). Just standard SQL. Even publishing will be simpler, because you don't have to upload anything. Make yourself a simple password-protected admin script and use that to manage your texts. Maybe the server already has a MySQL installation. If it doesn't, you can always use SQLite which stores the entire database in a single file.
  2. Neither code snippet makes much sense. The first one completely skips the first row, which is probably not what you want. And the second one is a nonsensical reimplementation of the standard fetchAll() method. If you just want to iterate over the result set, use a foreach loop, optionally with a flag to check for an empty set: <?php $hasProducts = false; foreach ($productsStmt as $product) { $hasProducts = true; // display $product } if (!$hasProducts) { echo 'No products found.'; } Modern template engines like Twig or Smarty have a specialized for-else statements which can do all that in one go.
  3. An example for a good database class is right in front of you: PDO. It's so intuitive that most of the time you don't even realize that it's object-oriented. It does have a few warts, though (like the cumbersome prepare/execute sequence). So a good and even useful project would be to write a streamlined PDO wrapper. For example, there should be a query() method which accepts parameters and then automatically takes care of creating a prepared statement: $databaseConnection->query('UPDATE foo SET bar = 12 WHERE baz = :baz', ['baz' => 42]); And the execute() method should return the statement for a more fluent interface: $foo = $fooStmt->execute(['bar' => 42])->fetchColumn();
  4. A fair warning: Stealing old code from other people and randomly piecing it together will neither teach you PHP nor produce anything useful. You may in fact end up violating software licenses (contrary to popular belief, open source doesn't mean you can do with the code whatever you want). It may surprise you, but learning to program is a lot about writing code. How do you learn a foreign language? You certainly don't collect a bunch of random sentences, put them all together and hope the text somehow makes sense. Instead, you learn the language basics and then start speaking or writing yourself.
  5. The whole chapter is bad. This doesn't teach anything about dependency injection. There are thousands of reputable open-source projects on GitHub covering every single topic and complexity level. This is as real as it gets. Or we can discuss your own projects, but then you need to set specific goals like “I want a wrapper for PDO”.
  6. Many things are “possible”. But programming is more about what's sensible. Your entire code is based on the assumption that there's a one-to-one relationship between users and cars. A user has exactly one car, and a car belongs to exactly one user. That's what a single table represents. Sure, you can also split the data into multiple tables, create an artificial one-to-one association via constraints, use joins to put all data back together and get hopelessly confused in the process. But what's the point of that? If users and cars were in fact separate entities (e. g. a user can have multiple cars), two tables would be appropriate. But you don't have that.
  7. What's the point of creating two tables when you want a strict one-to-one relationship?
  8. I know. But what are you struggling with? I can try to guess what your problems are, but I suggest you simply tell us. You seem to have forgotten the WHERE clause. Fixing this will also fix the nonexistent parameter in the bindParam() call. I also wonder how you're going to deal with (or prevent) multiple vehicles.
  9. If you don't know how to inspect the page source in your browser, learn it. That's definitely a skill every web programmer needs. The source will tell you that all input names are empty. This is also not how radio buttons work. All buttons must have the same name (like "motion"). That's how the browser knows they belong together.
  10. The code has plently of problems. First off, you're allowing anybody to send almost arbitrary content (read: spam) to arbitrary addresses without any restriction. That's certainly a good way to get yourself blacklisted. Then you're using the lame mail() function which sends the e-mails straight from the webserver. That's usually a bad idea. Unless the server is managed professionally (which I doubt), it probably doesn't have anything like a proper SPF record or DKIM to tell the world that it is in fact authorized to send e-mails for this domain. And it may already be blacklisted due to prior abuse. Last but not least, your e-mails are full of XSS vulnerabilities, which is even worse than spam and another good reason to reject your stuff. There's definitely a lot to learn and do before this is ready for production. Never ever let random visitors send out e-mails uncontrolledly. There should be a registration procedure for the sender or, if that isn't possible, a good CAPTCHA. A rate limit also helps avoid obvious abuse. Never ever let users put random content into e-mails. Always validate and escape the input. Use a proper library like PHPMailer instead of this mail() crap. Make sure to send the e-mails from an authorized machine. If you have an external mail server for your domain, use that.
  11. You need $Parsedown->setMarkupEscaped(true); to disable embedded HTML markup. I already did that: I neither use Windows nor have access to your server, so I cannot fix the permissions for you.
  12. The whole approach of building the table with dynamic query gymnastics is bad, so you shouldn't try to replicate this with PDO at all. I know this is hard to understand, but SQL is not Excel. SQL is supposed to store and provide data, not render pretty tables. That's what your application is for. So use your database to retrieve the data (i. e. the sum per date and type), and then write code to produce your pivot layout. So the query is simply SELECT datetransact, transactiontype, SUM(transactioncount) AS transactions FROM dummy_transaction GROUP BY datetransact, transactiontype ;
  13. The script doesn't make sense. You somehow seem to assume that you can put PHP code into a string, and this string (magically?) turns into application code whenever you reference it. This is conceptually impossible. A string is a string, not code. And the DSN string must contain the DSN, nothing else. You cannot “merge” other method arguments into it. The class layout is also somewhat strange. You again seem to confuse classes and functions. A class is not a function. It's not a procedure which you use to produce a single result like a DSN string. It's an autonomous actor which takes responsibility for an entire subsystem. Going back to the job analogy: When you hire a designer, you want somebody who takes care of all design-related tasks autonomously. They should be able to think for themselves and solve a variety of complex tasks on their own. Your current approach is more like hiring one person who turns on the PC and goes home, then another person who starts Photoshop and goes home, and then you do the design yourself. That's obviously not right. OOP is a lot about proper planning and much less about writing code, so maybe you should start with a class diagram rather than a PHP script. This can be helpful for seeing the bigger picture and avoiding the tunnel vision caused by years of procedural code.
  14. Given that strip_tags() is the worst possible choice and that you're struggling with the file permissions: no. So what happened with Markdown? If you want to filter your HTML in addition to or instead of using Markdown, there's HTML Purifier. The strip_tags() function is not an option for anything but joke applications, as the manual clearly says.
  15. Sounds like you want Markdown rather than HTML. Then ask the person who maintains the server. If that's you, look up how the permissions work, because that's kinda important.
  16. So your “text files” are actually HTML documents? Then you should stop pretending like they're text files. Give them a proper “.html” extension, double-check the file permissions (they must be read-only), then echo the raw content.
  17. Let me be more clear: PHP 5.4 was entirely abandoned and is full of security vulnerabilities that will never be fixed. Unless you have a special LTS operating system which provides its own PHP updates, you cannot use PHP 5.4. No amount of code will fix that. What kind of hoster and system is this?
  18. Including a text file with require_once is suicidal, because this turns the text into code which gets executed. Anybody with expected or unexpected access to those files can execute arbitrary commands on your server. Even echoing the content will make the application wide open to cross-site scripting attacks. If you want plain text, you need to escape the file content: $content = file_get_contents(...); echo htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); You should definitely reconsider your application infrastructure. I know that flat-file application are all the rage right now, but implementing this correctly -- i. e. without blowing up your server -- is a lot more work than simply using a proper database.
  19. PHP 5.4 reached end of life back in 2015. You need to keep your server up to date. The current PHP version is 7, the last supported one from the old 5.x branch is 5.6. Actually, you don't even seem to have 5.4, because this version already supported the short array syntax. Sounds more like 5.3 or older.
  20. The scripts are riddled with problems. Even if you spend another week trying to fix the obvious bugs, it will still be bad code, so it's not really worth the trouble. I would rewrite the code from scratch, this time using modern practices. Learn how to use mysqli properly, especially how to perform prepared statements. Or even better: Switch to PDO. Stop doing those output buffering gymnastics. Write proper code that works without any band-aid. Structure your code in a meaningful way (business logic at the top, output at the bottom). Also avoid useless actions like closing the database connection right before the script ends. PHP does this automatically. SHA-1 cannot protect your passwords. Today, any cell phone has enough computing power to perform a brute-force attack. Use a proper algorithm like bcrypt. The session ID must be regenerated after the log-in procedure. Otherwise the application will be wide open to session fixation attacks. Write valid HTML. A template: <?php // "require" statements go here session_start(); // collect errors, then display them at the bottom $input_errors = []; if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (!isset($_POST['email']) || trim($_POST['email']) == '') // empty() is usually a bad idea, because even strings like "0" are considered "empty" { $input_errors['email'] = 'You forgot to enter your e-mail address!'; } // etc. if (!$input_errors) { // fetch the user data with a prepared statement (this example uses PDO) $user_stmt = $database_connection->prepare(' SELECT ... '); $user_stmt->execute([ 'email' => $_POST['email'], ]); $user = $user_stmt->fetch(); if ($user && password_verify($_POST['pass'], $user['pass'])) { session_regenerate_id(true); $_SESSION['user_id'] = $user['user_id']; redirect(BASE_URL.'mempage.php'); // write your own function to avoid repeating the same boilerplate code over and over again } else { $input_errors['pass'] = 'Wrong e-mail address or password!'; } } } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Title</title> </head> <body> </body> </html> As you can see, this is much more straightforward and compact than what you currently have.
  21. If you want to discuss your own problems, create a new thread.
  22. This num_rows stuff has always been an anti-pattern, so the answer is to get rid of it altogether. Just check $row: As you can see in the manual, the fetch methods return false when there are no more rows. if ($row) // you'll want a more meaningful variable name than "row" { // echo the escaped(!) first name } else { echo 'No records found.'; }
  • 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.