Solved

Get username of the user submitting the form and add to the record

Posted on 2011-09-14
25
760 Views
Last Modified: 2012-05-12
I have a PHP form, in which a User enters data and clicks on Submit, then the data is commited to the database table and displayed in another view.  This is working fine.

I want to also display the username of the person who has submitted the form.    Username is in another database table called Users.  How can this be done?

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

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
?>
<?php 
ob_start();
/*  
 NEW.PHP 
 Allows user to create a new entry in the database 
*/ 
// creates the new record form 
 // since this form is used multiple times in this file, I have made it a function that is easily reusable 
 function renderForm() 
 { 
 ?> 
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
 <html> 
 <head> 
 <title>New Record</title>
 </head> 
 <body> 
 <?php  
 // if there are any errors, display them 
 if ($error != '') 
 { 
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>'; 
 } 
 ?>  
<form action="" method="post"> 
 <table> 
<tr>
<td><strong>* Title: </strong></td><td><input type="text" size="60" name="title" value="<?php echo $title; ?>" /></td>
</tr>
<tr>
<td><strong>* Category: </strong></td> <td><select name="categories" value="<?php echo $categories; ?>" >
<option value=” selected=’selected’>Select category</option> 
<option value=Business>Business</option> 
<option value=Shopping>Shopping</option> 
</select></td>
 </tr> 
<tr><td><label style="vertical-align:top"><strong>* Description: </strong></label></td><td><textarea name="description" cols="45" rows="5" value="<?php echo $description; ?>">describe here
</textarea></td>
</tr>
<tr><td><strong>* City: </strong></td><td><input type="text" name="city" value="<?php echo $city; ?>" /></td>
</tr>
<tr><td><strong>* Zip Code: </strong></td><td><input type="text" name="zipcode" value="<?php echo $zipcode; ?>" /></td>
</tr>
<tr><td><strong>* Country: </strong></td><td><select name="country" value="<?php echo $country; ?>" >
<option value=” selected=’selected’>Select Country</option> 
<option value=Zambia>Zambia</option> 
<option value=Zimbabwe>Zimbabwe</option>
</select>
</td>
</tr> 
<p>* required</p> 
<tr><td></td><td><input type="submit" name="submit" value="Submit"></td></tr>
 </table> 
 </form>
</body></html>
<?php  
 }  // connect to the database 
 include('connect-db.php'); 
 // check if the form has been submitted. If it has, start to process the form and save it to the database 
 if (isset($_POST['submit'])) 
 {  
 // get form data, making sure it is valid 
 $title = mysql_real_escape_string(htmlspecialchars($_POST['title'])); 
$categories = mysql_real_escape_string(htmlspecialchars($_POST['categories'])); 
 $description = mysql_real_escape_string(htmlspecialchars($_POST['description'])); 
$city = mysql_real_escape_string(htmlspecialchars($_POST['city'])); 
 $zipcode = mysql_real_escape_string(htmlspecialchars($_POST['zipcode'])); 
 $country = mysql_real_escape_string(htmlspecialchars($_POST['country']));
$domain = GetHostByName($REMOTE_ADDR);

// check to make sure all fields are entered 
 if ($title == '' || $description == '' || $city == '' || $zipcode == '' || $country == '') 
 { 
 // generate error message 
 $error = 'ERROR: Please fill in all required fields!'; 
  
 // if either field is blank, display the form again 
 renderForm($title, $categories, $description, $city, $zipcode, $country, $error); 
 } 
 else 
 { 
// save the data to the database
 mysql_query("INSERT responses SET title='$title', categories='$categories', description='$description', city='$city', zipcode='$zipcode', country='$country', userip='$domain'") 
 or die(mysql_error()); 
// once saved, redirect back to the view page 
header("Location: login-home.php");
 } 
 } 
 else 
 // if the form hasn't been submitted, display the form 
 { 
 renderForm('','',''); 
 } 
ob_end_flush();
?>

Open in new window

0
Comment
Question by:adamssap
  • 9
  • 6
  • 4
  • +2
25 Comments
 
LVL 10

Expert Comment

by:stu215
Comment Utility
Shouldnt the following variable contain their login name after logging in:
$_SERVER['PHP_AUTH_USER']
0
 
LVL 10

Expert Comment

