1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Help with userclass, form checking, and header

Discussion in 'PHP' started by Jeremy Benson, Nov 5, 2013.

  1. #1
    I seem to be having some trouble with my PHP code. Was wondering if someone could help me sort them out...

    One issue is that my session variables don't seem to be registering. I place a value inside a session variable to hold errors, but when the user is taken back to the index page the error isn't displayed in the error handle.

    A second issue is even though I've check a session variable to not be equal to something the header fires the redirect anyway...

    hmm... I've also got this section of code that searches form fields for special characters...it certainly works, but it's a bit of an over kill... I wasn't sure how to work the ereg function...it's quite confusing to me in the books...

    Maybe someone can help me make a better function?

    index.php
    this is at the very top of the document.

    PHP:
    1. <?php
    2.  
    3.     include('/system/scripts/php/systemclass.php');
    4.     $system = new system;
    5.     session_start();
    6.     $_SESSION['sessionStarted'] = "yes";
    7.     $_SESSION['registrationError'] = "";
    8. ?>
    9.  
    this is used to display CSS dynamically. I just removed an instantiation of a new system, lol, let me know if that fixes one of the problems above. Not sure if that conflicted with object instantiated at the top of the document. (at library, so time is limited)

    PHP:
    1. <?php
    2. $system->cssDisplay();
    3. ?>
    4.  
    This is the code used to display the error handle handed to the session variable from within my system class.

    PHP:
    1. <?php echo "<p><font color=\"red\">". $_SESSION['registrationError'] . "</font></p>" ?>
    registration.php

    This is the code at the top of my registration document. This is where the header that constantly fires is..

    PHP:
    1. <?php
    2.  
    3. include('../system/scripts/php/systemclass.php');
    4. $system = new system;
    5.  
    6. if($_SESSION['sessionStarted'] != "yes"){
    7.    
    8.     header("Location: ../index.php");
    9.     exit;
    10.    
    11. }else{
    12. $system->formFieldCheck();
    13. }
    14. ?>
    15.  
    Here's my user class. My lack of knowledge as I mentioned above left me coding functions that aren't very reusable usable in some cases...mostly the user check forum....I think I should split the function up into smaller functions to make it more reusable? Hopefully I can get some pointers :)

    PHP:
    1.  
    2.  
    3. <?php
    4.  
    5. class system{
    6.      
    7.    public $fireFoxStylePath = "\"admin/css/ffhomestyle.css\"";
    8.    private $webAgent;
    9.    private $errorRegistration;
    10.    
    11.    function __construct()
    12.    
    13.    {
    14.      $this->webAgent = getenv("HTTP_USER_AGENT");
    15.      
    16.    }
    17.    
    18.        
    19.    function cssDisplay()
    20.    
    21.    {
    22.      
    23.      if(preg_match("/Mozilla/i", "$this->webAgent")){
    24.  
    25.        echo "<link href=\"admin/css/ffhomestyle.css\" rel=\"stylesheet\" type=\"text/css\"/>";
    26.      }
    27.  
    28.    }
    29.    
    30.    
    31.    function formFieldCheck()
    32.    
    33.    {
    34.          
    35.          
    36.      foreach($_POST as $val){
    37.        if($val == ""){
    38.        
    39.        $_SESSION['registrationError'] = "Don't forget to fill in the form feilds.";
    40.        header("Location: ../index.php");
    41.        exit;
    42.  
    43.        }      
    44.      }
    45.      
    46.      foreach($_POST as $val){
    47.        if($val != ""){
    48.        
    49.          $tempVal = $val;
    50.        
    51.          htmlentities($tempVal);
    52.          strip_tags($tempVal);
    53.          nl2br($tempVal);
    54.          stripslashes($tempVal);
    55.                
    56.          $tempVal = str_replace("!", "NULL", $tempVal);
    57.          $tempVal = str_replace("`", "NULL", $tempVal);
    58.          $tempVal = str_replace("~", "NULL", $tempVal);
    59.          $tempVal = str_replace("#", "NULL", $tempVal);
    60.          $tempVal = str_replace("$", "NULL", $tempVal);
    61.          $tempVal = str_replace("%", "NULL", $tempVal);
    62.          $tempVal = str_replace("^", "NULL", $tempVal);
    63.          $tempVal = str_replace("&", "NULL", $tempVal);
    64.          $tempVal = str_replace("*", "NULL", $tempVal);
    65.          $tempVal = str_replace("(", "NULL", $tempVal);
    66.          $tempVal = str_replace( ")","NULL", $tempVal);
    67.          $tempVal = str_replace("+", "NULL", $tempVal);
    68.          $tempVal = str_replace("=", "NULL", $tempVal);
    69.          $tempVal = str_replace("[", "NULL", $tempVal);
    70.          $tempVal = str_replace("]", "NULL", $tempVal);
    71.          $tempVal = str_replace("{", "NULL", $tempVal);
    72.          $tempVal = str_replace("}", "NULL", $tempVal);
    73.          $tempVal = str_replace(";", "NULL", $tempVal);
    74.          $tempVal = str_replace(":", "NULL", $tempVal);      
    75.          $tempVal = str_replace("'", "NULL", $tempVal);
    76.          $tempVal = str_replace("\"","NULL", $tempVal);
    77.          $tempVal = str_replace("|", "NULL", $tempVal);
    78.          $tempVal = str_replace("<", "NULL", $tempVal);
    79.          $tempVal = str_replace(">", "NULL", $tempVal);
    80.          $tempVal = str_replace(",", "NULL", $tempVal);
    81.          $tempVal = str_replace("?", "NULL", $tempVal);
    82.          $tempVal = str_replace("/", "NULL", $tempVal);          
    83.                  
    84.          if($tempVal == "petNULLs nameNULL"){
    85.          
    86.            $tempVal = "pet's name?";
    87.          
    88.          }elseif($tempVal == "motherNULLs maiden nameNULL"){
    89.          
    90.            $tempVal = "mother's maiden name?";          
    91.          
    92.          }elseif($tempVal == "favorite yearNULL"){
    93.            
    94.           $tempVal = "favorite year?";
    95.          }  
    96.          
    97.          if($_POST['password'] != $_POST['password2']){
    98.          
    99.            $_SESSION['registrationError'] = "Your passwords don't match.";
    100.            header("Location: ../index.php");
    101.            exit;
    102.  
    103.          }
    104.          
    105.          if(!strstr($_POST['email'],"@") && !strstr($_POST['email'],"@")){
    106.          
    107.            $_SESSION['registrationError'] = "The e-mail isn't valid.";
    108.            header("Location: ../index.php");
    109.            exit;
    110.          
    111.          }
    112.          
    113.          if($_POST['password'] == $_POST['userName']){
    114.          
    115.            $_SESSION['registrationError'] = "Password and Username can't match.";
    116.            header("Location: ../index.php");
    117.            exit;
    118.    
    119.          
    120.          }
    121.          
    122.                    
    123.          if($tempVal != $val){
    124.            
    125.            $_SESSION['registrationError'] = "Form fields can't contain speacial characters.";
    126.            header("Location: ../index.php");
    127.            exit;
    128.            
    129.          }
    130.          elseif($val == $tempVal){
    131.          
    132.            $this->registerNewUser();
    133.          }            
    134.        
    135.        }
    136.      
    137.      }
    138.    
    139.    }
    140.    
    141.    function registerNewUser()
    142.    
    143.    {
    144.  
    145.    }
    146.    
    147. }
    148.  
    149. ?>
    150.  
    151.  
    Jeremy Benson, Nov 5, 2013 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,119
    Likes Received:
    331
    Best Answers:
    17
    Trophy Points:
    325
    #2
    First, I don't see you starting the session in registration.php.

    But then again, if you ask me, errors don't belong in sessions to begin with. I would have the form submit the data to the same page it's on. This way you don't have to carry around unnecessary data, and you don't lose the data the user inserted into the form fields. If that's not an option, you could redirect the user to the form and append an error variable to it.

    Like so:
    PHP:
    1.  
    2. if (/* error */)
    3. {
    4.     header('Location: index.php?error=username');
    5.     exit;
    6. }
    7.  
    And then in index.php
    PHP:
    1.  
    2. $errors = [
    3.     'username' => 'Username can\'t be empty',
    4.     'password' => '...'
    5. ];
    6.  
    7. if (!empty($_GET['error']) AND in_array($_GET['error'], $errors, true))
    8. {
    9.     echo $errors[$_GET['error']];
    10. }
    11.  
    ... or something along those lines. But that's just a dirty hack around something that can be much simpler.

    I would do it like this:
    PHP:
    1.  
    2. <?php
    3.  
    4. $errors = [];
    5.  
    6. if ($_SERVER['REQUEST_METHOD'] === 'POST')
    7. {
    8.     // Form has been submitted. Validate stuff here
    9.  
    10.     if (/* error */)
    11.     {
    12.         $errors[] = 'Empty username';
    13.     }
    14.  
    15.     // ...
    16.  
    17.     if (empty($errors))
    18.     {
    19.         // Save user
    20.     }
    21. }
    22.  
    23. if (!empty($errors))
    24. {
    25.     // Display errors here
    26. }
    27.  
    28. ?>
    29. <form action="registration.php" method="post">
    30. <!-- You can fill the form fields with the values from the $_POST array
    31.     so users don't have to refill them -->
    32. </form>
    nico_swd, Nov 5, 2013 IP
  3. nico_swd

    nico_swd Prominent Member

    Messages:
    4,119
    Likes Received:
    331
    Best Answers:
    17
    Trophy Points:
    325
    #3
    Oh, and note that these lines serve no purpose, since you're not overwriting the existing variables.
    PHP:
    1.  
    2.          htmlentities($tempVal);
    3.          strip_tags($tempVal);
    4.          nl2br($tempVal);
    5.          stripslashes($tempVal);
    6.  
    nico_swd, Nov 5, 2013 IP
  4. Jeremy Benson

    Jeremy Benson Member

    Messages:
    118
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    46
    #4
    hmm, since those functions aren't doing anything...is the rest of the function working the way I'd like it to? I'm kind of worried about that function not doing what I wanted it to, lol.

    just wondering you said you didn't see me start a session in registration... I had started the session in index.php because I wanted to take the user out of registration.php and back into index.php if a session wasn't started... that's why I was storing errors in session variable, but you're right about not doing that because of the extra data..so I'll try and store the errors in any array in the system class and and display them via the array :)

    ugh, hold on... trying to understand your code here...

    PHP:
    1.  
    2. <?php
    3.  
    4. $errors = [];
    5.  
    6. if ($_SERVER['REQUEST_METHOD'] === 'POST')
    7. {
    8.     // Form has been submitted. Validate stuff here
    9.  
    10.     if (/* error */)
    11.     {
    12.         $errors[] = 'Empty username';
    13.     }
    14.  
    15.     // ...
    16.  
    17.     if (empty($errors))
    18.     {
    19.         // Save user
    20.     }
    21. }
    22.  
    23. if (!empty($errors))
    24. {
    25.     // Display errors here
    26. }
    27.  
    28. ?>
    29.  
    That should be on the form page...just not sure what that does to my systemclass lol....or should my system class be for smaller purposes, like css and the likes?

    sorry for the questions, always struggle a bit with code, and I find that I have a horrible time understanding another's code, even if it's kind of easy...it's like if I don't write it myself I don't know what's going on, lol.
    Last edited: Nov 5, 2013
    Jeremy Benson, Nov 5, 2013 IP
  5. Jeremy Benson

    Jeremy Benson Member

    Messages:
    118
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    46
    #5
    maybe I should have mentioned that users start on index...fills out a form... go to registration.php and fill out a second form...that's why the validation of input isn't happening on the same page as the form at the moment...sorry really confused, lol
    Jeremy Benson, Nov 5, 2013 IP
  6. PoPSiCLe

    PoPSiCLe Well-Known Member

    Messages:
    1,224
    Likes Received:
    109
    Best Answers:
    51
    Trophy Points:
    160
    #6
    You need to do a session_start() on every page where you use or try to set sessions - else they won't work.
    PoPSiCLe, Nov 5, 2013 IP
  7. nico_swd

    nico_swd Prominent Member

    Messages:
    4,119
    Likes Received:
    331
    Best Answers:
    17
    Trophy Points:
    325
    #7
    It's not that the function doesn't do what you want it to do, it's that you're not using it correctly. It should be:
    PHP:
    1.  
    2. $tempval = htmlentities($tempVal);
    3. // ... etc
    4.  
    As for the rest of your code, I don't know. I haven't tried it, but without digging too deep into it, it looks okay.

    Sounds good!

    Well what your class does and/or how you use it is up to you. I was merely suggesting to place the form, and the code that processes it on the same page. You can still redirect the user to the new page if everything in the first form was filled out correctly. That's how I would do it anyway.

    It's not unusual, I suppose. But you'll eventually get around it. :)
    nico_swd, Nov 6, 2013 IP
  8. Jeremy Benson

    Jeremy Benson Member

    Messages:
    118
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    46
    #8
    Hey, thanks for all the replies. I got the code working, but have to transfer some of it back to relying on the class...especially the code that checks empty input, and special chars...also gonna break that down into ereg, or another method...just need to watch part video series on it, because the books are too dry on it....sometime someone teaching makes all the difference..

    I have some new issues now that I've gotten farther, lol...always something..

    I've got to the part where I want to connect to the database I have in wamp...just using phpmyadmin.

    I have a sql class for making a connection, and plan to run some queries but it's trying to say that I have at least on undefined variable in my sql class, and cannot access empty property on line 18. That's the function call to connect.

    You'll see I decided to take some of your advice and do same page validation, made things easier...

    ahh... I have a commented out include file which has the sql password in it, and thought that's where the errors were so I added the variables in the class file until later, but found out that wasn't the case, lol.

    index.php

    PHP:
    1. <?php
    2.  
    3.     session_start();
    4.     include('/system/scripts/php/systemclass.php');
    5.     require('system/scripts/php/sqlclass.php');  
    6.     $system = new system;
    7.     $sqlsystem = new sqlsystem;
    8.     $error = [];
    9.     $formIsEmpty = false;
    10.     $formDataSafe = false;
    11.    
    12.  
    13.     if($_SERVER['REQUEST_METHOD'] === 'POST'){
    14.        
    15.         if(!IsSet($_POST['userAgreement']) || !IsSet($_POST['AUP'])){
    16.        
    17.             $error[] = "Must commit to agreements.";
    18.         }
    19.  
    20.             foreach($_POST as $val){
    21.                
    22.                 if($val == ""){
    23.                
    24.                     $formIsEmpty = true;
    25.                    
    26.            
    27.                 }          
    28.             }
    29.            
    30.         if($formIsEmpty==true){
    31.                
    32.                 $error[] = "Empty fields.";
    33.                
    34.         }  
    35.        
    36.                 if($_POST['password'] != $_POST['password2']){
    37.                
    38.                         $error[] = "Passwords don't match. ";
    39.                    
    40.                     }
    41.                
    42.                         if(!strstr($_POST['email'],"@") && !strstr($_POST['email'],"@")){
    43.                    
    44.                             $error[] = "E-mail isn't valid. ";
    45.                
    46.                     }
    47.                
    48.                         if($_POST['password'] === $_POST['userName']){
    49.                    
    50.                             $error[] = "Password and Username match. ";
    51.                     }
    52.        
    53.             foreach($_POST as $val){
    54.                 if($val != ""){
    55.            
    56.                     $tempVal = $val;
    57.            
    58.                     $tempVal = str_replace("!", "NULL", $tempVal);
    59.                     $tempVal = str_replace("`", "NULL", $tempVal);
    60.                     $tempVal = str_replace("~", "NULL", $tempVal);
    61.                     $tempVal = str_replace("#", "NULL", $tempVal);
    62.                     $tempVal = str_replace("$", "NULL", $tempVal);
    63.                     $tempVal = str_replace("%", "NULL", $tempVal);
    64.                     $tempVal = str_replace("^", "NULL", $tempVal);
    65.                     $tempVal = str_replace("&", "NULL", $tempVal);
    66.                     $tempVal = str_replace("*", "NULL", $tempVal);
    67.                     $tempVal = str_replace("(", "NULL", $tempVal);
    68.                     $tempVal = str_replace( ")","NULL", $tempVal);
    69.                     $tempVal = str_replace("+", "NULL", $tempVal);
    70.                     $tempVal = str_replace("=", "NULL", $tempVal);
    71.                     $tempVal = str_replace("[", "NULL", $tempVal);
    72.                     $tempVal = str_replace("]", "NULL", $tempVal);
    73.                     $tempVal = str_replace("{", "NULL", $tempVal);
    74.                     $tempVal = str_replace("}", "NULL", $tempVal);
    75.                     $tempVal = str_replace(";", "NULL", $tempVal);
    76.                     $tempVal = str_replace(":", "NULL", $tempVal);          
    77.                     $tempVal = str_replace("'", "NULL", $tempVal);
    78.                     $tempVal = str_replace("\"","NULL", $tempVal);
    79.                     $tempVal = str_replace("|", "NULL", $tempVal);
    80.                     $tempVal = str_replace("<", "NULL", $tempVal);
    81.                     $tempVal = str_replace(">", "NULL", $tempVal);
    82.                     $tempVal = str_replace(",", "NULL", $tempVal);
    83.                     $tempVal = str_replace("?", "NULL", $tempVal);
    84.                     $tempVal = str_replace("/", "NULL", $tempVal);      
    85.                
    86.                                
    87.                 if($tempVal == "petNULLs nameNULL"){
    88.                
    89.                     $tempVal = "pet's name?";
    90.                
    91.                 }elseif($tempVal == "motherNULLs maiden nameNULL"){
    92.                
    93.                     $tempVal = "mother's maiden name?";                  
    94.                
    95.                 }elseif($tempVal == "favorite yearNULL"){
    96.                    
    97.                     $tempVal = "favorite year?";
    98.                 }  
    99.                
    100.                
    101.                 if($tempVal != $val){
    102.                        
    103.                     $error[] = "Special characters. ";                  
    104.                
    105.                 }elseif($tempVal == $val && IsSet($_POST['userAgreement']) && IsSet($_POST['AUP'])){
    106.                    
    107.                     $formDataSafe = true;
    108.                                    
    109.                                                
    110.                 }
    111.  
    112.             }
    113.         }
    114.     }      
    115.    
    116.             if($formDataSafe == true){
    117.            
    118.                 $sqlsystem->sqlConnect();
    119.                        
    120.             }
    121.            
    122.    
    123. ?>
    124.  
    125.  
    sql.class

    PHP:
    1. <?php
    2. //Remember to change the folder location of this file when site is launched.
    3. //Remember to make use of required file with variable. Couldn't make it
    4. //work.
    5. //require('/system/prime_system_data/sqlpassword.php');
    6. class sqlsystem{
    7.    
    8.     private $host = "localhost";
    9.     private $userName = "root";
    10.     private $password = "";
    11.     private $dbName = "famous4";
    12.     //variable host, userName, password, and database name.
    13.    
    14.     function sqlConnect()
    15.    
    16.     {
    17.    
    18.         mysql_connect($this->$host, $this->$userName, $this->$password);
    19.         mysql_select_db($this->$dbName);
    20.        
    21.     }
    22.  
    23. }
    24.  
    25.  
    26.  
    27. ?>
    Jeremy Benson, Nov 6, 2013 IP
  9. nico_swd

    nico_swd Prominent Member

    Messages:
    4,119
    Likes Received:
    331
    Best Answers:
    17
    Trophy Points:
    325
    #9
    If I can make a suggestion here, go with "another method", namely preg_match(). The ereg_* extension is deprecated and will be removed in the future.

    You got it almost right. It should be $this->dbName instead of $this->$dbName, etc...

    On a further note, the mysql_* extension is deprecated too. Not sure where you're learning from, but it sure must be an old book/site. Take a look at PDO instead. It also comes with an object orientated interface, so you don't have to create your own wrappers around existing APIs.

    One more thing. The foreach loop only checks if one of the submitted fields is empty. But nothing prevents me from removing a field before submitting the form, so I would be able to submit empty fields that you may consider "required".

    EDIT:

    For the past 10 years, since the release of the first PHP 5 RC, class constructors should be called __construct(), and not have the same name as the class itself. It will still work for backwards compatibility, but who knows for how much longer.

    http://us3.php.net/__construct

    I suggest you learn from another source, as the one you're currently using is horribly outdated.
    Last edited: Nov 6, 2013
    nico_swd, Nov 6, 2013 IP
  10. nico_swd

    nico_swd Prominent Member

    Messages:
    4,119
    Likes Received:
    331
    Best Answers:
    17
    Trophy Points:
    325
    #10
    Since you're learning, a few more suggestions:

    PHP:
    1.  
    2. strstr($_POST['email'],"@")
    3.  
    ... this is a very bad way of validating email addresses. It merely checks if it contains an @. This is a much better approach:
    PHP:
    1.  
    2. if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
    3. {
    4.     // invalid
    5. }
    6.  
    Calling str_replace() a million times in a row is slow (and not very elegant). Note that you can pass arrays to it, like so:
    PHP:
    1.  
    2. $replace = [')', '(', '#', '!', /* ... */];
    3. $tempVal = str_replace($replace, 'NULL', $tempVal);
    4.  
    This:
    PHP:
    1.  
    2. if($tempVal == "petNULLs nameNULL"){
    3.              
    4.                     $tempVal = "pet's name?";
    5.              
    6.                 }elseif($tempVal == "motherNULLs maiden nameNULL"){
    7.              
    8.                     $tempVal = "mother's maiden name?";                
    9.              
    10.                 }elseif($tempVal == "favorite yearNULL"){
    11.                  
    12.                     $tempVal = "favorite year?";
    13.                 }
    14.  
    ... is a dirty, dirty hack. If you don't want some fields to be filtered, you can do this:
    PHP:
    1.  
    2. $dontFilter = ['field1', 'field2', /* ... */];
    3.  
    4. foreach ($_POST AS $key => $val)
    5. {
    6.     // $key is the name of the form field.
    7.  
    8.     if (in_array($key, $dontFilter, true))
    9.     {
    10.          // Don't filter value
    11.     }
    12.     else
    13.     {
    14.          // Filter value
    15.     }
    16. }
    17.  
    But in general, I'm not a big fan of the loop. If you don't have hundreds of fields, I suggest you validate them manually. It's less hacky, and probably more secure.
    nico_swd, Nov 6, 2013 IP
  11. Jeremy Benson

    Jeremy Benson Member

    Messages:
    118
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    46
    #11
    hey, I'm sure the books are probably a bit outdated. Your help has been amazing, and the section of the code I'm definitely learning a lot here. I'm gonna go home, and start re-doing the code to your suggestions. I'm sure I'll have a ton more questions, as PDO is a bit foreign this point, but I did find a good forum tut. Also found a tut for preg_match which cleared a lot up, so I should be able to validate each expression in a lot less code.

    Thanks again :)
    Jeremy Benson, Nov 7, 2013 IP