Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 23
  1. #1
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Selecting current user's username from phpmyadmin database!

    Hi guys, first off - I'm new to back-end developing, I would love some help here, I've been searching tutorial and guides and forums for help for a while so I hope my search ends here..maybe my understanding and description skills are improving so lets hope

    I have a site with registering users, loging in and posting comments..I have a lot going on with different files and stuff i downloaded, but simply:

    I need help figuring out how to have the logged in user's username appear with their comments.

    I have a login page (index.php), and a user page once your'e logged in (login-home.php).
    I have a login page FILE (index.php), a user page FILE (login-home.php), a FILE for the comment body and coding (comment.class.php), a FILE that...I believe.. handles a lot of stuff I dont understand like login, register etc (include/fg_membersite.php).

    So the page with most things happening is: http://sidebet.mjrwebdesign.net/login-home.php , which you must be logged in to access. On my database I have a table called "users" which has columns called "name" "email" and "username".
    I can pull the email and name, but not the username when I rename it from:
    PHP Code:
    function UserEmail()
        {
            return isset(
    $_SESSION['email_of_user'])?$_SESSION['email_of_user']:'';
        } 
    to
    PHP Code:
    function UserEmail()
        {
            return isset(
    $_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
        } 
    Also, a strange thing to note is that I can successfully pull the email and name of a user on login-home.php BUT NOT when I put it inside the comment.class.php html(output comments).

    PHP Code:
    <div class="comment">
                                    
                    <!--<p>USERNAME GOES HERE I tried <?= $fgmembersite->UserFullName(); ?> but it prints out: UserFullName(); ?></p>-->
                    <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
                    <p class="thecomment">'.$d['body'].'</p>
                </div>
    :`( please help

  • #2
    Regular Coder
    Join Date
    Sep 2011
    Posts
    408
    Thanks
    18
    Thanked 26 Times in 26 Posts
    What is setting the session variables? Either var_export $_SESSION and see what variables you have available or post the code which sets the session variables as well as where it gets the information from (ex. query).

  • Users who have thanked Dubz for this post:

    mjrzasa (04-26-2014)

  • #3
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Honestly bro, I don't know too much about this but I think I understand what you're asking. I have a big ol file called fg_membersite.php that is inside an include folder on the server. That has a lot of functions and stuff. This is it:

    PHP Code:
    <?PHP
    /*
        Registration/Login script from HTML Form Guide
        V1.0

        This program is free software published under the
        terms of the GNU Lesser General Public License.
        http://www.gnu.org/copyleft/lesser.html
        

    This program is distributed in the hope that it will
    be useful - WITHOUT ANY WARRANTY; without even the
    implied warranty of MERCHANTABILITY or FITNESS FOR A
    PARTICULAR PURPOSE.

    For updates, please visit:
    http://www.html-form-guide.com/php-form/php-registration-form.html
    http://www.html-form-guide.com/php-form/php-login-form.html

    */
    require_once("class.phpmailer.php");
    require_once(
    "formvalidator.php");

    class 
    FGMembersite
    {
        var 
    $admin_email;
        var 
    $from_address;
        
        var 
    $username;
        var 
    $pwd;
        var 
    $database;
        var 
    $tablename;
        var 
    $connection;
        var 
    $rand_key;
        
        var 
    $error_message;
        
        
    //-----Initialization -------
        
    function FGMembersite()
        {
            
    $this->sitename 'YourWebsiteName.com';
            
    $this->rand_key '0iQx5oBk66oVZep';
        }
        
        function 
    InitDB($host,$uname,$pwd,$database,$tablename)
        {
            
    $this->db_host  $host;
            
    $this->username $uname;
            
    $this->pwd  $pwd;
            
    $this->database  $database;
            
    $this->tablename $tablename;
            
        }
        function 
    SetAdminEmail($email)
        {
            
    $this->admin_email $email;
        }
        
        function 
    SetWebsiteName($sitename)
        {
            
    $this->sitename $sitename;
        }
        
        function 
    SetRandomKey($key)
        {
            
    $this->rand_key $key;
        }
        
        
    //-------Main Operations ----------------------
        
    function RegisterUser()
        {
            if(!isset(
    $_POST['submitted']))
            {
               return 
    false;
            }
            
            
    $formvars = array();
            
            if(!
    $this->ValidateRegistrationSubmission())
            {
                return 
    false;
            }
            
            
    $this->CollectRegistrationSubmission($formvars);
            
            if(!
    $this->SaveToDatabase($formvars))
            {
                return 
    false;
            }
            
            if(!
    $this->SendUserConfirmationEmail($formvars))
            {
                return 
    false;
            }

            
    $this->SendAdminIntimationEmail($formvars);
            
            return 
    true;
        }

        function 
    ConfirmUser()
        {
            if(empty(
    $_GET['code'])||strlen($_GET['code'])<=10)
            {
                
    $this->HandleError("Please provide the confirm code");
                return 
    false;
            }
            
    $user_rec = array();
            if(!
    $this->UpdateDBRecForConfirmation($user_rec))
            {
                return 
    false;
            }
            
            
    $this->SendUserWelcomeEmail($user_rec);
            
            
    $this->SendAdminIntimationOnRegComplete($user_rec);
            
            return 
    true;
        }    
        
        function 
    Login()
        {
            if(empty(
    $_POST['username']))
            {
                
    $this->HandleError("UserName is empty!");
                return 
    false;
            }
            
            if(empty(
    $_POST['password']))
            {
                
    $this->HandleError("Password is empty!");
                return 
    false;
            }
            
            
    $username trim($_POST['username']);
            
    $password trim($_POST['password']);
            
            if(!isset(
    $_SESSION)){ session_start(); }
            if(!
    $this->CheckLoginInDB($username,$password))
            {
                return 
    false;
            }
            
            
    $_SESSION[$this->GetLoginSessionVar()] = $username;
            
            return 
    true;
        }
        
        function 
    CheckLogin()
        {
             if(!isset(
    $_SESSION)){ session_start(); }

             
    $sessionvar $this->GetLoginSessionVar();
             
             if(empty(
    $_SESSION[$sessionvar]))
             {
                return 
    false;
             }
             return 
    true;
        }
        
        function 
    UserFullName()
        {
            return isset(
    $_SESSION['name_of_user'])?$_SESSION['name_of_user']:'';
        }

        function 
    UserEmail()
        {
            return isset(
    $_SESSION['email_of_user'])?$_SESSION['email_of_user']:'';
        }

        function 
    MyHandle()
        {
            return isset(
    $_SESSION['username_of_user'])?$_SESSION['username_of_user']:'';
        }
        
        function 
    LogOut()
        {
            
    session_start();
            
            
    $sessionvar $this->GetLoginSessionVar();
            
            
    $_SESSION[$sessionvar]=NULL;
            
            unset(
    $_SESSION[$sessionvar]);
        }
        
        function 
    EmailResetPasswordLink()
        {
            if(empty(
    $_POST['email']))
            {
                
    $this->HandleError("Email is empty!");
                return 
    false;
            }
            
    $user_rec = array();
            if(
    false === $this->GetUserFromEmail($_POST['email'], $user_rec))
            {
                return 
    false;
            }
            if(
    false === $this->SendResetPasswordLink($user_rec))
            {
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    ResetPassword()
        {
            if(empty(
    $_GET['email']))
            {
                
    $this->HandleError("Email is empty!");
                return 
    false;
            }
            if(empty(
    $_GET['code']))
            {
                
    $this->HandleError("reset code is empty!");
                return 
    false;
            }
            
    $email trim($_GET['email']);
            
    $code trim($_GET['code']);
            
            if(
    $this->GetResetPasswordCode($email) != $code)
            {
                
    $this->HandleError("Bad reset code!");
                return 
    false;
            }
            
            
    $user_rec = array();
            if(!
    $this->GetUserFromEmail($email,$user_rec))
            {
                return 
    false;
            }
            
            
    $new_password $this->ResetUserPasswordInDB($user_rec);
            if(
    false === $new_password || empty($new_password))
            {
                
    $this->HandleError("Error updating new password");
                return 
    false;
            }
            
            if(
    false == $this->SendNewPassword($user_rec,$new_password))
            {
                
    $this->HandleError("Error sending new password");
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    ChangePassword()
        {
            if(!
    $this->CheckLogin())
            {
                
    $this->HandleError("Not logged in!");
                return 
    false;
            }
            
            if(empty(
    $_POST['oldpwd']))
            {
                
    $this->HandleError("Old password is empty!");
                return 
    false;
            }
            if(empty(
    $_POST['newpwd']))
            {
                
    $this->HandleError("New password is empty!");
                return 
    false;
            }
            
            
    $user_rec = array();
            if(!
    $this->GetUserFromEmail($this->UserEmail(),$user_rec))
            {
                return 
    false;
            }
            
            
    $pwd trim($_POST['oldpwd']);
            
            if(
    $user_rec['password'] != md5($pwd))
            {
                
    $this->HandleError("The old password does not match!");
                return 
    false;
            }
            
    $newpwd trim($_POST['newpwd']);
            
            if(!
    $this->ChangePasswordInDB($user_rec$newpwd))
            {
                return 
    false;
            }
            return 
    true;
        }
        
        
    //-------Public Helper functions -------------
        
    function GetSelfScript()
        {
            return 
    htmlentities($_SERVER['PHP_SELF']);
        }    
        
        function 
    SafeDisplay($value_name)
        {
            if(empty(
    $_POST[$value_name]))
            {
                return
    '';
            }
            return 
    htmlentities($_POST[$value_name]);
        }
        
        function 
    RedirectToURL($url)
        {
            
    header("Location: $url");
            exit;
        }
        
        function 
    GetSpamTrapInputName()
        {
            return 
    'sp'.md5('KHGdnbvsgst'.$this->rand_key);
        }
        
        function 
    GetErrorMessage()
        {
            if(empty(
    $this->error_message))
            {
                return 
    '';
            }
            
    $errormsg nl2br(htmlentities($this->error_message));
            return 
    $errormsg;
        }

  • #4
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Sorry the file is so big I had to cut it into two posts:

    PHP Code:
        //-------Private Helper functions-----------
        
        
    function HandleError($err)
        {
            
    $this->error_message .= $err."\r\n";
        }
        
        function 
    HandleDBError($err)
        {
            
    $this->HandleError($err."\r\n mysqlerror:".mysql_error());
        }
        
        function 
    GetFromAddress()
        {
            if(!empty(
    $this->from_address))
            {
                return 
    $this->from_address;
            }

            
    $host $_SERVER['SERVER_NAME'];

            
    $from ="nobody@$host";
            return 
    $from;
        } 
        
        function 
    GetLoginSessionVar()
        {
            
    $retvar md5($this->rand_key);
            
    $retvar 'usr_'.substr($retvar,0,10);
            return 
    $retvar;
        }
        
        function 
    CheckLoginInDB($username,$password)
        {
            if(!
    $this->DBLogin())
            {
                
    $this->HandleError("Database login failed!");
                return 
    false;
            }          
            
    $username $this->SanitizeForSQL($username);
            
    $pwdmd5 md5($password);
            
    $qry "Select name, email from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";
            
            
    $result mysql_query($qry,$this->connection);
            
            if(!
    $result || mysql_num_rows($result) <= 0)
            {
                
    $this->HandleError("Error logging in. The username or password does not match");
                return 
    false;
            }
            
            
    $row mysql_fetch_assoc($result);
            
            
            
    $_SESSION['name_of_user']  = $row['name'];
            
    $_SESSION['email_of_user'] = $row['email'];
            
    $_SESSION['username_of_user'] = $row['username'];
            
            return 
    true;
        }
        
        function 
    UpdateDBRecForConfirmation(&$user_rec)
        {
            if(!
    $this->DBLogin())
            {
                
    $this->HandleError("Database login failed!");
                return 
    false;
            }   
            
    $confirmcode $this->SanitizeForSQL($_GET['code']);
            
            
    $result mysql_query("Select name, email from $this->tablename where confirmcode='$confirmcode'",$this->connection);   
            if(!
    $result || mysql_num_rows($result) <= 0)
            {
                
    $this->HandleError("Wrong confirm code.");
                return 
    false;
            }
            
    $row mysql_fetch_assoc($result);
            
    $user_rec['name'] = $row['name'];
            
    $user_rec['email']= $row['email'];
            
    $user_rec['username']= $row['username'];
            
            
            
    $qry "Update $this->tablename Set confirmcode='y' Where  confirmcode='$confirmcode'";
            
            if(!
    mysql_query$qry ,$this->connection))
            {
                
    $this->HandleDBError("Error inserting data to the table\nquery:$qry");
                return 
    false;
            }      
            return 
    true;
        }
        
        function 
    ResetUserPasswordInDB($user_rec)
        {
            
    $new_password substr(md5(uniqid()),0,10);
            
            if(
    false == $this->ChangePasswordInDB($user_rec,$new_password))
            {
                return 
    false;
            }
            return 
    $new_password;
        }
        
        function 
    ChangePasswordInDB($user_rec$newpwd)
        {
            
    $newpwd $this->SanitizeForSQL($newpwd);
            
            
    $qry "Update $this->tablename Set password='".md5($newpwd)."' Where  id_user=".$user_rec['id_user']."";
            
            if(!
    mysql_query$qry ,$this->connection))
            {
                
    $this->HandleDBError("Error updating the password \nquery:$qry");
                return 
    false;
            }     
            return 
    true;
        }
        
        function 
    GetUserFromEmail($email,&$user_rec)
        {
            if(!
    $this->DBLogin())
            {
                
    $this->HandleError("Database login failed!");
                return 
    false;
            }   
            
    $email $this->SanitizeForSQL($email);
            
            
    $result mysql_query("Select * from $this->tablename where email='$email'",$this->connection);  

            if(!
    $result || mysql_num_rows($result) <= 0)
            {
                
    $this->HandleError("There is no user with email: $email");
                return 
    false;
            }
            
    $user_rec mysql_fetch_assoc($result);

            
            return 
    true;
        }
        
        function 
    SendUserWelcomeEmail(&$user_rec)
        {
            
    $mailer = new PHPMailer();
            
            
    $mailer->CharSet 'utf-8';
            
            
    $mailer->AddAddress($user_rec['email'],$user_rec['name']);
            
            
    $mailer->Subject "Welcome to ".$this->sitename;

            
    $mailer->From $this->GetFromAddress();        
            
            
    $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
            
    "Welcome! Your registration  with ".$this->sitename." is completed.\r\n".
            
    "\r\n".
            
    "Regards,\r\n".
            
    "Webmaster\r\n".
            
    $this->sitename;

            if(!
    $mailer->Send())
            {
                
    $this->HandleError("Failed sending user welcome email.");
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    SendAdminIntimationOnRegComplete(&$user_rec)
        {
            if(empty(
    $this->admin_email))
            {
                return 
    false;
            }
            
    $mailer = new PHPMailer();
            
            
    $mailer->CharSet 'utf-8';
            
            
    $mailer->AddAddress($this->admin_email);
            
            
    $mailer->Subject "Registration Completed: ".$user_rec['name'];

            
    $mailer->From $this->GetFromAddress();         
            
            
    $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
            
    "Name: ".$user_rec['name']."\r\n".
            
    "Email address: ".$user_rec['email']."\r\n";
            
            if(!
    $mailer->Send())
            {
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    GetResetPasswordCode($email)
        {
           return 
    substr(md5($email.$this->sitename.$this->rand_key),0,10);
        }
        
        function 
    SendResetPasswordLink($user_rec)
        {
            
    $email $user_rec['email'];
            
            
    $mailer = new PHPMailer();
            
            
    $mailer->CharSet 'utf-8';
            
            
    $mailer->AddAddress($email,$user_rec['name']);
            
            
    $mailer->Subject "Your reset password request at ".$this->sitename;

            
    $mailer->From $this->GetFromAddress();
            
            
    $link $this->GetAbsoluteURLFolder().
                    
    '/resetpwd.php?email='.
                    
    urlencode($email).'&code='.
                    
    urlencode($this->GetResetPasswordCode($email));

            
    $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
            
    "There was a request to reset your password at ".$this->sitename."\r\n".
            
    "Please click the link below to complete the request: \r\n".$link."\r\n".
            
    "Regards,\r\n".
            
    "Webmaster\r\n".
            
    $this->sitename;
            
            if(!
    $mailer->Send())
            {
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    SendNewPassword($user_rec$new_password)
        {
            
    $email $user_rec['email'];
            
            
    $mailer = new PHPMailer();
            
            
    $mailer->CharSet 'utf-8';
            
            
    $mailer->AddAddress($email,$user_rec['name']);
            
            
    $mailer->Subject "Your new password for ".$this->sitename;

            
    $mailer->From $this->GetFromAddress();
            
            
    $mailer->Body ="Hello ".$user_rec['name']."\r\n\r\n".
            
    "Your password is reset successfully. ".
            
    "Here is your updated login:\r\n".
            
    "username:".$user_rec['username']."\r\n".
            
    "password:$new_password\r\n".
            
    "\r\n".
            
    "Login here: ".$this->GetAbsoluteURLFolder()."/login.php\r\n".
            
    "\r\n".
            
    "Regards,\r\n".
            
    "Webmaster\r\n".
            
    $this->sitename;
            
            if(!
    $mailer->Send())
            {
                return 
    false;
            }
            return 
    true;
        }    
        
        function 
    ValidateRegistrationSubmission()
        {
            
    //This is a hidden input field. Humans won't fill this field.
            
    if(!empty($_POST[$this->GetSpamTrapInputName()]) )
            {
                
    //The proper error is not given intentionally
                
    $this->HandleError("Automated submission prevention: case 2 failed");
                return 
    false;
            }
            
            
    $validator = new FormValidator();
            
    $validator->addValidation("name","req","Please fill in Name");
            
    $validator->addValidation("email","email","The input for Email should be a valid email value");
            
    $validator->addValidation("email","req","Please fill in Email");
            
    $validator->addValidation("username","req","Please fill in UserName");
            
    $validator->addValidation("password","req","Please fill in Password");

            
            if(!
    $validator->ValidateForm())
            {
                
    $error='';
                
    $error_hash $validator->GetErrors();
                foreach(
    $error_hash as $inpname => $inp_err)
                {
                    
    $error .= $inpname.':'.$inp_err."\n";
                }
                
    $this->HandleError($error);
                return 
    false;
            }        
            return 
    true;
        }
        
        function 
    CollectRegistrationSubmission(&$formvars)
        {
            
    $formvars['name'] = $this->Sanitize($_POST['name']);
            
    $formvars['email'] = $this->Sanitize($_POST['email']);
            
    $formvars['username'] = $this->Sanitize($_POST['username']);
            
    $formvars['password'] = $this->Sanitize($_POST['password']);
        }
        
        function 
    SendUserConfirmationEmail(&$formvars)
        {
            
    $mailer = new PHPMailer();
            
            
    $mailer->CharSet 'utf-8';
            
            
    $mailer->AddAddress($formvars['email'],$formvars['name']);
            
            
    $mailer->Subject "Your registration with ".$this->sitename;

            
    $mailer->From $this->GetFromAddress();        
            
            
    $confirmcode $formvars['confirmcode'];
            
            
    $confirm_url $this->GetAbsoluteURLFolder().'/confirmreg.php?code='.$confirmcode;
            
            
    $mailer->Body ="Hello ".$formvars['name']."\r\n\r\n".
            
    "Thanks for your registration with ".$this->sitename."\r\n".
            
    "Please click the link below to confirm your registration.\r\n".
            
    "$confirm_url\r\n".
            
    "\r\n".
            
    "Regards,\r\n".
            
    "Webmaster\r\n".
            
    $this->sitename;

            if(!
    $mailer->Send())
            {
                
    $this->HandleError("Failed sending registration confirmation email.");
                return 
    false;
            }
            return 
    true;
        }
        function 
    GetAbsoluteURLFolder()
        {
            
    $scriptFolder = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) ? 'https://' 'http://';
            
    $scriptFolder .= $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);
            return 
    $scriptFolder;
        }
        
        function 
    SendAdminIntimationEmail(&$formvars)
        {
            if(empty(
    $this->admin_email))
            {
                return 
    false;
            }
            
    $mailer = new PHPMailer();
            
            
    $mailer->CharSet 'utf-8';
            
            
    $mailer->AddAddress($this->admin_email);
            
            
    $mailer->Subject "New registration: ".$formvars['name'];

            
    $mailer->From $this->GetFromAddress();         
            
            
    $mailer->Body ="A new user registered at ".$this->sitename."\r\n".
            
    "Name: ".$formvars['name']."\r\n".
            
    "Email address: ".$formvars['email']."\r\n".
            
    "UserName: ".$formvars['username'];
            
            if(!
    $mailer->Send())
            {
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    SaveToDatabase(&$formvars)
        {
            if(!
    $this->DBLogin())
            {
                
    $this->HandleError("Database login failed!");
                return 
    false;
            }
            if(!
    $this->Ensuretable())
            {
                return 
    false;
            }
            if(!
    $this->IsFieldUnique($formvars,'email'))
            {
                
    $this->HandleError("This email is already registered");
                return 
    false;
            }
            
            if(!
    $this->IsFieldUnique($formvars,'username'))
            {
                
    $this->HandleError("This UserName is already used. Please try another username");
                return 
    false;
            }        
            if(!
    $this->InsertIntoDB($formvars))
            {
                
    $this->HandleError("Inserting to Database failed!");
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    IsFieldUnique($formvars,$fieldname)
        {
            
    $field_val $this->SanitizeForSQL($formvars[$fieldname]);
            
    $qry "select username from $this->tablename where $fieldname='".$field_val."'";
            
    $result mysql_query($qry,$this->connection);   
            if(
    $result && mysql_num_rows($result) > 0)
            {
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    DBLogin()
        {

            
    $this->connection mysql_connect($this->db_host,$this->username,$this->pwd);

            if(!
    $this->connection)
            {   
                
    $this->HandleDBError("Database Login failed! Please make sure that the DB login credentials provided are correct");
                return 
    false;
            }
            if(!
    mysql_select_db($this->database$this->connection))
            {
                
    $this->HandleDBError('Failed to select database: '.$this->database.' Please make sure that the database name provided is correct');
                return 
    false;
            }
            if(!
    mysql_query("SET NAMES 'UTF8'",$this->connection))
            {
                
    $this->HandleDBError('Error setting utf8 encoding');
                return 
    false;
            }
            return 
    true;
        }    
        
        function 
    Ensuretable()
        {
            
    $result mysql_query("SHOW COLUMNS FROM $this->tablename");   
            if(!
    $result || mysql_num_rows($result) <= 0)
            {
                return 
    $this->CreateTable();
            }
            return 
    true;
        }
        
        function 
    CreateTable()
        {
            
    $qry "Create Table $this->tablename (".
                    
    "id_user INT NOT NULL AUTO_INCREMENT ,".
                    
    "name VARCHAR( 128 ) NOT NULL ,".
                    
    "email VARCHAR( 64 ) NOT NULL ,".
                    
    "phone_number VARCHAR( 16 ) NOT NULL ,".
                    
    "username VARCHAR( 16 ) NOT NULL ,".
                    
    "password VARCHAR( 32 ) NOT NULL ,".
                    
    "confirmcode VARCHAR(32) ,".
                    
    "PRIMARY KEY ( id_user )".
                    
    ")";
                    
            if(!
    mysql_query($qry,$this->connection))
            {
                
    $this->HandleDBError("Error creating the table \nquery was\n $qry");
                return 
    false;
            }
            return 
    true;
        }
        
        function 
    InsertIntoDB(&$formvars)
        {
        
            
    $confirmcode $this->MakeConfirmationMd5($formvars['email']);
            
            
    $formvars['confirmcode'] = $confirmcode;
            
            
    $insert_query 'insert into '.$this->tablename.'(
                    name,
                    email,
                    username,
                    password,
                    confirmcode
                    )
                    values
                    (
                    "' 
    $this->SanitizeForSQL($formvars['name']) . '",
                    "' 
    $this->SanitizeForSQL($formvars['email']) . '",
                    "' 
    $this->SanitizeForSQL($formvars['username']) . '",
                    "' 
    md5($formvars['password']) . '",
                    "' 
    $confirmcode '"
                    )'
    ;      
            if(!
    mysql_query$insert_query ,$this->connection))
            {
                
    $this->HandleDBError("Error inserting data to the table\nquery:$insert_query");
                return 
    false;
            }        
            return 
    true;
        }
        function 
    MakeConfirmationMd5($email)
        {
            
    $randno1 rand();
            
    $randno2 rand();
            return 
    md5($email.$this->rand_key.$randno1.''.$randno2);
        }
        function 
    SanitizeForSQL($str)
        {
            if( 
    function_exists"mysql_real_escape_string" ) )
            {
                  
    $ret_str mysql_real_escape_string$str );
            }
            else
            {
                  
    $ret_str addslashes$str );
            }
            return 
    $ret_str;
        }
        
     
    /*
        Sanitize() function removes any potential threat from the
        data submitted. Prevents email injections or any other hacker attempts.
        if $remove_nl is true, newline chracters are removed from the input.
        */
        
    function Sanitize($str,$remove_nl=true)
        {
            
    $str $this->StripSlashes($str);

            if(
    $remove_nl)
            {
                
    $injections = array('/(\n+)/i',
                    
    '/(\r+)/i',
                    
    '/(\t+)/i',
                    
    '/(%0A+)/i',
                    
    '/(%0D+)/i',
                    
    '/(%08+)/i',
                    
    '/(%09+)/i'
                    
    );
                
    $str preg_replace($injections,'',$str);
            }

            return 
    $str;
        }    
        function 
    StripSlashes($str)
        {
            if(
    get_magic_quotes_gpc())
            {
                
    $str stripslashes($str);
            }
            return 
    $str;
        }    
    }
    ?> 

  • #5
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    And This is the file that takes people's posts and displays them, it is called comment.class.php :

    PHP Code:
    <?php

    class Comment
    {
        private 
    $data = array();
        
        public function 
    __construct($row)
        {
            
    /*
            /    The constructor
            */
            
            
    $this->data $row;
        }

        public function 
    markup()
        {
            
    /*
            /    This method outputs the XHTML markup of the comment
            */
            
            // Setting up an alias, so we don't have to write $this->data every time:
            
    $d = &$this->data;
            
            
    $link_open '';
            
    $link_close '';
            
            if(
    $d['url']){
                
                
    // If the person has entered a URL when adding a comment,
                // define opening and closing hyperlink tags
                
                
    $link_open '<a href="'.$d['url'].'">';
                
    $link_close =  '</a>';
            }
            
            
    // Converting the time to a UNIX timestamp:
            
    $d['dt'] = strtotime($d['dt']);
            
            
    // Needed for the default gravatar image:
            
    $url 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
            
            return 
    '
            
                <div class="comment">
                                    
                    <!--  <p>USERNAME GOES HERE</p>  -->
                    <div class="date" title="Added at '
    .date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
                    <p class="thecomment">'
    .$d['body'].'</p>
                </div>


            '
    ;
        }
        
        public static function 
    validate(&$arr)
        {
            
    /*
            /    This method is used to validate the data sent via AJAX.
            /
            /    It return true/false depending on whether the data is valid, and populates
            /    the $arr array passed as a paremter (notice the ampersand above) with
            /    either the valid input data, or the error messages.
            */
            
            
    $errors = array();
            
    $data    = array();
            
            
    // Using the filter_input function introduced in PHP 5.2.0
            
            
            
            // Using the filter with a custom callback function:
            
            
    if(!($data['body'] = filter_input(INPUT_POST,'body',FILTER_CALLBACK,array('options'=>'Comment::validate_text'))))
            {
                
    $errors['body'] = 'Please enter a comment.';
            }
            
                    
            if(!empty(
    $errors)){
                
                
    // If there are errors, copy the $errors array to $arr:
                
                
    $arr $errors;
                return 
    false;
            }
            
            
    // If the data is valid, sanitize all the data and copy it to $arr:
            
            
    foreach($data as $k=>$v){
                
    $arr[$k] = mysql_real_escape_string($v);
            }
            
            
    // Ensure that the email is lower case:
            
            
    $arr['email'] = strtolower(trim($arr['email']));
            
            return 
    true;
            
        }

        private static function 
    validate_text($str)
        {
            
    /*
            /    This method is used internally as a FILTER_CALLBACK
            */
            
            
    if(mb_strlen($str,'utf8')<1)
                return 
    false;
            
            
    // Encode all html special characters (<, >, ", & .. etc) and convert
            // the new line characters to <br> tags:
            
            
    $str nl2br(htmlspecialchars($str));
            
            
    // Remove the new line characters that are left
            
    $str str_replace(array(chr(10),chr(13)),'',$str);
            
            return 
    $str;
        }

    }

    ?>

  • #6
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    And this is my index.php with the login form:
    PHP Code:
    <?php /* Template Name: The P - Board
    */ 
    ?>

    <?PHP
    require_once("./include/membersite_config.php");

    if(isset(
    $_POST['submitted']))
    {
       if(
    $fgmembersite->Login())
       {
            
    $fgmembersite->RedirectToURL("login-home.php");
       }
    }

    ?>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <html>
    <head>
    <title>Side Bet!</title>

    <link rel="stylesheet" type="text/css" href="pboard.css">
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
          <title>Login</title>
          <link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css" />
          <script type='text/javascript' src='scripts/gen_validatorv31.js'></script>

    </head>
    <body>

    <div class="container">

     <div id="title">
      <div class="shadow">SIDE BET!</div>
        <div class="shadow2">"How Much You Wanna Bet?!"</div>
     </div> <!-- close title -->
     <div class="nav">
      <table id="sports">
         <tr>
          <td><a href="nfl.php"><img class="icon" src="images/football.png" alt="NFL"></a></td>
            <td><a href="mlb.php"><img class="icon" src="images/baseball.png" alt="MLB"></a></td>
            <td><a href="nba.php"><img class="icon" src="images/basketball.png" alt="NBA"></a></td>
            <td><a href="nhl.php"><img class="icon" src="images/hockey.png" alt="NHL"></a></td>
       </tr>
         <tr>
          <td><a href="nfl.php" class="label">NFL</a></td>
            <td><a href="mlb.php" class="label">MLB</a></td>
            <td><a href="nba.php" class="label">NBA</a></td>
            <td><a href="nhl.php" class="label">NHL</a></td>
         </tr>
        </table>
     </div> <!-- close nav -->
     
      <div class="main">
        
        <div class="left">
          <a class="menu" href="login-home.php">Home</a><br>
          <a class="menu" href="archive.php">Archive</a><br>
            <a class="menu" href="http://www.espn.com">News</a><br>
         </div> <!-- close left -->
         
         <div class="right">
           <div class="menuright">Login</div>

             <!-- Form Code Start -->
    <div id='fg_membersite'>
    <form class="loginform" id='login' action='<?php echo $fgmembersite->GetSelfScript(); ?>' method='post' accept-charset='UTF-8'>


    <input type='hidden' name='submitted' id='submitted' value='1'/>



    <div><span class='error'><?php echo $fgmembersite->GetErrorMessage(); ?></span></div>
    <div class='container2'>
        <label for='username' >U:</label>
        <input type='text' name='username' id='username' value='<?php echo $fgmembersite->SafeDisplay('username'?>' maxlength="50" /><br/>
        <span id='login_username_errorloc' class='error'></span>
    </div>
    <div class='container2'>
        <label for='password' >P:</label>
        <input type='password' name='password' id='password' maxlength="50" /><br/>
        <span id='login_password_errorloc' class='error'></span>
    </div>

    <div class='container2'>
        <input id="log" type='submit' name='Submit' value='SUBMIT' />
    </div>


    </form>
    <!-- client-side Form Validations:
    Uses the excellent form validation script from JavaScript-coder.com-->

    <script type='text/javascript'>
    // <![CDATA[

        var frmvalidator  = new Validator("login");
        frmvalidator.EnableOnPageErrorDisplay();
        frmvalidator.EnableMsgsTogether();

        frmvalidator.addValidation("username","req","Please provide your username");
        
        frmvalidator.addValidation("password","req","Please provide the password");

    // ]]>
    </script>
    </div>
    <!--
    Form Code End (see html-form-guide.com for more info.)
    -->
              <div class="forgot">
               Forgot Your Password?<br>
                 <a class="menu" href="contact.php">Contact Me!</a>            
              </div> <!-- close forgot -->
             <div class="register">
              Not a Member? <a class="menu" href="register.php">Register!</a>
             </div> <!-- close register-->
                     
        
         </div> <!-- close right -->
             <div class="regorcont">
         
          <p class="hitmeup">Join The Ranks!</p>
            Oh so you want to join the club? A few things first. You need to create a username that you will be known by.
            This is the name that will show next to your posts, also the email you fill in will be how I contact you if you ever need assistance.
            Lastly, make sure you pick a password that you will remember. Head over <a class="menu" href="register.php">HERE</a> to sign up! Get to it!<br><br>
                            
          </div> <!-- close regorcont -->
            
            </div> <!-- close main -->
            
            <div class="footmenu">
           <a class="footlinks" href="login-home.php">Home</a>
             <a class="footlinks" href="register.php">Register</a>
             <a class="footlinks2" href="contact.php">Contact Me</a>
            </div> <!-- close footmenu -->     

    </div> <!-- close container -->

    </body>
    </html>

  • #7
    Regular Coder
    Join Date
    Sep 2011
    Posts
    408
    Thanks
    18
    Thanked 26 Times in 26 Posts
    To help get a better understanding of what's already set, do var_export($_SESSION); on the logged in page and post the results.

  • #8
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Omg thats awesome dude, thanks! Here are the results:
    PHP Code:
    array (
      
    'name_of_user' => 'Matthew Rzasa',
      
    'email_of_user' => 'matt@mjrwebdesign.net',
      
    'username_of_user' => NULL,
      
    'usr_87601d2e30' => 'mjrzasa',


  • #9
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Okay, so I created this:
    PHP Code:
    function MyHandle()
        {
            return isset(
    $_SESSION['usr_87601d2e30'])?$_SESSION['usr_87601d2e30']:'';
        } 
    And, testing it on the member page, I test it in two spots:
    PHP Code:
    <textarea  name="body" class="newmess" id="body" maxlength="200"><?= $fgmembersite->MyHandle(); ?></textarea>
    And it outputs: mjrzasa. thats what I want... but then I put it in my comment.class.php file (i have the entire code for that posted a few posts up) here:
    PHP Code:
    <div class="comment">
                                    
                <p>USERNAME GOES HERE <?= $fgmembersite->MyHandle(); ?></p>
                    <div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
                    <p class="thecomment">'.$d['body'].'</p>
                </div>
    And that outputs: USERNAME GOES HERE MyHandle(); ?>
    Then when I try <? echo '$fgmembersite->MyHandle();' ?> .... the page wont even load. Thanks for the help so far, I learned something already, and feel close to the solution!!

  • #10
    Regular Coder
    Join Date
    Sep 2011
    Posts
    408
    Thanks
    18
    Thanked 26 Times in 26 Posts
    The problem you're having is that the username is being set to a different variable ('usr_87601d2e30' in this case). I'm not sure whether it needs to be set there or not, but you could set it to the other ('username_of_user') at the same time to have the value stored, or simply change the key for the variable to match it.

    UPDATE (before post lol):
    In your function function CheckLoginInDB($username,$password), you aren't selecting the username from the table but you try to set it to the session variable later down in the function. Add username to the selection and that should fix that problem

    Edit:
    I don't see where the variable $_SESSION['usr_87601d2e30'] is even set. Make sure you unset and destroy the session in the logout, ESPECIALLY when under development. Otherwise, you may leave variables behind that you didn't intend to.
    Last edited by Dubz; 04-27-2014 at 11:45 AM.

  • #11
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks for the reply. Sorry I don't know what you mean by add username to the selection and destroy the session? You mean in logout.php ?

    Don't know if this matters but maybe it will show some insight.. my site recognizes when a user is logged in and on my login-home.php a function works to welcome user by name or email. Also I try two usernames and they display each others name and email correctly so I don't know if that means sessions are being ended correctly..or is that what you meant?

  • #12
    Regular Coder
    Join Date
    Sep 2011
    Posts
    408
    Thanks
    18
    Thanked 26 Times in 26 Posts
    PHP Code:
    function CheckLoginInDB($username,$password)
        {
            if(!
    $this->DBLogin())
            {
                
    $this->HandleError("Database login failed!");
                return 
    false;
            }          
            
    $username $this->SanitizeForSQL($username);
            
    $pwdmd5 md5($password);
            
    #Change this
            
    $qry "Select name, email from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";
            
    #To this (add username to the select list)
            
    $qry "Select name, email, username from $this->tablename where username='$username' and password='$pwdmd5' and confirmcode='y'";
            
            
    $result mysql_query($qry,$this->connection);
            
            if(!
    $result || mysql_num_rows($result) <= 0)
            {
                
    $this->HandleError("Error logging in. The username or password does not match");
                return 
    false;
            }
            
            
    $row mysql_fetch_assoc($result);
            
            
            
    $_SESSION['name_of_user']  = $row['name'];
            
    $_SESSION['email_of_user'] = $row['email'];
            
    $_SESSION['username_of_user'] = $row['username'];
            
            return 
    true;
        } 
    I added comments in for what I was talking about in regards to the actual login process

    As for the session_unset(); and session_destroy();, be sure those are called when the logout is finished. Those functions will erase all of the session data and destroy the session (unset then destroy). This ensures the credentials/data doesn't get mixed upon logout/login and ensures a full logout of the user.

  • Users who have thanked Dubz for this post:

    mjrzasa (04-28-2014)

  • #13
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Alright, cool, that results in now:
    PHP Code:
    array (
      
    'name_of_user' => 'Matthew Rzasa',
      
    'email_of_user' => 'matt@mjrwebdesign.net',
      
    'username_of_user' => 'mjrzasa',
      
    'usr_87601d2e30' => 'mjrzasa',

    Okay that's great, but now it doesnt work inside the comment though. Check picture please to see what I mean.Selecting current user's username from phpmyadmin database!-explained.jpg

  • #14
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    OMFG! I DID ITT!!!!! I simply put in:
    PHP Code:
    '.$_SESSION['username_of_user'].' 
    IT WORKS YAAAAAAAAAAAAAAAAYYYYYYYYYYYYY!! THANK YOU SO MUCH FOR YOUR HELP!

  • #15
    New Coder
    Join Date
    Apr 2014
    Posts
    15
    Thanks
    2
    Thanked 0 Times in 0 Posts
    CRAP. It now displays the username of the currently logged in user...what I want it to do is to display the username of the user that makes the post and is logged in at THE TIME OF THE POST and who is the one that submits the post


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •