Saturday 10 October 2015

The registration form

Here is the registration form:

<form id='register' action='register.php' method='post'
    accept-charset='UTF-8'>
<fieldset >
<legend>Register</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='name' >Your Full Name*: </label>
<input type='text' name='name' id='name' maxlength="50" />
<label for='email' >Email Address*:</label>
<input type='text' name='email' id='email' maxlength="50" />
<label for='username' >UserName*:</label>
<input type='text' name='username' id='username' maxlength="50" />
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" />
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
So, we have text fields for name, email and the password. Note that we are using the password widget for better usability.

Form validation

At this point it is a good idea to put some form validation code in place, so we make sure that we have all the data required to create the user account. We need to check if name and email, and password are filled in and that the email is in the proper format.
We can use the free JavaScript form validation script to add form validations quickly and easily, with lesser code.
Here is a sample JavaScript validation code to be used for the sample form we created earlier:
var frmvalidator  = new Validator("register");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("name","req","Please provide your name");
frmvalidator.addValidation("email","req","Please provide your email address");
frmvalidator.addValidation("email","email","Please provide a valid email address");
frmvalidator.addValidation("username","req","Please provide a username");
frmvalidator.addValidation("password","req","Please provide a password");
To be on the safe side, we will also have the same validations on the server side too. For server side validations, we will use the PHP form validation script

Handling the form submission

Now we have to handle the form data that is submitted.
Here is the sequence (see the file fg_membersite.php in the downloaded source):
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;
}
First, we validate the form submission. Then we collect and ‘sanitize’ the form submission data (always do this before sending email, saving to database etc). The form submission is then saved to the database table. We send an email to the user requesting confirmation. Then we intimate the admin that a user has registered.

Saving the data in the database

Now that we gathered all the data, we need to store it into the database.
Here is how we save the form submission to the database.
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;
   }
Note that you have configured the Database login details in the membersite_config.php file. Most of the cases, you can use “localhost” for database host.
After logging in, we make sure that the table is existing.(If not, the script will create the required table).
Then we make sure that the username and email are unique. If it is not unique, we return error back to the user.

The database table structure

This is the table structure. The CreateTable() function in the fg_membersite.php file creates the table. Here is the code:
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;
}
The id_user field will contain the unique id of the user, and is also the primary key of the table. Notice that we allow 32 characters for the password field. We do this because, as an added security measure, we will store the password in the database encrypted using MD5. Please note that because MD5 is an one-way encryption method, we won’t be able to recover the password in case the user forgets it.

Inserting the registration to the table

Here is the code that we use to insert data into the database. We will have all our data available in the $formvars array.
function InsertIntoDB(&$formvars)
{
    $confirmcode = $this->MakeConfirmationMd5($formvars['email']);
    $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;
}
Notice that we use PHP function md5() to encrypt the password before inserting it into the database.
Also, we make the unique confirmation code from the user’s email address.

Sending emails

Now that we have the registration in our database, we will send a confirmation email to the user. The user has to click a link in the confirmation email to complete the registration process.
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 = urlencode($this->MakeConfirmationMd5($formvars['email']));
     
    $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;
}
We use the free PHPMailer script to send the email.
Note that we make the confirmation URL point to confirmreg.php?code=XXXX (where XXXX is the confirmation code).

Making a login form using PHP


Here is the HTML code for the login form.

<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName*:</label>
<input type='text' name='username' id='username'  maxlength="50" />
<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" />
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>

Logging in

We verify the username and the password we received and then look up those in the database. Here is the code:
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(!$this->CheckLoginInDB($username,$password))
    {
        return false;
    }
     
    session_start();
     
    $_SESSION[$this->GetLoginSessionVar()] = $username;
     
    return true;
}
In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable.
Here is the code to look up the username and password.
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;
    }
    return true;
}
Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set an “authorized” session variable, and then redirect to the protected content. If there are no rows with the entered data, we just redirect the user to the login form again.

Access controlled pages

For those pages that can only be accessed by registered members, we need to put a check on the top of the page.
Notice that we are setting an “authorized” session variable in the login code above. On top of pages we want to protect, we check for that session variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.
Include this sample piece of code on top of your protected pages:
<?PHP
require_once("./include/membersite_config.php");
if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
?>
See the file: access-controlled.php in the downloaded code for an example.
Here is the CheckLogin() function code.
function CheckLogin()
{
     session_start();
     $sessionvar = $this->GetLoginSessionVar();
      
     if(empty($_SESSION[$sessionvar]))
     {
        return false;
     }
     return true;
}
These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a “Forgot password” page to allow the user to retrieve or change his password if he forgets it.







PHP login form

