Tuesday 29 July 2014

Tagged under: , , , , ,

Zend Framework from Scratch Part II: MVC and Creating Zend Project

In the Part I of the 'Zend from Scratch' series, we installed Zend and configured the environment to create our first Zend project. Continuing with our 'Zend from Scratch' series, we will have a look at the MVC framework using Zend and then create our first Zend web application. For those who haven't read the Part I of this series, here's the blog post of it:

Model-View-Controller (MVC) framework:

Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.
  • Model - This is the part of your application that defines its basic functionality behind a set of abstractions. Data access routines and some business logic can be defined in the model.
  • View - Views define exactly what is presented to the user. Usually controllers pass data to each view to render in some format. Views will often collect data from the user, as well. This is where you're likely to find HTML markup in your MVC applications.
  • Controller - Controllers bind the whole pattern together. They manipulate models, decide which view to display based on the user's request and other factors, pass along the data that each view will need, or hand off control to another controller entirely.

We will discuss more on MVC and how it fits in the Zend framework once we create our first project.

Create a Zend Framework Project:

Once you have completed all the steps in Part I of this series, we can start with creating of first PHP Zend project.
Open command prompt and navigate to the folder where you want to create your project. It should be the folder where the server points to. If you have XAMPP installed, its 'C:\xampp\htdocs'. Now run the below command:
zf create project zendtest
Here, 'zendtest' is the name of the project.

You may get an error for 'PHPUnit_Framework_TestCase', but this should not be a concern as it will not create any hindrance while working with the development activities. The error is related to Unit Testing.

Once you run the above command, you can find a folder named 'zendtest' (the name of our project) in the 'htdocs' folder. Below is the directory structure of our newly created project:


Now, once we can see the directory structure, we can relate this back to the MVC framework.

Zend Framework and MVC:

Open the 'application' folder in the newly created project:

As you can see, there are three prominent folders: models, views and controllers.

Controllers:

Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.
Open the IndexController.php file in the controllers folder:

<?php

class IndexController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {
        // action body
    }


}

Note the method 'indexAction()'. IndexController is a fallback controller and which also serves the home page of the site. Since there is nothing in the indexAction() method right now, it takes the default view, which is 'C:\xampp\htdocs\zendtest\application\views\scripts\index\index.phtml'. This is nothing but the home page of your project.
Open your browser and goto
http://localhost/zendtest/public
This is what you get:
This page is nothing but the index.phtml in 'C:\xampp\htdocs\zendtest\application\views\scripts\index'.
Now, lets have a look into Views.

Views:

View scripts are placed in application/views/scripts/, where they are further categorized using the controller names. In our case, we have an IndexController and an ErrorController, and thus we have corresponding index/ and error/ subdirectories within our view scripts directory.

Creating a Layout:

You may have noticed that the view scripts in the previous sections were HTML fragments- not complete pages, and they lack html, head, and body tags. This is purposely done by design, so that all actions return content related to that action only, and not the whole application. This gives a consistent look and feel throughout the application.
To create a layout, open the command prompt and navigate to the project directory. Now run the below command:
zf enable layout
The output is as below:

This will create a 'layout.phtml' file in 'C:\xampp\htdocs\zendtest\application\layouts\scripts'. If we open the file, below is what we see:

<?php echo $this->layout()->content; ?>

This is nothing but echoing the content from the view. We need to wrap this content with proper header and footer files. Replace the code in 'layout.phtml' file with the below code:

<!DOCTYPE html>
<html>
    <head>
        <title>Zend Test</title>
    </head>
    <body>
        <div id="wrap">
            <div id="header">
                <p>This is the header</p>
            </div>
            <div id="content">
                <!-- Echo our content here! -->
                <?php echo $this->layout()->content; ?>
            </div>
            <div id="footer">
                <p>This is the footer</p>
            </div>
        </div>
    </body>
</html>

