Jump to content


  • Posts

  • Joined

  • Last visited

  • Days Won


Community Answers

  1. gizmola's post in using array_diff on 2 arrays was marked as the answer   
    He literally gave you code that works, only missing a semicolon:
    $result = array_udiff($table, $newdata, fn($a, $b) => $a <=> $b); var_dump($result); If you are familiar with Javascript ES6, it is a similar type of anonymous function shorthand, equivalent to this:
    $result = array_udiff($table, $newdata, function($a, $b) { return $a <=> $b; }); You need to have a current supported PHP version ( >= 7.4) although the syntax I showed works with any version 7.x or >
    The "arrow function" version was introduced with php 7.4
  2. gizmola's post in When user tries to download .iso, tar.gz, or .deb from my website php is opening the file instead of downloading it was marked as the answer   
    One pro tip:
    Never have a php end tag (ie. ?> ) in your scripts.  It is not needed, and can lead to bugs like this  remove all php end tags whenever they are the last thing in a .php file.
    You can start with looking at PSR-1, and perhaps graduate to PSR-12 if you are looking for some standards to help guide you.
  3. gizmola's post in Cant find the old thread about wrapper/container (CSS2-3). was marked as the answer   
    I don't have any specific recollection of such a thing, but a lot of things have changed in the css world, most notably the standardization of flexbox and grid that make older techniques and tricks of css layout obsolete.  You just don't need those things anymore when flexbox or grid can take care of your layout needs with simple, consistent and easy to understand syntax.  
    There was a time when you needed to know the ins and outs of floats and clear fix, and other arcane tricks of css, but that's basically obsolete knowledge.  People also use to use tables inside tables inside tables to get their "pixel perfect" layouts, but that also has given way to a focus on creating layouts that adapt from desktop to mobile.  
    This guy (Kevin Powell) has become well known in the css/web design world, and he really knows his stuff.  This video covers flexbox.  If you work through the examples with him, you will learn what you need.  He also has a corresponding Grid video.
    If you want something more interactive, lots of people love Scrimba, and in particular Per Borgen, who is one of the Scrimba founders.  He happens to have a free scrimba course covering grid and flexbox, so that is another way you can learn flexbox, if you want something more interactive.  The free Scrimba Grid/Flexbox course is here:   https://scrimba.com/learn/cssgrid
  4. gizmola's post in How to override trait methods from another trait? was marked as the answer   
    In the PHP manual section Traits section.
    You have 2 options:
    Alias the conflicting method so it doesn't conflict Specify an "insteadof" method statement in the use section of the class
  5. gizmola's post in PHP Variable Variables & Loops with Forms was marked as the answer   
    No worries - we all agree on using PDO so that is a good investment of your time.
    If you want to goto a new page that just has the signup form, then have all the buttons in the game list inside anchor tags.  Then you can just pass the game_name as a url parameter to the page that generates the form.  The signup page can just set the hidden game attribute using the $_GET parameter.
    I personally would opt for the usability of not having a separate signup form, but if it's simpler for you to go from a->b->c and get things working that way, do that then.  It makes the javascript event stuff simpler, although you will definitely need to learn that sooner than later.  I like Scrimba as a platform to learn html/css/javascript concepts, although there are many other freemium platforms.  Freecodecamp also does a good job.
    Simpler solution for you, again rendered buttons inside your foreach loop that lists the games (ie. one button per game listed):
    echo "<a href='signup.php?game_name=\"{$game['game_name']}\"'><button class='btn_game_signup'>Signup for this game</button></a>"; Clicking on the signup page will send a GET request to your signup.php script, which will include the $_GET parameter of 'game_name'.
    Then you just set the hidden form attribute of that page in your signup.php script to the value of $_GET['game_name'].
  6. gizmola's post in PHP+MySQL Unique Article Styling was marked as the answer   
    Yes there is a way to do this, but it involves a solid foundational understanding of relational database design concepts and how to write code.  It would be a significant amount of work for a professional programmer.  An alternative to reinventing the wheel from scratch would be to use a php based CMS like Drupal or Bolt  These projects start you out with a lot of functionality and systems that already have templating, much of which can be tweaked without programming.  They also have "taxonomies" which are extensible.  You can utilize existing templates to learn how templating works, and how to customize them without already being an advanced developer.
    Not to sound pessimistic here, but creating a blog database is not difficult at all, for something simple, but you still need to know what you are doing.  With that said, even though it might be fairly simple to do so, providing you a custom CMS database structure and instructions on how to create different templates against it is the topic of many an article, book and online course.   If you have a better idea of what approach you might take, people can provide you better advice.
  7. gizmola's post in Widespread Exploitation of Unauthenticated RCE in Apache Log4j (CVE-2021-44228) was marked as the answer   
    To be absolutely clear:  The Apache HTTP server that is commonly used in the AMP,LAMP, MAMP,WAMP stack, is not java based, does not integrate or use any java components, and is not at risk.
    This is a common enough misconception, in regards to Apache vs the Apache Software Foundation.
    The Apache webserver is one of the oldest Free Open Source web servers.  For the record it is written in c.  
    The original core contributors to the Apache HTTPD server, went on to create the Apache Software Foundation(ASF), which was incorporated as a non-profit to support the continued development of FOSS software.  The ASF also authored their own License, that is comparable and competes with the GPL and MIT licenses often used for FOSS.
    Over the years, the ASF has sponsored and brought many different types of software under their umbrella.  These projects benefit from funding and support services provided to them by the ASF.  At present there are something like 180+ individual software projects under the ASF umbrella.  Here is a list by programming language.
    Apache is a big player in the Java development space, with many important tools and java based projects under their umbrella.  Log4j is just one of these projects, but it is often integrated into other java based software and systems via their java logging project.  
    Here's one quote to help understand the potential scope of the problem:
    Anyone running an Enterprise or Java based system is a potential target, but there are also many pieces of java based software that are used by companies for the services they provide.
    For example, note the mention above of "Solr" which is a popular full text indexing engine that many sites who aren't otherwise java based, may use.  Apache also provides the Lucene engine, which is also Java based.  Basically if you are running any sort of java based software server, there is a good chance that the log4j vulnerability is a concern.  
    For any company with sysadmin/devops/developers with a degree of competency, the log4j exploit vector can be quickly and easily closed using several techniques that vary by log4j version and environment.  The problem is that there are many packages of java based software like Lucene & Solr, that the users may not realize are java based.  They may come with a packaged JRE, or be running via an independently installed JVM.
    The actual exploit requires crafted input that gets logged containing instructions which trigger java JNDI to download and run remote code.  So it's a "remote code exploit". 
    If a server with a vulnerable installation or version of log4j doesn't have some sort of publically available listener, there isn't a vector for exploitation.  For example, depending on the integration, your Solr or Lucene engine might not be at risk.  It could depend on how or what you are indexing, and where the data being indexed comes from.
    Many people are running java based editors like Eclipse or Netbeans, or any of the Jetbrains editors, in particular the very popular PHPStorm.  What does Jetbrains have to say about this?  https://blog.jetbrains.com/blog/2021/12/13/log4j-vulnerability-and-jetbrains-products-and-services/
    I hope this helps clarify some things for people.
  8. gizmola's post in Cookies and checkbox was marked as the answer   
    Yes, although again the UI is incorrect.  Checkboxes are not mutually exclusive.  So you are just doing this UI in the wrong way.  Your form code is also wrong. 
    You have a label that is hardwired to dark, yet you have variables toggling the value from light to dark.  When a form is rendered, it should always be checked, because you are using the checkbox to toggle from light to dark.   This means that a value for the checkbox will never be set in the way you using this.  A newly rendered form will always have a value (light or dark) and will be checked.  Once you uncheck it, you'll submit the form, and the checkbox will not be passed.
    However, to your question, you have 2 choices:
    Write a little js that checks the check/uncheck state and sets a hidden element, which you use on submit Just have php check for isset() or use array_key_exists.  If ! isset() then it was unchecked.  You want to check the request method to make sure the form was actually posted. Not that I'd advise this, but in this case, and again you have to be logical and clear, if the form is submitted, then you are looking to toggle the value.  
    <php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; //Toggle it $mode = ($mode == 'Light') ? 'Dark' : 'Light'; setCookie('mode', $mode); } else { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; setCookie('mode', $mode); } // Now can use $mode to render ?> <input type="checkbox" onChange="this.form.submit()" value="<?= $mode ?>" name="mode" checked> <label for="mode"><?php echo "$mode Mode"; ?><label><br>  
    Again when you think about it, the actual value of the checkbox is irrelevant as you are really going to toggle the cookie value on any submit.
    The other option is to use some js.  Probably what I would do is use a hidden field, so that you could rely on the submission, but then when you have a cookie you are also relying on, this whole scheme makes less sense
    Something like this could work:
    <?php if ($_SERVER['REQUEST_METHOD'] == 'POST') { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; //Toggle it $mode = ($mode == 'Light') ? 'Dark' : 'Light'; setCookie('mode', $mode); } else { $mode = empty($_COOKIE['mode']) ? 'Light' : $_COOKIE['mode']; setCookie('mode', $mode); } ?> <!DOCTYPE html> <html lang="en"> <head> <title>Form Test</title> <script type="text/javascript"> function toggleMode() { let cb = document.getElementById("cbmode"); let newMode = document.getElementById("new_mode"); newMode.value = (cb.value == "Light") ? "Dark" : "Light"; console.log(newMode.value); document.getElementById("modeForm").submit(); } </script> </head> <body> <form id="modeForm" method="post"> <input type="checkbox" onChange="toggleMode()" value="<?= $mode ?>" id="cbmode" name="cbmode" checked> <label for="cbmode"><?php echo "$mode mode"; ?></label> <input id="new_mode" type="hidden" value="<?= $mode ?>"> </form> </body> </html>  
  9. gizmola's post in Only one select statment instead of two was marked as the answer   
    There is no way to combine the queries,  other than to union them, and that has essentially no significant value to you.  You can write the count query in a slightly more compact manner if you like:
    $total_recs = $conn->query("SELECT count(*) FROM table1")->fetchColumn(); Your pagination limit variables should use bind variables:
    // You'll set your $limit and offset variables from your pagination calculation $res = $conn->prepare("SELECT * FROM users LIMIT ?,?"); $res->execute([$limit,$offset]); $data = $res->fetchAll();  
  10. gizmola's post in No data supplied for parameters in prepared statement was marked as the answer   
    Obviously if you don't have all the data required for the insert, you are going to get an error. One issue that you have made for yourself unnecessarily is:
    $user_id=""; $date_created = date( 'Y-m-d H:i:s' ); $date_edited =""; So i'm going to assume that you have an auto_increment for user_id, and date_edited can be null, and since this is a new row you want that to be NULL on insert.

    In this case, you should not be passing values for these. MySQL figures out how to auto_increment, and it makes no sense to pass a NULL date string for a date parameter that you will never set in this context.

    Change the insert so that those are not included:
    $stmt = $connection->prepare("INSERT INTO users values(?,?,?,?,?,?)"); $stmt->bind_param("s,s,s,s,s,s", $firstname, $lastname, $username, $hashed_password, $date_created, $status_id);
  11. gizmola's post in Call variable from another function in class was marked as the answer   
    When you define your class, just have properties that store the values you need to ingest from the constructor. Typically you want these properties to be private or protected, so scope them accordingly.

    class Client { private $currentAccount = 0; private $numberOfAccounts = 0; public function __construct($start = []) { //code $this->currentAccount = $currentAccount; //more code $this->numberOfAccounts = $numberOfAccounts; } } It looks like you would benefit from a quick read through the PHP manual section that covers classes and OOP
  12. gizmola's post in Importing an .xlsx file to a MySQL Database by using phpMyAdmin was marked as the answer   
    You can certainly convert it from Excel to csv easily enough, but you need csv to import, so if you can have that instead it saves you some complications.  The important thing with csv is that your string columns need to be surrounded by double quotes so that commas inside a string don't confuse the parsing. This also necessitates that if you have double quotes in the string, the double quotes have to be doubled in order to escape them.
    Excel export to csv should do this for you, so ultimately it's up to you if the excel has value outside of the import, or if getting a .csv version is more trouble than it's worth.
  13. gizmola's post in Always Incorrect Credentials when logging in was marked as the answer   
    I'm afraid you need to actual read/debug/trace the login code in order to understand why it works with the original table and not yours, but at least you have pinpointed a logical place to start.
  14. gizmola's post in set partial text color via javascript was marked as the answer   
    You can't just randomly color a piece of text. What you can do however, is put a span around that section, and style the span.
  15. gizmola's post in Real time order confirmation was marked as the answer   
    There aren't any generic examples out there to look at.  The closest thing I could suggest to you would be to look at the php ecommerce projects like Magento, Opencart and WooCommerce (for Wordpress) and even perhaps the API documentation for Shopify.
    It depends 100% on a companies specific payment processing & fulfillment systems.  
    In the US, there is consumer law that regulates things like this, in terms of consumer goods and when you are actually allowed to charge someone for a product, but even if we ignore that, the simple fact is that companies often have fulfillment and accounting systems that need to be integrated with, or there is no reason for a system to wait.  What is it waiting for?
    -Was there inventory available, and could that inventory be reserved?
    -Did the payment go through
    -Alert the fulfillment system that the order was successful, so that the order can be fulfilled
    In other words, there is no generic solution to the problem anyone can point you to.  
  16. gizmola's post in Building a CMS was marked as the answer   
    There is no magic to it, it's javascript/ajax.
    With that said, in the last few years, javascript frameworks have developed a tremendous amount of momentum.  Essentially this moves a lot of the code from the backend into a client javascript application.  Typically the backend becomes an api providing access to data via REST or SOAP.  I don't see a lot of people using SOAP anymore.
    Wordpress has been all in on the use of ReactJS, even to the extent that they announced they would abandon its use due to Facebook's plan to utilize a BSD + Patents license.  Ultimately, Facebook bowed to the pressure and threats to abandon it and changed the ReactJS license to MIT.
    At any rate ReactJS, Angular, Ember, Vue etc. are all quite prevalent in the current web development world, and provide the sexy interactive UI you are talking about.  The underlying technology that anchors all of these technologies is still Javascript/Ecmascript and Ajax which facilitates actively changing the UI without having to GET/POST the entire page and rebuild it from scratch.
  17. gizmola's post in Proper place to put memcache caching was marked as the answer   
    One of the reasons to do dependency injection in your use case is to de-couple the specifics of caching from the specifics of the switch. Memcache is not the only caching technology out there, so you could improve the reusability and utility of the class by utilizing an interface and wrapping the memcache in a class that implements the interface.
    You also have the option of doing setter injection rather than injecting memcache in the constructor. Again, that is something that makes things more optional.
    Whether any of this effort is beneficial in your specific situation is up to you. If you're not planning to change code inside the Switch class, it hardly seems worth the effort, although there shouldn't be much of a noticeable difference when you pass a memcache object into the Switch class as a parameter. A fundamental change from 3.x to 5.x was PHP passing all objects by reference, thus eliminating a common reason people used Global objects in the olden days.
  18. gizmola's post in aws elastic beanstalk permissions and ownership. was marked as the answer   
    You are running shell scripts that set environment variables for some reason. Maybe these are ubuntu things, but they aren't important to the basic workings of the system unless there is something happening in the apache startup script. I personally use amazon linux for all my ec2 instances, since they insure it works well with ec2 and they come preconfigured with package repos maintained and tested by amazon.
    At any rate, what I feel is the best practices in this situation is that you have a separate user|group combination for apache. However, apparently that is webapp currently, so I would not look into trying to change it. Check your apache httpd.conf file (should be somewhere in /etc or a directory underneath it) and see who the user/group is.
    To check out the entry for webapp, cat the /etc/passwd file and see what the entry for the webapp user is. I don't know why there wouldn't be a group there.
    In the apache httpd.conf file there is an entry for the user/group apache will run as. That should be webapp in this case.

    User webapp Group webapp
  19. gizmola's post in Php page image with text rewritten to function but... was marked as the answer   
    You should not be outputting an image header in a script that is simply creating an image and writing it to disk. Remove the

    Header ("Content-type: image/jpeg"); The other thing to look into is the path: 

    imagejpeg($image, 'vda-images/'.$n1.'.jpg', 80); Make sure that whatever process is running this php code has rights to rwx the vda-images directory.
  20. gizmola's post in Can a saved vagrant box handle a change in ISP ? was marked as the answer   
    What you want to do is change your network from public_network to "private_network". This will used the Nat adapter.
    Make sure the network is something that is unlikely to conflict with your home or work network. Something like '192.168.77.x'
  21. gizmola's post in what to do now ?! was marked as the answer   
    Learning to program can easily become a rabbit hole.
    Programming exists to create applications and systems that solve a problem or facilitate a business.
    The simple answer is, in order to progress as a programmer you need to actually program.
    Write down a design specification for something you want to build, and build it. Along the way you will need to problem solve. You will need to learn things you don't understand adequately at present, and you will fail, and in the process learn how to debug and become more competent.
    Let's say you read a bunch of books on carpentry, but never try to build anything? Would you hire that person to make you cabinets for your house?
    I know many developers who are starting out, who build things simply to have a portfolio showing what they can do.
    When I first started as a programmer, I made some silly applications that didn't do much, but in each case I learned a great deal. Eventually I created a freeware menu system (this was back in the days when DOS PC computers dominated the marketplace) and my software allowed you to create some simple text files that would be read in, and allow a user to navigate through the options and start programs. There were many such programs available at the time, but I built mine anyways, and used it on my computer and installed it on my parents computer.
    In creating it, I realized that I had a need to utilize record structures, linked lists, windowing libraries and file io. It required me to learn a lot of things and as a result I advanced as a programmer and this experience lead directly to a job that essentially started my professional programming career.
    With each project you learn more and become a more capable developer.
  22. gizmola's post in Please explain "FOR" loops was marked as the answer   
    For loops are just generic conditional control structures. The php syntax was borrowed from c, and it's common to many languages.
    In your example there's a problem because all php variables have to start with a '$'. But if we forget about that for a second, and just consider your question, here is what happened.
    What you wanted (echo a string 10x)

    $myVar = "This is awesome"; for ($i = 0; $i < 10; $i++){ echo $myVar . '<br>'; } What you did: 

    $myVar = "This is awesome"; for ($i = 0; $i < 10; $i++){ echo $myVar[$i] . '<br>'; } What is happening then? In this second case, what you are asking php to do, is to try and transform $myVar into an array from a string.PHP is happy to do this for you, as it already considers a string to be an array of characters.
    So what your code does is echo a single character from the $myVar string each time, and since $i is being incremented you get this:
    $myVar[0] .. then $myVar[1] .. then $myVar[2] etc. until the loop condition becomes false. In your example, it will loop 10 times, or up to 10 letters of the string: from $myVar[0] - $myVar[9].
    The loop itself is going to repeat the individual instructions contained within the control structure -- { ... } until the condition becomes false. With "for loops", you just have some place holders for built in variables that it will initialize, and increment or decrement each time the loop is entered.
    In other words, the $i is something that you may or may not want to be using inside the loop, but it's not required. Just to echo 10 strings, there is no need for you to reference $i inside the loop at all.
  23. gizmola's post in Creating a prepared statement from an array was marked as the answer   
    PDO::PARAM_STR is a constant defined with an integer value.
    There is absolutely no reason that you should have an issue assigning the value to an array element and using it later. It's an integer value when it's passed.
    We would have to see the code that does this "cramming" to understand whether your technique is valid or doing something different than what you think it is.
    With that said:

    $foo['type'] = PDO::PARAM_STR; Is entirely different from: 

    $foo['type'] == 'PDO::PARAM' . '_STR'; We need to know the specifics of what you were trying to do there that lead you down this path in the first place.
  24. gizmola's post in 4 bytes to float was marked as the answer   
    Here's a more modern, simpler and cleaner way of approaching this, that incorporates the advice already provided

    <?php $file = new SplFileObject("myfile.dat"); $raw = ''; while (!$file->eof()) { // Get one line from the file. $values = explode(',', $file->fgets()); $raw .= chr($values[1]); // Is this the 4th value? if (0 == $values % 4) { // Do whatever you need with the value. Just echoed it here echo unpack('f', $raw); $raw = ''; } } // Unset the file to close the file handle. $file = null;
  25. gizmola's post in Undefined Index if ID added to text field was marked as the answer   
    An undefined index occurs when you try and reference a key in an array that doesn't exist. Based on the info you provide that was the attempted referencing of "$_POST['company_address']". Clearly, prior to the api actually returning something, that variable didn't exist in the POST data.
    You can improve your error checking by using functions like array_key_exists or trying:

    if (isset($POST['some_key'])) { } else { // Deal with error, it's not going to work }
  • 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.