Basic CRUD Application

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Basic CRUD Application - jQuery EasyUI CRUD Demo</title>
  6. <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
  7. <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
  8. <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/color.css">
  9. <link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
  10. <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
  11. <script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
  12. </head>
  13. <body>
  14. <h2>Basic CRUD Application</h2>
  15. <p>Click the buttons on datagrid toolbar to do crud actions.</p>
  16. <table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
  17. url="get_users.php"
  18. toolbar="#toolbar" pagination="true"
  19. rownumbers="true" fitColumns="true" singleSelect="true">
  20. <thead>
  21. <tr>
  22. <th field="firstname" width="50">First Name</th>
  23. <th field="lastname" width="50">Last Name</th>
  24. <th field="phone" width="50">Phone</th>
  25. <th field="email" width="50">Email</th>
  26. </tr>
  27. </thead>
  28. </table>
  29. <div id="toolbar">
  30. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newUser()">New User</a>
  31. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editUser()">Edit User</a>
  32. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyUser()">Remove User</a>
  33. </div>
  34. <div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
  35. closed="true" buttons="#dlg-buttons">
  36. <div class="ftitle">User Information</div>
  37. <form id="fm" method="post" novalidate>
  38. <div class="fitem">
  39. <label>First Name:</label>
  40. <input name="firstname" class="easyui-textbox" required="true">
  41. </div>
  42. <div class="fitem">
  43. <label>Last Name:</label>
  44. <input name="lastname" class="easyui-textbox" required="true">
  45. </div>
  46. <div class="fitem">
  47. <label>Phone:</label>
  48. <input name="phone" class="easyui-textbox">
  49. </div>
  50. <div class="fitem">
  51. <label>Email:</label>
  52. <input name="email" class="easyui-textbox" validType="email">
  53. </div>
  54. </form>
  55. </div>
  56. <div id="dlg-buttons">
  57. <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveUser()" style="width:90px">Save</a>
  58. <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')" style="width:90px">Cancel</a>
  59. </div>
  60. <script type="text/javascript">
  61. var url;
  62. function newUser(){
  63. $('#dlg').dialog('open').dialog('center').dialog('setTitle','New User');
  64. $('#fm').form('clear');
  65. url = 'save_user.php';
  66. }
  67. function editUser(){
  68. var row = $('#dg').datagrid('getSelected');
  69. if (row){
  70. $('#dlg').dialog('open').dialog('center').dialog('setTitle','Edit User');
  71. $('#fm').form('load',row);
  72. url = 'update_user.php?id='+row.id;
  73. }
  74. }
  75. function saveUser(){
  76. $('#fm').form('submit',{
  77. url: url,
  78. onSubmit: function(){
  79. return $(this).form('validate');
  80. },
  81. success: function(result){
  82. var result = eval('('+result+')');
  83. if (result.errorMsg){
  84. $.messager.show({
  85. title: 'Error',
  86. msg: result.errorMsg
  87. });
  88. } else {
  89. $('#dlg').dialog('close'); // close the dialog
  90. $('#dg').datagrid('reload'); // reload the user data
  91. }
  92. }
  93. });
  94. }
  95. function destroyUser(){
  96. var row = $('#dg').datagrid('getSelected');
  97. if (row){
  98. $.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
  99. if (r){
  100. $.post('destroy_user.php',{id:row.id},function(result){
  101. if (result.success){
  102. $('#dg').datagrid('reload'); // reload the user data
  103. } else {
  104. $.messager.show({ // show error message
  105. title: 'Error',
  106. msg: result.errorMsg
  107. });
  108. }
  109. },'json');
  110. }
  111. });
  112. }
  113. }
  114. </script>
  115. <style type="text/css">
  116. #fm{
  117. margin:0;
  118. padding:10px 30px;
  119. }
  120. .ftitle{
  121. font-size:14px;
  122. font-weight:bold;
  123. padding:5px 0;
  124. margin-bottom:10px;
  125. border-bottom:1px solid #ccc;
  126. }
  127. .fitem{
  128. margin-bottom:5px;
  129. }
  130. .fitem label{
  131. display:inline-block;
  132. width:80px;
  133. }
  134. .fitem input{
  135. width:160px;
  136. }
  137. </style>
  138. </body>
  139. </html>

How to Integrate Stripe Payment Gateway in PHP







Step 3.
Edit charge.php file and replace with your Secret Key
Edit index.php file and replace with your Publishable Key
The test version does not entail actual transfer of funds and you can teste transfer if you have set up everything necessary to charge a customer by entering the following credit card number: 4242424242424242.
The only thing you would have to worry is Man-in-the-middle attacks and that is why Stripe highly recommends using HTTPS but no data about a card will be stored in your server.
First, we create a basic static web page and create a form that includes a script from Stripe (Checkout.js).

<?php

//let's say each article costs 15.00 bucks

try {
  require_once('Stripe/lib/Stripe.php');
  Stripe::setApiKey("secret_key_here"); //Replace with your Secret Key

  $charge = Stripe_Charge::create(array(
  "amount" => 1500,
  "currency" => "usd",
  "card" => $_POST['stripeToken'],
  "description" => "Charge for Facebook Login code."
));
    //send the file, this line will be reached if no error was thrown above
    echo "<h1>Your payment has been completed. We will send you the Facebook Login code in a minute.</h1>";


//you can send the file to this email:
echo $_POST['stripeEmail'];
}
//catch the errors in any way you like

catch(Stripe_CardError $e) {
   
}


catch (Stripe_InvalidRequestError $e) {
// Invalid parameters were supplied to Stripe's API

} catch (Stripe_AuthenticationError $e) {
// Authentication with Stripe's API failed
// (maybe you changed API keys recently)

} catch (Stripe_ApiConnectionError $e) {
// Network communication with Stripe failed
} catch (Stripe_Error $e) {

// Display a very generic error to the user, and maybe send
// yourself an email
} catch (Exception $e) {

// Something else happened, completely unrelated to Stripe
}
?>

  $charge = Stripe_Charge::create(array(
  "amount" => 1500,
  "currency" => "usd",
  "card" => $_POST['stripeToken'],
  "description" => "Charge for Facebook Login code."
));
Signup on stripe