Jump to content

benanamen

Members
  • Posts

    2,134
  • Joined

  • Last visited

  • Days Won

    42

Posts posted by benanamen

  1.  

    It's a security vulnerability in any case, because even wrong passwords will often be very close to the actual passwords. They may in fact be actual passwords from other sites which the user mixed up, or they're old passwords which can be used to figure out the new passwords.

     

    You really cannot log any password of any kind. I'm not even sure how that data would be useful.

     

     

     

     

    No, it's a class/interface name (the first case in the list).

    <?php
    
    /**
     *
     */
    class LoginAttemptsLog
    {
        /**
         * @var PDO the connection to the underlying database
         */
        protected $database;
    
        /**
         * @param PDO $database the connection to the underlying database
         */
        public function __construct(PDO $database)
        {
            $this->database = $database;
        }
    
        /**
         * @param string $username
         */
        public function logFailedAttempt($username)
        {
            $this->logAttempt($username, false);
        }
    
        /**
         * @param string $username
         */
        public function logSuccessfulAttempt($username)
        {
            $this->logAttempt($username, true);
        }
    
        /**
         * @param string  $username
         * @param boolean $successful
         */
        protected function logAttempt($username, $successful)
        {
            $attemptStmt = $this->database->prepare('
                INSERT INTO
                  user_login (login_status, login_ip, login_username, login_datetime)
                VALUES
                  (?, INET_ATON(?), ?, NOW())
            ');
            $attemptStmt->execute([($successful ? 1 : 0), $_SERVER['REMOTE_ADDR'], $username]);
    
        }
    }
    

     

    Continuing from https://forums.phpfreaks.com/topic/302938-oop-class-code-review/ in regards to a global being used in a class, my research shows that you do not want to use globals in a class. How then should this last line be properly dealt with? In another thread @requinix said as long as you are not changing anything it is ok. Reference  https://forums.phpfreaks.com/topic/302901-oop-convert-function-to-class/?do=findComment&comment=1541244

    $attemptStmt->execute([($successful ? 1 : 0), $_SERVER['REMOTE_ADDR'], $username]);
    
  2. Once you showed the last code, yes it is easy. What is the proper way to document the code? Do you do it at ALL the functions or just the interface function? Seems redundant if documentation is exactly the same for each function. I know function alone is the same as public function. Is it best practice to always use public anyways?

     

    This is what I have done with your help. Any problems? I have not messed with CLI yet so no clue about that part right now.

    <?php
    /**
     * Dumps data
     */
    
    interface VarDumper
    {
        function dump($title, $data);
    }
    
    class HTMLVarDumper implements VarDumper
    {
    /**
     * @param string $title
     * @param ?? $data
     */
        function dump($title, $data)
        {
        echo '<pre><span style="color:red;font-weight:bold">';
        echo $title . '<br>';
        print_r($data);
        echo '</span></pre>';
        }
    }
    
    class CLIVarDumper implements VarDumper
    {
        function dump($title, $data)
        {
            // output for CLI contexts
        }
    }
    
    // the class user is free to define custom classes as well
    
    $_POST     = ['username' => 'MyUsername', 'email' => 'user@example.com'];
    $varDumper = new HTMLVarDumper();
    $varDumper->dump('POST', $_POST);
    
    
  3. It doesn't really make sense to instantiate a class just for the trivial purpose of making a fancy variable inspection. This should be a function or, if you insist on OOP, a static method.

     

    I had it as a function. I am just trying to learn OOP. Can you give an example of a static method please.

     

    The hard-coded HTML output violates the reusability principle. If I want to have debug information in CLI mode, I cannot use the class at all. Even a different formatting isn't possible.

     

    Good to know. I was wondering about the html when I did it. For the purpose of viewing the superglobal arrays, what other format could you possibly want besides print_r?

    • Method names are supposed to use camelCase according to PSR-1not PascalCase.

    Yes, I know. I noticed it after I posted. Too late to edit post.

     

    The class description is confusing. It claims that the class is meant specifically for the PHP superglobals, but the actual implementation has no reference to the superglobals at all. It's a general-purpose debug display which can for example be used for the superglobals.

     

    I realized later that the superglobals are not the only thing that could be passed to the class. Since you pointed it out, I can see how the name could be confusing. In another post I asked how to properly use superglobals with a class. The answer I got was not particularly helpful. What would be a name that makes sense to you?

    • What's the @param doing in the class description?

    It should actually go right above the constructor right? I noticed later @param $title was missing.

     

    A better approach would be to first define a generic interface for debug information and then subclass it for different formattings. This also allows custom formattings:

     

    Right now I don't know what that means. Any other info would be helpful. How would I use the code you posted?

  4. @clukas,

    With your table you don't need any relationships or junction tables and you don't need more than one query.

     

    Output from code:

    Array(    [Flight One] => 300    [Depart One] => MIA    [Arrive One] => JFK    [Flight Two] => 100    [Depart Two] => JFK    [Arrive Two] => LHR    [Flight Three] => 200    [Depart Three] => LHR    [Arrive Three] => FRA)

    Flight Itenerary
    1. Flight 300 MIA To JFK
    2. Flight 100 JFK To LHR
    3. Flight 200 LHR To FRA 

    <?php
    $hostdb   = 'localhost';
    $dbname   = 'flights';
    $username = 'root';
    $password = '';
    
        $pdo = new PDO("mysql:host=localhost;dbname=$dbname", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        $sql  = "SELECT
        f1.flt_num AS 'Flight One',
        f1.arr_airport AS 'Depart One',
        f1.dep_airport AS 'Arrive One',
        f2.flt_num AS 'Flight Two',
        f2.arr_airport AS 'Depart Two',
        f2.dep_airport AS 'Arrive Two',
        f3.flt_num AS 'Flight Three',
        f3.dep_airport AS 'Depart Three',
        f3.arr_airport AS 'Arrive Three'
    FROM
        myflights AS f1,
        myflights AS f2,
        myflights AS f3
    WHERE
        f1.id = 3
    AND f2.id = 1
    AND f3.id = 2";
    
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
        echo "<pre>";
        print_r($row);
        echo "</pre>";
    ?>
    
    Flight Itenerary
    <br>
    1. Flight <?= $row['Flight One'] ?> <?= $row['Depart One'] ?> To <?= $row['Arrive One'] ?>
    <br>
    2. Flight <?= $row['Flight Two'] ?> <?= $row['Depart Two'] ?> To <?= $row['Arrive Two'] ?>
    <br>
    3. Flight <?= $row['Flight Three'] ?> <?= $row['Depart Three'] ?> To <?= $row['Arrive Three'] ?>
    
    
    
    -- ----------------------------
    -- Table structure for myflights
    -- ----------------------------
    DROP TABLE IF EXISTS `myflights`;
    CREATE TABLE `myflights` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `dep_airport` varchar(255) DEFAULT NULL,
      `arr_airport` varchar(255) DEFAULT NULL,
      `flt_num` int(11) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of myflights
    -- ----------------------------
    INSERT INTO `myflights` VALUES ('1', 'LHR', 'JFK', '100');
    INSERT INTO `myflights` VALUES ('2', 'LHR', 'FRA', '200');
    INSERT INTO `myflights` VALUES ('3', 'JFK', 'MIA', '300');
    
  5. You are missing the closing }

     

    There are other problems. You need to use prepared statements. You never insert user supplied data directly to the DB. Dont SELECT *. Specify the columns you want. You also do not need to manually close the connection. It closes automatically. It would appear your logic is flawed.

     

    You can't throw two query parameters into mysql like that. And don't create variables for no reason. I formatted your code so it is more readable but it still needs fixing aside from the missing bracket I put in.

     

    I would recommend you use PDO. https://phpdelusions.net/pdo

     <?php
    if (isset($_POST['choices']) && !empty($_POST['choices']))
        {
        if ($_POST['choices'] == 'four')
            {
            //variables from form entered
            $username = $_POST['username'];
            $neptune  = $_POST['neptune'];
            $email    = $_POST['useremail'];
    
            //connect to the database
            $dbc = mysqli_connect('localhost', 'root', '', 'happygam_main') or die('Error connecting to MySQL server');
            $check     = mysqli_query($dbc, "select * from ballot where username='$username' and neptune='$neptune'");
            $checkrows = mysqli_num_rows($check);
            
            if ($checkrows > 0)
                {
                echo "This combination of neptune and username has already been processed";
                }
            else
                {
                //insert results from the form input in 2 rows one with neptune one without
                $query  = "INSERT IGNORE INTO ballot(username, useremail, neptune) VALUES('$username', '$email', '$neptune')";
                $query1 = "INSERT IGNORE INTO ballot(username, neptune) VALUES('$username', '$neptune')";
                $result = mysqli_query($dbc, $query, $query1) or die('Error querying database.');
                
                mysqli_close($dbc);
                }
            }
        
        }
    ?>
    
  6. The following is my further attempt to learn OOP. Is there anything technically wrong with it or is there any better practices in the code or its use? Purpose is to display dev/debugging data. Your feedback is appreciated.

     

    * Code in forum is on one page so you can easily run it if desired.

    <?php
    /**
     * Displays data from $_COOKIE, $_SESSION, $_GET, $_POST, $_REQUEST
     * @param string $debug COOKIE, SESSION, GET, POST, REQUEST
     */
    
    class DebugDisplay
        {
        private $title;
        private $debug;
    
        public function __construct($title, $debug)
            {
            $this->title = $title;
            $this->debug = $debug;
            }
    
        public function ShowDebug()
            {
            echo '<pre><span style="color:red;font-weight:bold">';
            echo $this->title . '<br>';
            print_r($this->debug);
            echo '</span></pre>';
            }
        }
    
    //----------------------------------------------------------------------------------------
    // Test Data
    //----------------------------------------------------------------------------------------
    
    $_COOKIE[]  = 'COOKIE Data';
    $_SESSION[] = 'SESSION Data';
    $_REQUEST[] = 'REQUEST Data';
    $_GET[]     = 'GET Data';
    $_POST[]    = 'POST Data';
    
    //----------------------------------------------------------------------------------------
    // Debugging
    //----------------------------------------------------------------------------------------
    
    
    define("DEBUG", true); // Toggle Debugging
    
    define("SHOW_DEBUG_PARAMS", DEBUG); // Display Sql & Sql Parameters
    define("SHOW_SESSION_DATA", DEBUG); // Display Session Data
    define("SHOW_POST_DATA", DEBUG); // Display Post Data
    define("SHOW_GET_DATA", DEBUG); // Display Get Data
    define("SHOW_COOKIE_DATA", DEBUG); // Display Cookie Data
    define("SHOW_REQUEST_DATA", DEBUG); // Display Request Data
    
    if (DEBUG === true)
        {
        echo '<div class="error_custom"><H1>DEBUGGING IS ON !!!</H1></div>';
        }
    
    if (SHOW_COOKIE_DATA === true)
        {
        $show = new DebugDisplay('COOKIE', $_COOKIE);
        echo $show->ShowDebug();
        }
    
    if (SHOW_SESSION_DATA === true)
        {
        if (isset($_SESSION))
            {
            $show = new DebugDisplay('SESSION', $_SESSION);
            echo $show->ShowDebug();
            }
        }
    
    if (SHOW_POST_DATA === true)
        {
        $show = new DebugDisplay('POST', $_POST);
        echo $show->ShowDebug();
        }
    
    if (SHOW_GET_DATA === true)
        {
        $show = new DebugDisplay('GET', $_GET);
        echo $show->ShowDebug();
        }
    
    if (SHOW_REQUEST_DATA === true)
        {
        $show = new DebugDisplay('REQUEST', $_REQUEST);
        echo $show->ShowDebug();
        }
    

    Application Output

     

    post-179806-0-64301700-1484519667_thumb.png

  7. You have several other issues but as to your problem. Your button group is named name='RadioGroup1' but you are trying to insert ans. There is no $_POST['ans']. There is also no $_POST['value'] either. 

     

    You also gave two buttons the same value. You also have a ridiculous amount of unnecessary escaping. Your opening form tag is in the completely wrong place. The whole bit of code is quite a mess.

     

    You need to take a minute and study some basic tutorials. The whole thing needs a complete re-write. And while you're at it you should do it in PDO. https://phpdelusions.net/pdo

     

    Edit * It looks like you were already give good information on this in your other posts but you did not listen to what you were told. Your were even given code by @gingerjm that you ignored. You are just wasting our time if you're not going to do what we tell you. After seeing the other posts and responses you got you have now irritated me for wasting my time on this post.

  8. Just noticed that you are looking up ICD codes. That data is way to huge to select everything. You are going to have to do something like a chained select where you select a category and work your way down the dropdowns. 

     

    @barand makes a good point about the DB structure. What does the current DB look like? One big spreadsheet type table or something else?

  9. This is just for learning OOP. It is not about the function itself really, but how to handle superglobals in a class. The issue actually came up in a login logging class that uses $_SERVER['REMOTE_ADDR'], another superglobal. Several code analyzers (scrutinizer, codacy, code climate ) pointed out a problem with using them in the class. 

     

     

    * As far as what the function is for, it is used to display messages to the user after certain actions such as a db record added or deleted

  10. How would I to convert the following function to a class? What is the proper way to deal with GET and POST in a class since they are globals?

     

    My start

    class ShowActionMessage
    {
    
    }

    Function to convert

    function show_action_messages()
    {
    if (isset($_GET['insert']))
    {
    $action = 'Added';
    }
    
    if (isset($_GET['edit']))
    {
    $action = 'Updated';
    }
    
    if (isset($_GET['deleted']))
    {
    $action = 'Deleted';
    }
    
    if (isset($_GET['emailed']))
    {
    $action = 'Emailed';
    }
    
    if (isset($action))
    {
    ?>
    <div class="row">
    <div class="col-md-8 col-md-offset-2">
    <div class="success">Record <?= $action ?></div>
    </div>
    </div>
    <?php
    }
    }
    
  11. Problem is I am returning all the "null" values and I am not sure if there is a way to weed them out.

     

    Oh no, no, no, your problem is the entire database structure. Seriously, stop what you are doing right now and go back to the drawing board and start working on a sensible DB Schema. We will be happy to help you get going. What you have is an XY problem to the extreme.

     

    Start with a project summary of what this application is and what it should do then create a requirements document and post it. Once we know what you want and need we can offer the correct direction.

×
×
  • 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.