0

Hello,
I'm trying to set up a website where user can upload files to which should be readable by everybody. Logged users should be able to comment on the files and rate the files.
I'm new to MySql and quite new to PHP so it has taken me already lots of hours for not so much result so far.

Here is where I am:
In MySql I've created four tables with MyISAM (members, files, comments, ratings).
I've set up a user registration system which works more or less fine (I've used big parts of this code http://www.html-form-guide.com/php-form/php-login-form.html). The users are registered in my members table with the user id, name, firstname, username, email and password.
Now, I've created a small script to upload files to the files table called addnewtest.php with a form included in a php file called upload.php. I can insert a trace of the files in my files table, but I can't retrieve the user id from the members table.
I have a php script I can include in a page to see whether a user is logged in. Here is a short version of my uploadtest.php

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

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-US" lang="en-US">
<head>
      <meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
      <title>test upload site</title>
      <link rel="STYLESHEET" type="text/css" href="style/fg_membersite.css"/>
</head>
<body>
<div id='fg_membersite_content'>
<h2>Upload</h2>
Hello <?= $fgmembersite->UserFullName(); ?>!


<form method="post" action="addnewtest.php" enctype="multipart/form-data">
    <p>
              pls indicate your username
            </p>
            <p>
              username:
            </p>
            <input type="text" name="username"/>

            <p>
              upload a file with max. 2MB:
            </p>
            <p>
              file:
            </p>
            <input type="hidden" name="size" value="20480000">
            <input type="file" name="notes"> 


            <p>
              your faculty
            </p>
            <p>
              Faculty:
            </p>

            <select name="faculty">
                <option>ABC</option>
                <option>DEF</option>
                <option>GHI</option>
            </select>
            <br/>
            <br/>
            <input TYPE="submit" name="upload" title="Add data to the Database" value="Valider"/>
          </form>

</div>
</body>
</html>

the file addnewtest.php looks like