by:stu215
Comment Utility
That was assuming that they logged in - if yes just pass it to your form handler and insert it with the rest of your data.
0
 
LVL 12

Expert Comment

by:jet-black
Comment Utility
Hi adamssap,

Use sessions to login user.
When user logs in save his/her id or his/her name to session like this:
$_SESSION['connected_user_name'] = 'the user name matched with login details';
Then on the form page, just write this value to the page after form submission like that:
<?php echo $_SESSION['connected_user_name']; ?>

don't forget to add
<?php session_start(); ?>
on the first line on every php page.

For the more information about sessions, you can use these websites:
http://www.w3schools.com/PHP/php_sessions.asp
http://www.tizag.com/phpT/phpsessions.php
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
If you follow the design pattern shown in this article, the access_control() function will return the user id.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_2391-PHP-login-logout-and-easy-access-control.html
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
I tried to add this, but nothing happens
<?php
function access_control($test=FALSE)
{
       // IF THE UID IS SET, WE ARE LOGGED IN
    if (isset($_SESSION["uid"])) return $_SESSION["uid"];

}
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Where did you add that?  Did you add the other code that is necessary to use the access_control() function?  The article is an integrated suite of code, and it is meant to be used as a teaching example.
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
I added it like this...
<?PHP
require_once("./include/membersite_config.php");

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
?>
<?php
function access_control($test=FALSE)
{
       // IF THE UID IS SET, WE ARE LOGGED IN
    if (isset($_SESSION["uid"])) return $_SESSION["uid"];

}
?>