Now, again goto 'http://localhost/zendtest/public' in your browser. You now have the previous page with a proper header and footer!!


So far, we have created the basic layout of our site using the Zend framework. In the next part, we will cover creating Models and database, creating new controllers and the rest of the things required to create a full-fledged web site.

A summary of what we covered in this tutorial:

  • What is Model-View-Controller framework
  • Zend Framework as an MVC
  • Creating Zend Project
  • Understanding the Controllers and Views in Zend Framework
  • Creating a layout using Zend
Stay tuned for the final segment of this three part Zend from scratch series.
You can subscribe for free or become a follower to get the latest alerts and posts.

Sunday 27 July 2014

Tagged under: , , ,

Zend Framework from Scratch Part I: Install and Configure PHP Zend Framework

Zend Framework (ZF) is an open source, object-oriented, full-stack PHP framework created by Zend Technologies implemented in PHP 5 and licensed under the New BSD License.

In this 'Zend from Scratch' series, we will try to get the understanding about Zend Framework...not theoretically, but covering things like installing and configuring Zend Framework, understanding the MVC framework and developing a sample application using Zend.

In this series, I would be using XAMPP for all purposes. XAMPP is nothing but a package of PHP, MySQL, Apache and other services. So, the PHP environment at my end is set up with XAMPP. You can download xampp from https://www.apachefriends.org/index.html.

So, lets get started...This part of the series will cover Installing and Configuring the Zend Framework on Windows.

System Requirements:

Zend Framework version 1.7 requires PHP 5.2.4 or later. Previous versions required PHP 5.1.4 or later, although the ZF Programmer's Reference Guide strongly recommended PHP 5.2.3 or later for security and performance improvements included in these versions of PHP.

Step 1: Download Zend Framework

Download the latest version of Zend Framework 1 (Full) from http://framework.zend.com/. At the time of writing this tutorial, the latest version of Zend was 1.12.7.