<?php 


 //This is the directory where files will be saved 
 $target = "usernotes/"; 
 $target = $target . basename( $_FILES['notes']['name']); 

 //This gets all the other information from the form 
 $name=$_POST['username']; 
 $size=($_FILES['notes']['size']);
 $faculty=$_POST['faculty'];
 $note=($_FILES['notes']['name']); 
 $mime=($_FILES['notes']['type']); 

 // Connects to your Database 
 mysql_connect("....", "...") or die(mysql_error()) ; 
 mysql_select_db("...") or die(mysql_error()) ; 

 //Writes the information to the database 
 mysql_query("INSERT INTO files (username,size,faculty,notes,type)
VALUES ('$name',  '$size', '$faculty', '$note', '$mime')" ) ; 


 //Writes the file to the server 
 if(move_uploaded_file($_FILES['notes']['tmp_name'], $target)) 
 { 

 //Tells you if its all ok 
 echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; 
 } 
 else { 

 //Gives and error if its not 
 echo "Sorry, there has been a problem with the upload."; 
 } 
 ?> 

the members table has
id_user int(11) auto_increment primary key
name varchar(40)
firstname varchar(40)
email varchar(64)
username varchar(16) unique
password varchar(32)
confirmcode varchar(32)

(I don't know if I have to add field here yet to link the tables ?? like
IDFILE to link id_user.members with file_id.files
IDCOM to link id_user.members with comment_id.comments etc)

the files table has
file_id int(11) auto_increment primary key
id_user int(11) (not sure whether this is needed here)
size int(11)
notes varchar(60)
faculty varchar(60)

(I have the same problem for the comments table as for my files table (how to retrieve the user id of the logged in user from the members table and I haven't figured out yet how to do the rating as most scripts on the web are for rating a site or comments, but not for rating files on a file system.)

What do I have to do for mySql knows which user has uploaded which file??
How to retrieve the id_user of the members table of the person which is uploading the file??

thanks in advance for your help!!

Roger

Edited by diafol: applied code tags

2
Contributors
21
Replies
27
Views
5 Years
Discussion Span
Last Post by rogerg
Featured Replies
  • 1

    > $_SESSION[$this->GetLoginSessionVar()] = $username; Also that function returns a random string so it's basically setting some random variable in the session to the value of $username, impossible to reference it later. Read More

0

this is still giving me a headache... after reading more about how this works, I think I would have to store the user ID in the session and then insert it into the files table, right?

tough, in fg_membersite.php, I have

 function Login()
    {
        if(empty($_POST['username']))
        {
            $this->HandleError("Champ utilisateur vide!");
            return false;
        }

        if(empty($_POST['password']))
        {
            $this->HandleError("Champ mot de passe vide!");
            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;
        $_SESSION[$this->GetLoginSessionVar()] = $id_user;

now, in addnew.php I have the lines

$username = $_SESSION['username'];
 $id_user = $_SESSION['id_user'];

 and 

 mysql_query("INSERT INTO files (id_user,username,...)
VALUES ('$id_user', '$username', ...)" ) ;

but this still doesn't insert me the id_user and/or username in the files table when uploading a file.

anyone can help?

Edited by diafol: reapply code tags

0

I removed line25 in the fg_membersite.php as this was causing login errors - my mistake

but I still don't get it how/where to get the id_user and/or username from the logged in user in my example?

I have a login form login.php with

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

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

?>

I tried to add something like

$_SESSION['username'] = $result->username; // use this for user name
$_SESSION['id_user'] = $result->id_user; // use this for user ID

in there but it doesn't work. I also tried it in the page it redirects to, login-home.php, but didn't work. I also tried it in the include part of the page which is containing the upload form upload.php, but no success.

HELP

Edited by diafol: applied code tags

0

$fgmembersite->CheckLogin()

whats this object?

that needs to have a method to get the currently logged in users user id - then use that to inesrt the user id of the person who uploaded the file eg.

$userData = $fgmembersite->getUserData();

function getUserData(){
    //$sql = "select * from users where token = '{$_COOKIE['token']}'";
    $sql = "select * from users where token = '{$_SESSION['userid']}'";
    //probably want to exclude password/hash/salt from select
    $result = mysql_query($sql);
    if($result !== false){
        $data = mysql_fetch_assoc($result);
    }else{
        $data = false;
    }
    return $data;
}
0

Hi Biiim,

the function checklogin in fg_membersite.php only has

 function CheckLogin()
    {
         if(!isset($_SESSION)){ session_start(); }

         $sessionvar = $this->GetLoginSessionVar();

         if(empty($_SESSION[$sessionvar]))
         {
            return false;
         }
         return true;
    }

then, the function login in fg_membersite.php has

 function Login()
    {
        if(empty($_POST['username']))
        {
            $this->HandleError("Username empty!");
            return false;
        }

        if(empty($_POST['password']))
        {
            $this->HandleError("Password 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;
    }

so, would the token, session variable you mean be the $username in the login function?:

$_SESSION[$this->GetLoginSessionVar()] = $username;

could I use the id_user instead by including the function you propose in fg_membersite.php?

function getUserData(){
//$sql = "select * from users where token = '{$_COOKIE['token']}'";
$sql = "select * from members where token = '{$_SESSION['id_user']}'";
//probably want to exclude password/hash/salt from select
$result = mysql_query($sql);
if($result !== false){
$data = mysql_fetch_assoc($result);
}else{
$data = false;
}
return $data;
}
0

I had tested before by just adding

$_SESSION[$this->GetLoginSessionVar()] = $username;
            $_SESSION[$this->GetLoginSessionVar()] = $id_user;

in the function CheckLogin(), but this didn't work out

  function CheckLogin()
    {
         if(!isset($_SESSION)){ session_start(); }

         $sessionvar = $this->GetLoginSessionVar();

         if(empty($_SESSION[$sessionvar]))
         {
            return false;
         }
         return true;

         $_SESSION[$this->GetLoginSessionVar()] = $username;
        $_SESSION[$this->GetLoginSessionVar()] = $id_user;
    }
0

I have added the function getuserdata in my fg_membersite.php file now:
...

 function CheckLogin()
    {
         if(!isset($_SESSION)){ session_start(); }

         $sessionvar = $this->GetLoginSessionVar();

         if(empty($_SESSION[$sessionvar]))
         {
            return false;
         }
         return true;

    }


    function getUserData(){
//$sql = "select * from users where token = '{$_COOKIE['token']}'";
$sql = "select * from members where token = '{$_SESSION['username']}'";
//probably want to exclude password/hash/salt from select
$result = mysql_query($sql);
if($result !== false){
$data = mysql_fetch_assoc($result);
}else{
$data = false;
}
return $data;
}

...

then, I have tried to add

$userData = $fgmembersite->getUserData();

it my addnew.php file before or after the database connection, but got a "Call to a member function getUserData() on a non-object " error message

<?php
//This is the directory where files will be saved
$target = "usernotes/";
$target = $target . basename( $_FILES['notes']['name']);
//This gets all the other information from the form
$size=($_FILES['notes']['size']);
$faculty=$_POST['faculty'];
$note=($_FILES['notes']['name']);
$mime=($_FILES['notes']['type']);
// Connects to your Database
mysql_connect("....", "...") or die(mysql_error()) ;
mysql_select_db("...") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO files (username,size,faculty,notes,type)
VALUES ('$username', '$size', '$faculty', '$note', '$mime')" ) ;
...
?> 

if I add the line in my upload form file upload.php instead it doesn't create an error and the file is uploaded to the filesystem but the username isn't inserted in the files table either

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

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}

$userData = $fgmembersite->getUserData();



?>
<!DOCTYPE

where do I have to add the line?:

$userData = $fgmembersite->getUserData();
0

Hello I think the problem is still that I don't get the username or id_user from the fg_membersite.php script. If I try a echo "$username" on my upload.php, nothing is showing, but I can make a echo "helloworld" for example...

0

ok, the problem has to be with the session declaration in the fg_membersite.php file. Can you see what is wrong below? I paste all the functions of the fg_membersite.php related to a session:

   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 LogOut()
    {
        session_start();

        $sessionvar = $this->GetLoginSessionVar();

        $_SESSION[$sessionvar]=NULL;

        unset($_SESSION[$sessionvar]);
    }

    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'];

        return true;
    }


function getUserData(){
//$sql = "select * from users where token = '{$_COOKIE['token']}'";
$sql = "select id_user from membres where username = '{$_SESSION['username']}'";
//connect to database
mysql_connect("…", "…", "...") or die(mysql_error()) ; 
 //mysql_select_db("...") or die(mysql_error()) ;
 //probably want to exclude password/hash/salt from select
$result = mysql_query($sql);
if($result !== false){
$data = mysql_fetch_assoc($result);
}else{
$data = false;
}
return $data;
}
0

how is the user data stored in mysql?

"Call to a member function getUserData() on a non-object "

that sounds like $fgmembersite isn't an object and that you've dived headfirst into a load of code you don't understand!

$fgmembersite->CheckLogin()

In your config file it will likely say $fgmembersite = new someobject(); and it will have a class declaration file starting class someobject{... classes get their own functions defined that are only accessible through them, you can run them using $object->function();.

i've never actually really used classes before in php bar a shopping cart i ran into, most of what i know about classes comes from actionscript 3 (adobe flash script) they are really designed for pretty complex setups where you want to make many instances of the same thing, such as in a flash game where you need to make 1000's of enemies or in php where you might make several mysql connection objects to access different databases but with common functions you want to run on all of them.

So i think using a class for a logon is pretty redundant since i only see you ever having 1 logon per user?

Now thats a class and we want to be able to find the user_id from it, the data we want isn't stored inside the object it's stored in mysql. If we want to find this data we go to the one place that must know who just logged in, which is when the user logs in, from your login function you posted that leads us to the function CheckLoginInDB() you've not posted that function so can't write the exact code you will need.

One thing i do know is that function will do a lookup in the database to find the user that matches that user/pass and that function needs editing so the user_id gets returned and saved into the session.

Then you have his user_id for future and can run that getUserData() function to pull his data, the getUserData() function doesnt even have to be in the object it can be just a standalone function, i find it actually better than way cause you can use that function where ever you want.

To call a function you just have to write its name like any other standard mysql function eg. str_replace() mysql_connect() just you can't declare a function with the same name twice.

So once $_SESSION['user_id'] is set you just need to call $userData = getUserData(); near the top of the page and you will have all the currently logged in users data.

$_SESSION[$this->GetLoginSessionVar()] = $username;

That's also a bit confusing to me, what does that function return?

0

function CheckLoginInDB($username,$password)
{
if(!$this->DBLogin())
{
$this->HandleError("Database login failed!");
return false;
}
$username = $this->SanitizeForSQL($username);
$pwdmd5 = md5($password);
$qry = "Select user_id, 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['user_id'] = $row['user_id'];
$_SESSION['name_of_user'] = $row['name'];
$_SESSION['email_of_user'] = $row['email'];
return true;
}

1

$_SESSION[$this->GetLoginSessionVar()] = $username;

Also that function returns a random string so it's basically setting some random variable in the session to the value of $username, impossible to reference it later.

Votes + Comments
correct
0

Hello Biiim,

CheckLoginInDB just seems to check whether the user has clicked on the confirmation email. The confirmcode in the mysql table is set to y instead of the temp. code once the user clicks on the confirmation email. In the members table I have id_user int primary key autoincrement, name, email, username, password and confirmcode. In the files table, I just have a file_id, then I want to reuse either the username or the id_user to know which user has uploaded which file. Maybe it would be easier to use the username.

now I've tried to see wheter the name and email are stored at least. When just doing an echo

$email = $_SESSION['email_of_user'];
echo "$email";

$user4 = $_SESSION['name_of_user'];
echo "$user4";

the email and name of the user are returned. However, I can't do the same with the username. Is this because of the functions

function GetLoginSessionVar()
    {
        $retvar = md5($this->rand_key);
        $retvar = 'usr_'.substr($retvar,0,10);
        return $retvar;
    }

and

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;
}

GetLoginSessionVar shows then up as something like usr_87601d2e30

I post the full code of the original fg_membersite.php file below for you can see how it looks like

0

fg_membersite.php : the original 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 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;
    }    
    //-------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'];

        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'];

        $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;
    }    
}
?>
0

if I do a var dump on the upload.php file, I get

array(4) 
{ 
["name_of_user"]=> string(6) "G..." 
["firstname_of_user"]=> string(5) "Roger" 
["email_of_user"]=> string(21) "..." 
["usr_87601d2e30"]=> string(6) "rogerg" } 

is there a possibility to store the username in my fg_membersite.php?

0

oh, I replaced the function function GetLoginSessionVar() by a function

 function username()
    {
        return isset($_SESSION['username_of_user'])?$_SESSION['username']:'';
    }

and with a var dump I now get the below

array(8) { ["name_of_user"]=> string(6) "G..." ["firstname_of_user"]=> string(5) "Roger" ["email_of_user"]=> string(21) "..." ["id_user_of_user"]=> NULL ["username_of_user"]=> NULL ["usr_87601d2e30"]=> string(6) "rogerg" ["username"]=> string(6) "rogerg" [""]=> string(6) "rogerg" }

hm, it's not quite it but almost - I get the username returned 3 times but username now gives the logged user, there is still this usr_..., I have declared id_user_of_user and username_of_user somewhere and the logout doesn't work any more as it still has GetLoginSessionVar() associated with

Edited by rogerg: addition

0

I don't get the username any more today, not sure what I changed - can't reproduce it -grr

0

I don't have the

["username"]=> string(6) "rogerg"

any more, but I stil have

[""]=> string(6) "rogerg" }

not the nicest solution, but works

0

Sorry i wasnt around yesterday, nice you've got a solution.

you just don't need any function in defining a session variable, a session is unique to every user automatically.

$_SESSION[$this->GetLoginSessionVar()] = $username;

should just be

$_SESSION['username'] = $username;
0

Hi Biiim, I had been away for 4 days. I'll try this

0

it didn't work out with just

    $_SESSION['username'] = $username;

as this came back with a NULL value again. Well, I use the workaround for the moment. Now, I have to figure out how users can comment or rate the uploaded PDF files... so, I'll try to do some PHP for that

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.