<?php 
ob_start();
/*  
 NEW.PHP 
 Allows user to create a new entry in the database 
*/ 
// creates the new record form 
 // since this form is used multiple times in this file, I have made it a function that is easily reusable 
 function renderForm() 
 { 
 ?> 
 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
 <html> 
 <head> 
 <title>New Record</title>
 </head> 
 <body> 

 <?php  
 // if there are any errors, display them 
 if ($error != '') 
 { 
 echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>'; 
 } 
 ?>  
<form action="" method="post"> 
 <table> 
<tr>
<td><strong>* Title: </strong></td><td><input type="text" size="60" name="title" value="<?php echo $title; ?>" /></td>
</tr>
<tr>
<td><strong>* Category: </strong></td> <td><select name="categories" value="<?php echo $categories; ?>" >
<option value=” selected=’selected’>Select category</option> 
<option value=Business>Business</option> 
<option value=Education>Education</option> 
<option value=Entertainment>Entertainment</option> 
<option value=Incident/Event>Incident/Event</option> 
<option value=Life Style>Life Style</option> 
<option value=Politics>Politics</option> 
<option value=Science>Science</option> 
<option value=Shopping>Shopping</option> 
<option value=Sports>Sports</option> 
<option value=Technology>Technology</option> 
</select></td>
 </tr> 
<tr><td><label style="vertical-align:top"><strong>* Description: </strong></label></td><td><textarea name="description" cols="45" rows="5" value="<?php echo $description; ?>">describe here
</textarea></td>
</tr>
<tr><td><strong>* City: </strong></td><td><input type="text" name="city" value="<?php echo $city; ?>" /></td>
</tr>
<tr><td><strong>* Zip Code: </strong></td><td><input type="text" name="zipcode" value="<?php echo $zipcode; ?>" /></td>
</tr>
<tr><td><strong>* Country: </strong></td><td><select name="country" value="<?php echo $country; ?>" >
<option value=” selected=’selected’>Select Country</option> 
<option value=Afghanistan>Afghanistan</option> 
<option value=Albania>Albania</option> 
<option value=Algeria>Algeria</option> 
<option value=American Samoa>American Samoa</option> 
<option value=Andorra>Andorra</option> 
<option value=Angola>Angola</option> 
<option value=Anguilla>Anguilla</option> 
<option value=Antarctica>Antarctica</option> 
<option value=Antigua and Barbuda>Antigua and Barbuda</option> 
<option value=Argentina>Argentina</option> 
<option value=Armenia>Armenia</option> 
<option value=Aruba>Aruba</option> 
<option value=Australia>Australia</option> 
<option value=Austria>Austria</option> 
<option value=Azerbaijan>Azerbaijan</option> 
<option value=Bahamas>Bahamas</option> 
<option value=Bahrain>Bahrain</option> 
<option value=Bangladesh>Bangladesh</option> 
<option value=Barbados>Barbados</option> 
<option value=Belarus>Belarus</option> 
<option value=Belgium>Belgium</option> 
<option value=Belize>Belize</option> 
<option value=Benin>Benin</option> 
<option value=Bermuda>Bermuda</option> 
<option value=Bhutan>Bhutan</option> 
<option value=Bolivia>Bolivia</option> 
<option value=Bosnia and Herzegovina>Bosnia and Herzegovina</option> 
<option value=Botswana>Botswana</option> 
<option value=Bouvet Island>Bouvet Island</option> 
<option value=Brazil>Brazil</option> 
<option value=British Indian Ocean Territory>British Indian Ocean Territory</option> 
<option value=Brunei Darussalam>Brunei Darussalam</option> 
<option value=Bulgaria>Bulgaria</option> 
<option value=Burkina Faso>Burkina Faso</option> 
<option value=Burundi>Burundi</option> 
<option value=Cambodia>Cambodia</option> 
<option value=Cameroon>Cameroon</option> 
<option value=Canada>Canada</option> 
<option value=Cape Verde>Cape Verde</option> 
<option value=Cayman Islands>Cayman Islands</option> 
<option value=Central African Republic>Central African Republic</option> 
<option value=Chad>Chad</option> 
<option value=Chile>Chile</option> 
<option value=China>China</option> 
<option value=Christmas Island>Christmas Island</option> 
<option value=Cocos (Keeling) Islands>Cocos (Keeling) Islands</option> 
<option value=Colombia>Colombia</option> 
<option value=Comoros>Comoros</option> 
<option value=Congo>Congo</option> 
<option value=Congo, The Democratic Republic of The>Congo, The Democratic Republic of The</option> 
<option value=Cook Islands>Cook Islands</option> 
<option value=Costa Rica>Costa Rica</option> 
<option value=Cote D’ivoire>Cote D’ivoire</option> 
<option value=Croatia>Croatia</option> 
<option value=Cuba>Cuba</option> 
<option value=Cyprus>Cyprus</option> 
<option value=Czech Republic>Czech Republic</option> 
<option value=Denmark>Denmark</option> 
<option value=Djibouti>Djibouti</option> 
<option value=Dominica>Dominica</option> 
<option value=Dominican Republic>Dominican Republic</option> 
<option value=Ecuador>Ecuador</option> 
<option value=Egypt>Egypt</option> 
<option value=El Salvador>El Salvador</option> 
<option value=Equatorial Guinea>Equatorial Guinea</option> 
<option value=Eritrea>Eritrea</option> 
<option value=Estonia>Estonia</option> 
<option value=Ethiopia>Ethiopia</option> 
<option value=Falkland Islands (Malvinas)>Falkland Islands (Malvinas)</option> 
<option value=Faroe Islands>Faroe Islands</option> 
<option value=Fiji>Fiji</option> 
<option value=Finland>Finland</option> 
<option value=France>France</option> 
<option value=French Guiana>French Guiana</option> 
<option value=French Polynesia>French Polynesia</option> 
<option value=French Southern Territories>French Southern Territories</option> 
<option value=Gabon>Gabon</option> 
<option value=Gambia>Gambia</option> 
<option value=Georgia>Georgia</option> 
<option value=Germany>Germany</option> 
<option value=Ghana>Ghana</option> 
<option value=Gibraltar>Gibraltar</option> 
<option value=Greece>Greece</option> 
<option value=Greenland>Greenland</option> 
<option value=Grenada>Grenada</option> 
<option value=Guadeloupe>Guadeloupe</option> 
<option value=Guam>Guam</option> 
<option value=Guatemala>Guatemala</option> 
<option value=Guinea>Guinea</option> 
<option value=Guinea-bissau>Guinea-bissau</option> 
<option value=Guyana>Guyana</option> 
<option value=Haiti>Haiti</option> 
<option value=Heard Island and Mcdonald Islands>Heard Island and Mcdonald Islands</option> 
<option value=Holy See (Vatican City State)>Holy See (Vatican City State)</option> 
<option value=Honduras>Honduras</option> 
<option value=Hong Kong>Hong Kong</option> 
<option value=Hungary>Hungary</option> 
<option value=Iceland>Iceland</option> 
<option value=India>India</option> 
<option value=Indonesia>Indonesia</option> 
<option value=Iran, Islamic Republic of>Iran, Islamic Republic of</option> 
<option value=Iraq>Iraq</option> 
<option value=Ireland>Ireland</option> 
<option value=Israel>Israel</option> 
<option value=Italy>Italy</option> 
<option value=Jamaica>Jamaica</option> 
<option value=Japan>Japan</option> 
<option value=Jordan>Jordan</option> 
<option value=Kazakhstan>Kazakhstan</option> 
<option value=Kenya>Kenya</option> 
<option value=Kiribati>Kiribati</option> 
<option value=Korea, Democratic People’s Republic of>Korea, Democratic People’s Republic of</option> 
<option value=Korea, Republic of>Korea, Republic of</option> 
<option value=Kuwait>Kuwait</option> 
<option value=Kyrgyzstan>Kyrgyzstan</option> 
<option value=Lao People’s Democratic Republic>Lao People’s Democratic Republic</option> 
<option value=Latvia>Latvia</option> 
<option value=Lebanon>Lebanon</option> 
<option value=Lesotho>Lesotho</option> 
<option value=Liberia>Liberia</option> 
<option value=Libyan Arab Jamahiriya>Libyan Arab Jamahiriya</option> 
<option value=Liechtenstein>Liechtenstein</option> 
<option value=Lithuania>Lithuania</option> 
<option value=Luxembourg>Luxembourg</option> 
<option value=Macao>Macao</option> 
<option value=Macedonia, The Former Yugoslav Republic of>Macedonia, The Former Yugoslav Republic of</option> 
<option value=Madagascar>Madagascar</option> 
<option value=Malawi>Malawi</option> 
<option value=Malaysia>Malaysia</option> 
<option value=Maldives>Maldives</option> 
<option value=Mali>Mali</option> 
<option value=Malta>Malta</option> 
<option value=Marshall Islands>Marshall Islands</option> 
<option value=Martinique>Martinique</option> 
<option value=Mauritania>Mauritania</option> 
<option value=Mauritius>Mauritius</option> 
<option value=Mayotte>Mayotte</option> 
<option value=Mexico>Mexico</option> 
<option value=Micronesia, Federated States of>Micronesia, Federated States of</option> 
<option value=Moldova, Republic of>Moldova, Republic of</option> 
<option value=Monaco>Monaco</option> 
<option value=Mongolia>Mongolia</option> 
<option value=Montserrat>Montserrat</option> 
<option value=Morocco>Morocco</option> 
<option value=Mozambique>Mozambique</option> 
<option value=Myanmar>Myanmar</option> 
<option value=Namibia>Namibia</option> 
<option value=Nauru>Nauru</option> 
<option value=Nepal>Nepal</option> 
<option value=Netherlands>Netherlands</option> 
<option value=Netherlands Antilles>Netherlands Antilles</option> 
<option value=New Caledonia>New Caledonia</option> 
<option value=New Zealand>New Zealand</option> 
<option value=Nicaragua>Nicaragua</option> 
<option value=Niger>Niger</option> 
<option value=Nigeria>Nigeria</option> 
<option value=Niue>Niue</option> 
<option value=Norfolk Island>Norfolk Island</option> 
<option value=Northern Mariana Islands>Northern Mariana Islands</option> 
<option value=Norway>Norway</option> 
<option value=Oman>Oman</option> 
<option value=Pakistan>Pakistan</option> 
<option value=Palau>Palau</option> 
<option value=Palestinian Territory, Occupied>Palestinian Territory, Occupied</option> 
<option value=Panama>Panama</option> 
<option value=Papua New Guinea>Papua New Guinea</option> 
<option value=Paraguay>Paraguay</option> 
<option value=Peru>Peru</option> 
<option value=Philippines>Philippines</option> 
<option value=Pitcairn>Pitcairn</option> 
<option value=Poland>Poland</option> 
<option value=Portugal>Portugal</option> 
<option value=Puerto Rico>Puerto Rico</option> 
<option value=Qatar>Qatar</option> 
<option value=Reunion>Reunion</option> 
<option value=Romania>Romania</option> 
<option value=Russian Federation>Russian Federation</option> 
<option value=Rwanda>Rwanda</option> 
<option value=Saint Helena>Saint Helena</option> 
<option value=Saint Kitts and Nevis>Saint Kitts and Nevis</option> 
<option value=Saint Lucia>Saint Lucia</option> 
<option value=Saint Pierre and Miquelon>Saint Pierre and Miquelon</option> 
<option value=Saint Vincent and The Grenadines>Saint Vincent and The Grenadines</option> 
<option value=Samoa>Samoa</option> 
<option value=San Marino>San Marino</option> 
<option value=Sao Tome and Principe>Sao Tome and Principe</option> 
<option value=Saudi Arabia>Saudi Arabia</option> 
<option value=Senegal>Senegal</option> 
<option value=Serbia and Montenegro>Serbia and Montenegro</option> 
<option value=Seychelles>Seychelles</option> 
<option value=Sierra Leone>Sierra Leone</option> 
<option value=Singapore>Singapore</option> 
<option value=Slovakia>Slovakia</option> 
<option value=Slovenia>Slovenia</option> 
<option value=Solomon Islands>Solomon Islands</option> 
<option value=Somalia>Somalia</option> 
<option value=South Africa>South Africa</option> 
<option value=South Georgia and The South Sandwich Islands>South Georgia and The South Sandwich Islands</option> 
<option value=Spain>Spain</option> 
<option value=Sri Lanka>Sri Lanka</option> 
<option value=Sudan>Sudan</option> 
<option value=Suriname>Suriname</option> 
<option value=Svalbard and Jan Mayen>Svalbard and Jan Mayen</option> 
<option value=Swaziland>Swaziland</option> 
<option value=Sweden>Sweden</option> 
<option value=Switzerland>Switzerland</option> 
<option value=Syrian Arab Republic>Syrian Arab Republic</option> 
<option value=Taiwan, Province of China>Taiwan, Province of China</option> 
<option value=Tajikistan>Tajikistan</option> 
<option value=Tanzania, United Republic of>Tanzania, United Republic of</option> 
<option value=Thailand>Thailand</option> 
<option value=Timor-leste>Timor-leste</option> 
<option value=Togo>Togo</option> 
<option value=Tokelau>Tokelau</option> 
<option value=Tonga>Tonga</option> 
<option value=Trinidad and Tobago>Trinidad and Tobago</option> 
<option value=Tunisia>Tunisia</option> 
<option value=Turkey>Turkey</option> 
<option value=Turkmenistan>Turkmenistan</option> 
<option value=Turks and Caicos Islands>Turks and Caicos Islands</option> 
<option value=Tuvalu>Tuvalu</option> 
<option value=Uganda>Uganda</option> 
<option value=Ukraine>Ukraine</option> 
<option value=United Arab Emirates>United Arab Emirates</option> 
<option value=United Kingdom>United Kingdom</option> 
<option value=United States>United States</option> 
<option value=United States Minor Outlying Islands>United States Minor Outlying Islands</option> 
<option value=Uruguay>Uruguay</option> 
<option value=Uzbekistan>Uzbekistan</option> 
<option value=Vanuatu>Vanuatu</option> 
<option value=Venezuela>Venezuela</option> 
<option value=Viet Nam>Viet Nam</option> 
<option value=Virgin Islands, British>Virgin Islands, British</option> 
<option value=Virgin Islands, U.S.>Virgin Islands, U.S.</option> 
<option value=Wallis and Futuna>Wallis and Futuna</option> 
<option value=Western Sahara>Western Sahara</option> 
<option value=Yemen>Yemen</option> 
<option value=Zambia>Zambia</option> 
<option value=Zimbabwe>Zimbabwe</option>
</select>
</td>
</tr> 
<p>* required</p> 
<tr><td></td><td><input type="submit" name="submit" value="Submit"></td></tr>
 </table> 
 </form>
</body></html>
<?php  
 }  // connect to the database 
 include('connect-db.php'); 
 // check if the form has been submitted. If it has, start to process the form and save it to the database 
 if (isset($_POST['submit'])) 
 {  
 // get form data, making sure it is valid 
 $title = mysql_real_escape_string(htmlspecialchars($_POST['title'])); 
$categories = mysql_real_escape_string(htmlspecialchars($_POST['categories'])); 
 $description = mysql_real_escape_string(htmlspecialchars($_POST['description'])); 
$city = mysql_real_escape_string(htmlspecialchars($_POST['city'])); 
 $zipcode = mysql_real_escape_string(htmlspecialchars($_POST['zipcode'])); 
 $country = mysql_real_escape_string(htmlspecialchars($_POST['country']));
$domain = GetHostByName($REMOTE_ADDR);

// check to make sure all fields are entered 
 if ($title == '' || $description == '' || $city == '' || $zipcode == '' || $country == '') 
 { 
 // generate error message 
 $error = 'ERROR: Please fill in all required fields!'; 
  
 // if either field is blank, display the form again 
 renderForm($title, $categories, $description, $city, $zipcode, $country, $error); 
 } 
 else 
 { 
// save the data to the database
 mysql_query("INSERT responses SET title='$title', categories='$categories', description='$description', city='$city', zipcode='$zipcode', country='$country', userip='$domain'") 
 or die(mysql_error()); 
// once saved, redirect back to the view page 
header("Location: login-home.php");
 } 
 } 
 else 
 // if the form hasn't been submitted, display the form 
 { 
 renderForm('','',''); 
 } 
ob_end_flush();
?>

Open in new window

0
 
LVL 12

Expert Comment

by:jet-black
Comment Utility
I will write again :)

don't forget to add
<?php session_start(); ?>
on the first line on every php page.
0
 
LVL 12

Expert Comment

by:jet-black
Comment Utility
You need to save user name to session after the logon.
Then you'll be able to access it when you need.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Let me recommend a good book to help you get some foundation in how PHP and MySQL work together to create HTML and web sites.  Very readable with great examples, and now in its fourth printing, it has been a permanent part of my professional library since Version One.
http://www.sitepoint.com/books/phpmysql4/

I may be able to help you get the user id after the login.  To do that we will need to see the complete contents of this file:
require_once("./include/membersite_config.php");

Please post that in the code snippet (after you have read it over to be sure you are not accidentally exposing a password -- blot those out).

Thanks, ~Ray
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
Ray_Paseur:

Here is the code from membersite_config.php

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

$fgmembersite = new FGMembersite();

//Provide your site name here
$fgmembersite->SetWebsiteName('xxxxxx.com');

//Provide the email address where you want to get notifications
$fgmembersite->SetAdminEmail('xxxxx@gmail.com');
$fgmembersite->InitDB(/*hostname*/'xxxxx.xxxxx.com',
                      /*username*/'xxxxx',
                      /*password*/'xxxxx',
                      /*database name*/'project1',
                      /*table name*/'registers');

$fgmembersite->SetRandomKey('kVBsKARF8yWcefp');

?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Uhh, OK.  Now we need to see the code for this:
require_once("./include/fg_membersite.php");

And to save everyone time, read that code when you post it.  And post the code for anything used in any require() or include() function or any variant of those functions.

But seriously -- buy that SitePoint book and start working your way through it.  You will learn PHP much faster if you do that, compared to learning by trial and error and asking questions in an online forum.  Believe me!
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 1

Author Comment

by:adamssap
Comment Utility
i am sorry, I over looked the code, here is the code for fg_membersite.php

I will buy the book tomorrow.  

Thanks.
<?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']);
        
        session_start();
        if(!$this->CheckLoginInDB($username,$password))
        {
            return false;
        }
        
        $_SESSION[$this->GetLoginSessionVar()] = $username;
        
        return true;
    }
    
    function CheckLogin()
    {
         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]);
    }
    
    //-------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 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 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;
    }    
}
?>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
You will love the book, I promise.

On line 144 of the code above we have this:

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

That suggests to me that you might find the user identifier in the $_SESSION array.  You can use var_dump($_SESSION) to print out the session information.  You will find an associative array with keys pointing to values.  In this case the key is (unfortunately) a variable equal to the return from this method: $this->GetLoginSessionVar()

The method looks something like this:

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

So when you see the var_dump() output, you will be looking for an array key that starts with usr_ and has ten more characters of "stuff" after that.  It is probably a subset of the string set at line 42 where we find this:

$this->rand_key = '0iQx5oBk66oVZep';

... but since that is a variable we cannot really be sure until you print out the session array and look at it.

On line 250 we find the CheckLoginInDB($username,$password) method.  Inside that method at line 272 we find this:

        $_SESSION['name_of_user']  = $row['name'];
        $_SESSION['email_of_user'] = $row['email'];

So you might look at those elements of the $_SESSION array and see if they contain what you're looking for.

I think you might want to watch out for deprecated functions and other programming errors in this code.  An example of something that does not make sense to me is the definition of the stripslashes() method on line 636.  That definition re-uses the name of a PHP built-in function.  While you can apparently get away with this inside a class definition, it would cause a fatal error outside of the class.

HTH, and good luck, ~Ray

Hope that helps, ~Ray
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
Solution is not accurate
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@adamssap: WTF?  

We do not have your data model and you did not give us any test data, so it is impossible to give you tested code.  About the best we could hope for was to follow the logic (such as it is in the code above) and variable names.  You left this question for a month and a half without comment and then you close it with the worst possible grade that anyone can give at EE?  I will ask a moderator to reopen the question so you can tell us what is wrong with our efforts to help you.
0
 