Step 2: Configure Zend Framework

  • Once you download the .zip file, extract its contents to a folder. The folder structure after extracting should look like this:
  • Now, copy the 'bin' folder and paste it in the 'PHP' folder, which for me (since I'm using xampp) is 'C:\xampp\php'. Rename the copied folder to 'zend-bin'.
  • Open the 'library' folder in the extracted folder. You can find a folder named 'Zend' in it. Copy this 'Zend' folder and paste it in your PHP's include_path. You can find the include_path for your environment in the 'php.ini' file. The default include_path for xampp is:
For UNIX:
include_path = ".:/php/includes"

For Windows:
include_path = ".;C:\xampp\php\PEAR"

The format of include_path is "path1;path2". The '.'(dot) in path1 means the current directory. So, there are basically 2 include_path(s).
  • Lastly, we need to configure the Zend CLI tool. To do this, we need to add the 'zend-bin' folder to the path System variables. Right click on My Computer and select Properties. In the Advanced tab, click on 'Environment variables'. Here, in the 'System Variables' section, click on edit, and add the path to 'zend-bin' folder (C:\xampp\php\zend-bin) at the end:
  • Just to ensure that the setup is fine (which it should be if you have followed the steps exactly), open the command prompt and run 'zf --help'. This command gives a list of all the commands you can use with Zend CLI. You should get he below output:

And there you are!! You have just set up the environment for creating your first project using the Zend Framework.

The next part of this series will give a brief idea about the MVC architecture of the Zend framework, and we will create our first project using Zend...So stay tuned!!

You can subscribe for free or become a follower to get the latest alerts and posts.

For the Part II of this series, click here.

Monday 21 July 2014

Tagged under: , , ,

Print Web Page using JavaScript

Many a times, we come across situations where we have to selectively print only a certain part of a web page. When it comes to a normal print command, it will print the entire web page for you. However, what if you want only a certain section, say a certain <div>...</div> to be printed, and exclude the content of the rest of the page?
This tutorial aims at doing just the thing...

Step 1: Enclose the content that you want to be printed in a <div> tag, and name it, say 'report':

<div id="report">
.
.
Your Content goes here...
.
.
</div>

Step 2: Add a print button:

<input type="button" value="Print Summary" onclick="printContent('report')"/>

As we see in the above snippet, 'printContent()' is the function that would do the printing job for us. To this function, we pass the id of the <div> tag whose content we want to print.

Step 3: Create a javaScript function 'printContent()':
At the bottom of the page, add the below javascript function

<script type="text/javascript">
<!--
function printContent(id){
str=document.getElementById(id).innerHTML
newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
newwin.document.write('<HTML>\n<HEAD>\n')
newwin.document.write('<TITLE>Summary</TITLE>\n')
newwin.document.write('<script>\n')
newwin.document.write('function chkstate(){\n')
newwin.document.write('if(document.readyState=="complete"){\n')
newwin.document.write('window.close()\n')
newwin.document.write('}\n')
newwin.document.write('else{\n')
newwin.document.write('setTimeout("chkstate()",2000)\n')
newwin.document.write('}\n')
newwin.document.write('}\n')
newwin.document.write('function print_win(){\n')
newwin.document.write('window.print();\n')
newwin.document.write('chkstate();\n')
newwin.document.write('}\n')
newwin.document.write('<\/script>\n')
newwin.document.write('</HEAD>\n')
newwin.document.write('<BODY onload="print_win()">\n')
newwin.document.write(str)
newwin.document.write('</BODY>\n')
newwin.document.write('</HTML>\n')
newwin.document.close()
}
//-->
</script>

The above function will take the id of the <div> tag whose content we want to print.
And there you are!! You can now print the page. With the help of software like PDF Creator, now you can also selectively print the page to a PDF file.
This functionality can be used where you want to print reports, receipts etc.

Thursday 17 July 2014

Tagged under: , , , ,

Forgot Password Functionality in PHP


When you implement a Login functionality, one thing that becomes an obvious inclusion is the 'Forgot Password' functionality. There are several ways to implement the forgot password functionality, some of which may be:


  • Ask the security Question
  • Send a new password to the registered mail, etc etc
But the most popular one is
  • Send an encoded, one time password reset link to the registered mail id
We would be discussing on this, i.e. the password reset link functionality implementation in this tutorial.

Before we get on with the actual coding, we need to create a proper database schema:
In the Table where you store the login credentials, add another column 'forgotpassword', which will store the encoded random string that you would be sending to the registered mail id.

Now comes the code...

Step 1: Ask for the email id with which the user is registered

<?php

$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);

if(isset($_POST['submit'])) {
$selectuser="Select * from USERTABLE where emailid='".addslashes($_POST['email'])."'";
$result = mysql_query($selectuser);
$numrows = mysql_num_rows($result);
if($numrows == 1) {
 $row = mysql_fetch_assoc($result);
 $validusername=$result['username'];
 for($i = 0; $i < 16; $i++) {
  $randomstring .= chr(mt_rand(1,126));
 }
 $verifyurl = "resetpwd.php";
 $verifystring = urlencode($randomstring);
 $verifyemail = urlencode($_POST['email']);
 
 $updateuser="Update USERTABLE SET forgotpassword='".addslashes($randomstring)."' WHERE emailid='".addslashes($_POST['email'])."'";
 mysql_query($updateuser);
 
 $mail_body=<<<_MAIL_
Hi,
A request has been made to reset the password for your account.
Please click on the following link to go to the password reset page:
$verifyurl?email=$verifyemail&verify=$verifystring
_MAIL_;
 
 require("class.phpmailer.php");
 $mailer = new PHPMailer();
 $mailer->IsSMTP();
 $mailer->Host = ""; //Add smtp details
 $mailer->SMTPAuth = TRUE;
 $mailer->Username = "";  // Change this to your gmail adress
 $mailer->Password = "";  // Change this to your gmail password
 $mailer->From = "";  // This HAVE TO be your gmail adress
 $mailer->FromName = ""; // This is the from name in the email, you can put anything you like here
 $mailer->Body = $mail_body;
 $mailer->Subject = "User Verification";
 $mailer->AddAddress($_POST['email']);  // This is where you put the email adress of the person you want to mail
 if(!$mailer->Send()){
  echo "Message was not sent<br/ >";
  echo "Mailer Error: " . $mailer->ErrorInfo;
 }
 else{
  echo "<center>A link has been
emailed to the address you entered below.
Please follow the link in the email to reset the passwod for 
your account.</center><br>";
 }
}
else{
 echo "We could not find any registered user with the email id as ".addslashes($_POST['email'])."<br>
 Please Enter the correct mail id & try again";
}
}
else{
?>

<div id="content">
<form action="forgotpwd.php" method="post">
<table>
<tr>
<td>Enter the Mail Id you registered with</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<tr>
<td></td>
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
</table>
</form>
</div>
<?php
}
?>


In the above snippet of code, We ask the user to enter the mail id he/she registered with. Once the user submits the form, you first check if the email id is present in the database, if not, you notify the user accordingly.
Once you find the email id in the database, the next step is to create a random string, encode it and append it to the password reset page url. Encoding of a string can be done using urlencode() method in PHP.
We also store the encoded randomly generated string to the database. Next, encode the mail id of the user and append it too to the url. The next part is where we send this url to the registered mail id. For this, I have used PHP Mailer.
To know more about PHP Mailer as to how it works, refer to my tutorial on this: Sending Email using PHP

Step 2: Check the encoded url when the user clicks it from his mail

<?php

$verify = addslashes(urldecode($_GET['verify']));
$verifymail = urldecode($_GET['email']);

if (isset($_POST['confirmpwdreset'])) {
 $resetpwd="Update USERTABLE SET password='". md5($_POST['newpwd'])."' WHERE emailid='".$verifymail."'"; 
 if(mysql_query($resetpwd))
 {
  $removeverifystring="Update USERTABLE SET forgotpwd='' WHERE emailid='".$verifymail."'";
  mysql_query($removeverifystring);
 }
 echo "<b>Your Password has been reset successfully.Login with your new password</b>";
}
else{
if($verify!=''){
$sql = "SELECT * FROM USERTABLE WHERE forgotpwd= '" . $verify . "' AND emailid = '" .$verifymail . "';";
$result = mysql_query($sql);
$numrows = mysql_num_rows($result);
if($numrows == 1) {
$row = mysql_fetch_assoc($result);
echo "<br><h3>Hi </h3><br>";
echo "You can now reset your password<br><br>";
?>
<form name="reset" action="resetpwd.php?emailid=<?php echo $_GET['emailid'];?>&verify=<?php echo $_GET['verify'];?>" method="post">
<table>
<tr>
<td>New password: </td><td><input type="password" name="newpwd"></td>
</tr>
<tr>
<td>Confirm password: </td><td><input type="password" name="confirmpwd"></td>
</tr>
<tr>
<td></td><td><input type="submit" name="confirmpwdreset" value="Confirm"></td>
</tr>
</table>
<?php
} 

else {
echo "The link is either invalid or has expired";
}
}
else echo "The link is either invalid or has expired";
}
?>


Once the user clicks the url in the mail, we decode the random string and the email-id in the url. For decoding, we can use the urldecode() method in PHP. Next, all we have to do is to check the database for the combination of the random string and the mail-id. Once we find that combo, we ask the user to enter the new password, which on submission is updated in the database. As we update the database with the new password value, we reset the value of the corresponding 'forgotpassword' field to '' so that the same random string cannot be reused, thus ensuring one time usability of password reset url

Thats it!! We now have a full fledged 'Forgot Password' functionality to make life easy for the users.