LVL 12

Expert Comment

by:jet-black
Comment Utility
+1 for Ray_Paseur' comment. This is not scriptlance.
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 500 points for Ray_Paseur's comment http:/Q_27308574.html#36542550
Assisted answer: 0 points for adamssap's comment http:/Q_27308574.html#37084837

for the following reason:

Thanks
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
Thanks, I worked on it and solved.
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 500 points for Ray_Paseur's comment http:/Q_27308574.html#36542550
Assisted answer: 0 points for adamssap's comment http:/Q_27308574.html#37238731

for the following reason:

Thanks.
0
 
LVL 1

Author Comment

by:adamssap
Comment Utility
Thanks.
0
 
LVL 1

Expert Comment

by:rog7312
Comment Utility
Hello all, im quite new to php/mysql and I also tried to use the same fg_membersite.php script I also found as I was looking for a php/mysql user authentification.
I also wanted to re-user the id_user and/or the username and have tried for a week without success. I figured out over the weekend that the problem has to be in the fg_membersite.php

today I came across your posts here.

Ray's post is very helpful. I can reuse the name or the email as defined in line 272:

  $_SESSION['name_of_user']  = $row['name'];
        $_SESSION['email_of_user'] = $row['email'];

However, do you see a way of reusing either the username or the id_user with the above script?

I tried to add $_SESSION['username_of_user'] = $row['username']; , but this didn't work out.

thanks in advance for your help!
0
 
LVL 1

Accepted Solution

by:
rog7312 earned 500 total points
Comment Utility
the var dump in my version returns

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

Open in new window


the username is returned in the  ["usr_87601d2e30"]=> string(6) "..." } output.

would it be possible somehow to replace the function

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

Open in new window


by a username function
0
 
LVL 1

Expert Comment

by:rog7312
Comment Utility
I try to use the same html form and I'm also stuck a bit here. I tried to create the simplest possible username function
function username()
    {
        return isset($_SESSION['username_of_user'])?$_SESSION['username']:'';
    }

Open in new window

   and then replaced GetLoginSessionVar by username in the login and check login function, but now I get an array of 8 with
array(8) { 
["name_of_user"]=> string(6) "ok" 
["firstname_of_user"]=> string(5) "ok" 
["email_of_user"]=> string(21) "ok" 
["id_user_of_user"]=> NULL  =>just added this for testing
["username"]=> NULL 
["usr_87601d2e30"]=> string(6) "rogerg" 
["username_of_user"]=> NULL 
[""]=> string(6) "rogerg" } 

Open in new window


last night I got the username returned almost the same way, but I don't know what I missed this time :-(

by completely removing the GetLoginSessionVar I can remove the ["usr_87601d2e30"]=> string(6) "rogerg"  . However, dunno if this influences the username output in any way. If anybody has a solution how to get the username here, I'd be grateful
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Someone recently asked me about how to display a progress indicator on a page while an iframe is loading. And I remember when I first came across this myself. It was a bit tricky to get my head around, but really, it's very simple. The most impor…
Building a website can seem like a daunting task to the uninitiated but it really only requires knowledge of two basic languages: HTML and CSS.
In this tutorial viewers will learn how to position overlapping items using z-index in CSS. They will also learn the restrictions on the z-index property.  Create a new HTML document with an internal stylesheet.: Create a div in CSS and name it Red.…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now