Archive for the Category » Symfony «

Add Security Math to Protect Unauthorized Access

You may need to add security math while visitor post their comments. Or even more sensitive admin login panel. whatever the case is here is php code which take a minute to implement security math.

View File(form_login_view.php):
<?php echo $x=rand(1,10);?> + <?php echo $y=rand(11,20);?> =
<?php $this->session->set_userdata(‘security_math_result’ , $x+$y);?>
[input type="text" name="security_math_result" value="<?php echo set_value('security_math_result', $default['security_math_result']); ?>” size=”5″ ]

Controller (auth.php):
if ($_POST)
{
if($this->session->userdata(‘security_math_result’)!=$_POST['security_math_result'])
{
$data['msg_class'] = ‘error’;
$data['msg'] = “Security Math is incorrect. Please check below.”;
$data['default'] = $_POST;
}
…… other codes…….

 

A quick start of Symfony2 from Symfony.com

I was looking for an easy to understand Symfony2 tutorial. I found a very good resource in symfony website where they explain basics of symfony using easy example. They start from a spaghetti php coding and convert into strong symfony2 application by step by step conversion. I like the tutorial very much and will try to understand clearly very soon(hopefully from tomorrow).

Here is the link of that crazy tutorial.

Another good & descent basic concept of symfony2 link is here.

Install PHP5-CLI in WAMP at Win-XP

 

let us have a quick start of CLI(Command Line Interface) activation/installation in WAMP(Windows Apache MySQL & PHP). for me windows xp is my operation system. however, lets start step by step.

  1. Install windows XP server pack II
  2. Install wamp (version WampServer2.1e-x32.exe, Apache 2.2.17,PHP 5.3.5,MySQL 5.5.8). i haven’t change the default installation location. but you may change it as you need.
  3. let’s open: C:\wamp\bin\php\php5.2.5\php.ini and remove “;” from the line:  ;extension=php_xsl.dll
  4. let’s open: C:\wamp\bin\php\php5.2.5\php.ini and remove “;” from the line: ;extension=php_openssl.dll
  5. Click WAMP Icon Apache > Apache Modules > rewrite_module (tick mark by click). WAMP will restart.
  6. Now we should add environment variables to have access to PHP i MySQL under the command line. Right-click on My Computer, than Properties. Switch to Advanced tab and click the Environment Variables button. At the end of variable PATH let’s add ;C:\wamp\bin\php\php5.3.5;C:\wamp\bin\mysql\mysql5.5.8\bin (paths to MySQL and PHP files separated by a semicolon).
  7. edit the ‘go-pear.bat’ file at C:\wamp\bin\php\php5.3.0\go-pear.bat to look like the following(simply copy following 5 lines and replace all content of go-pear.bat
  8. @ECHO OFF
    set PHP_BIN=php.exe
    rem %PHP_BIN% -d output_buffering=0 PEAR\go-pear.phar
    php -d phar.require_hash=0 PEAR\go-pear.phar
    pause
  9. Download latest version of go-pear.phar from here and replace C:\wamp\bin\php\php5.3.5\PEAR\go-pear.phar file.
  10. open command prompt. Start->run->cmd press ender.
  11. at command prompt C:\wamp\bin\php\php5.3.5>go-pear.bat
  12. A command prompt window will be opened. press Enter to proceed.
  13. Afterward, a list of up to 10 (this length may differ on XAMPP and others) filesystem locations will be displayed. Once again press Enter.
  14. Then it will ask if we want to modify php.ini; Type in the letter “Y” (in capital letters) and press Enter.
  15. Double click C:\wamp\bin\php\php5.3.5\PEAR_ENV.reg file. When asked to confirm the addition of registry values choose ”Yes”and then click ”OK”.
  16. copy the file “C:\wamp\bin\php\php5.3.5\pear.bat” to “C:\WINDOWS\system32″.
  17. Reboot PC.
  18. Right-click on My Computer, than Properties. Switch to Advanced tab. Find variable php_pear_php_bin (which current value is .\php.exe) and change value to C:\wamp\bin\php\php5.3.5\php.exe
  19. Test PEAR installation by cmdprompt>pear. it output says unrecognized then you have to review above mentioned steps more carefully
  20. Whenever you update PEAR or some of its packages, copy pear.bat into system32 to update our list of PEAR commands. This extra step can be avoided if the path to pear.bat has been added to your PATH environment variable.
  21. CLI of PHP & PEAR SUCCESSFUL !! START SYMFONY !!
  22. Add symfony channel to pear by C:\>pear channel-discover pear.symfony-project.com
    (output: Adding Channel “pear.symfony-project.com” succeeded
    Discovery of channel “pear.symfony-project.com” succeeded)
  23. Install Symfony by C:\>pear install symfony/symfony (output: WARNING: channel “pear.symfony-project.com” has updated its protocols, use “pear
    channel-update pear.symfony-project.com” to update
    downloading symfony-1.4.13.tgz …
    Starting to download symfony-1.4.13.tgz (3,186,371 bytes)
    ……………………………………………………………………..
    ……………………………………………………………………..
    ……………………………………………………………………..
    ……………………………………………………………………..
    ……………………………………………………………………..
    ………….done: 3,186,371 bytes
    install ok: channel://pear.symfony-project.com/symfony-1.4.13)

Symfony installed correctly and now you are ready for Symfony project with the power of ORM (Object Relationship Mapping)

Let me start a project in Symfony.

Error: during PEAR installation by go-pear.bat you may get error in Windows 7, and get
Solution: it working by running the command prompt as administrator. Start -> Type in “cmd” -> right-click “cmd.exe” -> click “run as administrator”

Error:  phar “C:\wamp\bin\php\php5.3.5\PEAR\go-pear.phar” does not have a signaturePHP Warning:  require_once(phar://go-pear.phar/index.php): failed to open stream: phar error: invalid url or non-existent phar “phar://go-pear.phar/index.php” in C:\wamp\bin\php\php5.3.5\PEAR\go-pear.phar on line 1236PHP Stack trace: PHP   1. {main}() C:\wamp\bin\php\php5.3.5\PEAR\go-pear.phar:0
Solution: php -d phar.require_hash=0 ./PEAR/go-pear.phar (not sure)

  1. Double click C:\wamp\bin\php\php5.3.5\PEAR_ENV.reg file. When asked to confirm the addition of registry values choose ”Yes”and then click ”OK”.

Error:  Discovering channel pear.symfony-project.com over http:// failed with message: channel-add: Cannot open “http://pear.symfony-project.com/channel.xml” (Connectio
n to `pear.symfony-project.com:80′ failed: php_network_getaddresses: getaddrinfo
failed: No such host is known. ) Trying to discover channel pear.symfony-project.com over https:// instead Discovery of channel “pear.symfony-project.com” failed (channel-add: Cannot open  “https://pear.symfony-project.com/channel.xml” (Connection to `pear.symfony-project.com:443′ failed: Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?))
Solution: let’s open: C:\wamp\bin\php\php5.2.5\php.ini and remove “;” from the line: ;extension=php_openssl.dll (Step-4)

Some Resourceful/Helpful Links:

http://trac.symfony-project.org/wiki/HowToInstallPearOnWindowsWithWamp

http://trac.symfony-project.org/wiki/HowToInstallSymfonyOnWindowsWithWamp

http://www.sencha.com/forum/showthread.php?120958-Php-Pear-Hell-can-t-install-Logger-%28Solved%29

Category: Symfony  Leave a Comment

The MVC Architecture & Layout(Decorator Design Pattern)

[Note: 100% copy and paste from symfony web site]
If you are used to developing PHP websites without a framework, you probably use the one PHP file per HTML page paradigm. These PHP files probably contain the same kind of structure: initialization and global configuration, business logic related to the requested page, database records fetching, and finally HTML code that builds the page.
You may use a templating engine to separate the logic from the HTML. Perhaps you use a database abstraction layer to separate model interaction from business logic. But most of the time, you end up with a lot of code that is a nightmare to maintain. It was fast to build, but over time, it’s more and more difficult to make changes, especially because nobody except you understands how it is built and how it works.
As with every problem, there are nice solutions. For web development, the most common solution for organizing your code nowadays is the MVC design pattern. In short, the MVC design pattern defines a way to organize your code according to its nature. This pattern separates the code into three layers:
• The Model layer defines the business logic (the database belongs to this layer). You already know that symfony stores all the classes and files related to the Model in the lib/model/directory.
• The View is what the user interacts with (a template engine is part of this layer). In symfony, the View layer is mainly made of PHP templates. They are stored in varioustemplates/ directories as we will see later on today.
• The Controller is a piece of code that calls the Model to get some data that it passes to the View for rendering to the client. When we installed symfony the first day, we saw that all requests are managed by front controllers (index.php and frontend_dev.php). These front controllers delegate the real work to actions.

MVC Architecture

MVC Architecture

The Layout

First, if you have a closer look at the mockups, you will notice that much of each page looks the same. You already know that code duplication is bad, whether we are talking about HTML or PHP code, so we need to find a way to prevent these common view elements from resulting in code duplication.
One way to solve the problem is to define a header and a footer and include them in each template:

Header Footer

Template using Header Footer

But here the header and the footer files do not contain valid HTML. There must be a better way. Instead of reinventing the wheel, we will use another design pattern to solve this problem: the decorator design pattern. The decorator design pattern resolves the problem the other way around: the template is decorated after the content is rendered by a global template, called a layout in symfony:

Decorator Design Pattern

Decorator Design Pattern

Build another symfony project

well here we are for build second symfony project. previously we have seen, how difficult first project was without a single line of php code. here is the second one similar to first project. but this time not only signp form. instead we implement a small project. lets start
propel:
article:
id: ~
title: { type: varchar(255), required: true }
slug: { type: varchar(255), required: true }
content: longvarchar
status: varchar(255)
author_id: { type: integer, required: true, foreignTable: author, foreignReference: id, OnDelete: cascade }
category_id: { type: integer, required: false, foreignTable: category, foreignReference: id, onDelete: setnull }
published_at: timestamp
created_at: ~
updated_at: ~
_uniques:
unique_slug: [slug]

author:
id: ~
first_name: varchar(20)
last_name: varchar(20)
email: { type: varchar(255), required: true }
active: boolean

category:
id: ~
name: { type: varchar(255), required: true }

tag:
id: ~
name: { type: varchar(255), required: true }

article_tag:
article_id: { type: integer, foreignTable: article, foreignReference: id, primaryKey: true, onDelete: cascade }
tag_id: { type: integer, foreignTable: tag, foreignReference: id, primaryKey: true, onDelete: cascade }

now goto command prompt and run few commands we already practice yesterday:

  • from DOS prompt d:\dev\small_project> php symfony propel:build-all
  • from DOS prompt d:\dev\small_project> php symfony propel:generate-crud frontend article Article
  • from DOS prompt d:\dev\small_project> php symfony propel:generate-crud frontend author Author
  • from DOS prompt d:\dev\small_project> php symfony propel:generate-crud frontend category Category
  • that’s it. readymade module for you. browse your project using:

    http://loclhost:420/author

    Hey!! i have no idea which client like this project ;) but yes developer might like it for customization and build a genuine one :)

Build your first symfony project (Symfony 1.2)

Good time to build first simple symfony project. The project is very simple one. Build a Signup form. Don’t blame me, how a signup form can be a project !!!. Yes it is :) Lets Start.

Before start follow the instructions make sure you have successfully configured symfony in your local PC. which mean, your PHP, MySql and Apache are perfectly installed. Moreover, PEAR library is also installed and you have enabled PHP CLI (Command Line Instruction). Fair enough :) you have all these installed and support. So lets get start!!!

First create a folder with your project name. for example, for this tutorial we name the project signup. Say we create a folder at d:\dev\signup and we create two sub folder named lib and vendor. which mean the directory structure is exactly d:\dev\signup\lib\vendor. okay !! now donwload symfony latest stable package from here and extract it inside d:\dev\signup\lib\vendor. rename the extract folder to symfony. which mean our structure is like D:\dev\signup\lib\vendor\symfony\ and at this location we get some folders (data, lib, etc etc).

Hang ON!! Don’t dive!! Before that, we need to analyze what exactly we are going to do. we have to build a signup page and a success page. That’s all !!!! Signup Form: only 3 fields: name, email and sex(male or female). as though you all are quite mature lets define specific. we use html text box for name and email and radio button for sex. Success Form: simply a message. Operation Successful !! Very easy requirement for us. if we start write raw coding then it must not take more then 20 minutes of us. Right? Let’s see how long symfony take for this tiny requirement.

LETS DIVE !! DIVE !! DIVE !! DIVE !! DIVE !! DIVE !!

  • Goto Start->Run->cmd press enter
  • navigate to d:\dev\signup
  • Setup your PROJECT by d:\dev\signup>php lib\vendor\symfony\data\bin\symfony generate:project signup =) lot of files automatically generated for you :)
  • Create frontend application using d:\dev\signup>symfony generate:app –escaping-strategy=on –csrf-secret=UniqueSecret frontend
    [Attention: before escaping and csrf it's double - not single - . Please don't do copy paste of these command. Write yourself by hand.]
    =) lot of file again automatically generated for you at d:\dev\signup\app\frontend :)

Upto this step these are common for any types of projects like facebook.com or ebay.com. :) Lets dive into symfony to build our HUGE signup project. Till now we have not write a single line of code and it’s time for us to do that. Let’s remember our requirement. it was a signup form with only 3 fields. This is the most most most tricky one. Lot’s of class, form, validation etc etc will create automatically based on our object signup. So lets build our object first. How? very easy


// D:\dev\signup\config\schema.yml
propel:
member: id: ~ name: { type: varchar(255), required: true }
email: { type: varchar(255), required: true }
sex: { type: varchar(255), required: true }

and customize your database file

// D:\dev\signup\config\databases.yml
dev:
propel:
param:
classname: DebugPDO
test:
propel:
param:
classname: DebugPDO
param:
classname: DebugPDO
dsn: 'mysql:host=localhost;dbname=signup_test'
username: root
password: null
all:
propel:
class: sfPropelDatabase
param:
classname: PropelPDO
dsn: mysql:dbname=signup_dev;host=localhost
username: root
password:
encoding: utf8
persistent: true
pooling: true

Is the class, form etc etc created by writing only these above line of code? It’s impossible. Yes it’s really impossible until you run few lines of code at command prompt. Lets do that.

  • first create create two database named signup_dev and signup_test from your browser http://localhost/phpmyadmin
  • now from command promt: d:\dev\signup>php symfony propel:build-all automatically generate lot of classes for you inside d:\dev\signup\lib\. don’t get any file? don’t worry look inside model, form, filter folder :D

i hope you have fair experience of PORT BASED SETUP. if No then you are most welcome :) . simply add these lines at the end of your configuration file apache\conf\httpd.conf


Listen 127.0.0.1:8081
DocumentRoot "D:\dev\signup\web" DirectoryIndex index.php
AllowOverride All Allow from All
Alias /sf D:\dev\signup\lib\vendor\symfony\data\web\sf
AllowOverride All Allow from All

Run http://localhost:8081/frontend_dev.php what comes in browser? “Symfony Project Created”. right? which mean’s you are Successful at first stage!! YEAAAAAAA !! Lets celebrate!!

Well let’s move forward.
From command promt: d:\dev\signup>php symfony generate:module frontend member
Have a look inside app\frontend\module. A ready made module named member for us :)
another one: d:\dev\signup>php symfony propel:generate-crud frontend member Member

That’s it!!! Member module is 100 % complete. which means you can add, edit, update, delete a member with proper VALIDATION. did you write a single line of php code? i don’t think so. browse

http://localhost:8081/member

default display a list of members and option for add new one, edit existing one, delete or update any one.

hope you have not enjoyed. because either you know symfony very well, then this article is waste of time for you :D in contrast, no knowledge of symfony means this article is not fair enough to understand. i am afraid but you need to http://www.symfony-project.org. which means waste of time with this article :D

BEST OF LUCK :)

build first symfony project

Good time to build first simple symfony project. The project is very simple one. Build a Signup form. Don’t blame me, how a signup form can be a project !!!. Yes it is :) Lets Start.

Before start follow the instructions make sure you have successfully configured symfony in your local PC. which mean, your PHP, MySql and Apache are perfectly installed. Moreover, PEAR library is also installed and you have enabled PHP CLI (Command Line Instruction). Fair enough :) you have all these installed and support. So lets get start!!!

First create a folder with your project name. for example, for this tutorial we name the project signup. Say we create a folder at d:\dev\signup and we create two sub folder named lib and vendor. which mean the directory structure is exactly d:\dev\signup\lib\vendor. okay !! now donwload symfony latest stable package from here and extract it inside d:\dev\signup\lib\vendor. rename the extract folder to symfony. which mean our structure is like D:\dev\signup\lib\vendor\symfony\ and at this location we get some folders (data, doc, lib, etc etc).

Hang ON!! Don’t dive!! Before that, we need to analyze what exactly we are going to do. we have to build a signup page and a success page. That’s all !!!!

Signup Form: only 3 fields: name, email and sex(male or female). as though you all are quite mature lets define specific. we use html text box for name and email and radio button for sex.
Success Form: simply a message. Operation Successful !!

Very easy requirement for us. if we start write raw coding then it must not take more then 20 minutes of us. Right? Let’s see how long symfony take for this tiny requirement.

LETS DIVE !! DIVE !! DIVE !! DIVE !! DIVE !! DIVE !!

  • Goto Start->Run->cmd press enter
  • navigate to d:\dev\signup
  • Setup your PROJECT by d:\dev\signup>php lib\vendor\symfony\data\bin\symfony generate:project signup
    =) lot of files automatically generated for you :)
  • Create frontend application using d:\dev\signup>php symfony generate:app –escaping-strategy=on –csrf-secret=Unique$ecret frontend
    =) lot of file again automatically generated for you at d:\dev\signup\app\frontend :)

Upto this step these are common for any types of projects like facebook.com or ebay.com. :) Lets dive into symfony to build our HUGE signup project.

Till now we have not write a single line of code and it’s time for us to do that. Let’s remember our requirement. it was a signup form with only 3 fields. This is the most most most tricky one. Lot’s of class, form, validation etc etc will create automatically based on our object signup. So lets build our object first. How? very easy
// D:\dev\signup\config\schema.yml
propel:
member:
id: ~
name: { type: varchar(255), required: true }
email: { type: varchar(255), required: true }
sex: { type: varchar(255), required: true }

and customize your database file
// D:\dev\signup\config\databases.yml
dev:
propel:
param:
classname: DebugPDO

test:
propel:
param:
classname: DebugPDO
param:
classname: DebugPDO
dsn: 'mysql:host=localhost;dbname=signup_test'
username: root
password: null

all:
propel:
class: sfPropelDatabase
param:
classname: PropelPDO
dsn: mysql:dbname=signup_dev;host=localhost
username: root
password:
encoding: utf8
persistent: true
pooling: true

Is the class, form etc etc created by writing only these above line of code? It’s impossible. Yes it’s really impossible until you run few lines of code at command prompt. Lets do that.

  • first create create two database named signup_dev and signup_test from your browser http://localhost/phpmyadmin
  • now from command promt: d:\dev\signup>php symfony propel:build-all
    automatically generate lot of classes for you inside d:\dev\signup\lib\. don’t get any file? don’t worry look inside model, form, filter folder :D

i hope you have fair experience of PORT BASED SETUP. if No then you are most welcome :) . simply add these lines at the end of your configuration file apache\conf\httpd.conf

Listen 127.0.0.1:8081

DocumentRoot "D:\dev\signup\web"
DirectoryIndex index.php

AllowOverride All
Allow from All

Alias /sf D:\dev\signup\lib\vendor\symfony\data\web\sf

AllowOverride All
Allow from All


now try to run http://localhost:8081/frontend_dev.php what comes here? “Symfony Project Created”. right? which mean’s you are Successful at first stage!! YEAAAAAAA !! Lets celebrate!!

YAML Database Format

[NOTE: copy and paste from : http://www.symfony-project.org/jobeet/1_2/Propel/en/03 ]

According to the official YAML website, YAML is “is a human friendly data serialization standard for all programming languages”

Put another way, YAML is a simple language to describe data (strings, integers, dates, arrays, and hashes).

In YAML, structure is shown through indentation, sequence items are denoted by a dash, and key/value pairs within a map are separated by a colon. YAML also has a shorthand syntax to describe the same structure with fewer lines, where arrays are explicitly shown with [] and hashes with {}.

By Example, here is a YAML database schema
schema.yml
# config/schema.yml
propel:
jobeet_category:
id: ~
name: { type: varchar(255), required: true }

jobeet_job:
id: ~
category_id: { type: integer, foreignTable: jobeet_category, foreignReference: id, required: true }
type: { type: varchar(255) }
company: { type: varchar(255), required: true }
logo: { type: varchar(255) }
url: { type: varchar(255) }
position: { type: varchar(255), required: true }
location: { type: varchar(255), required: true }
description: { type: longvarchar, required: true }
how_to_apply: { type: longvarchar, required: true }
token: { type: varchar(255), required: true, index: unique }
is_public: { type: boolean, required: true, default: 1 }
is_activated: { type: boolean, required: true, default: 0 }
email: { type: varchar(255), required: true }
expires_at: { type: timestamp, required: true }
created_at: ~
updated_at: ~

jobeet_affiliate:
id: ~
url: { type: varchar(255), required: true }
email: { type: varchar(255), required: true, index: unique }
token: { type: varchar(255), required: true }
is_active: { type: boolean, required: true, default: 0 }
created_at: ~

jobeet_category_affiliate:
category_id: { type: integer, foreignTable: jobeet_category, foreignReference: id, required: true, primaryKey: true, onDelete: cascade }
affiliate_id: { type: integer, foreignTable: jobeet_affiliate, foreignReference: id, required: true, primaryKey: true, onDelete: cascade }

The schema.yml file contains the description of all tables and their columns. Each column is described with the following information:

type: The column type (boolean, tinyint, smallint, integer, bigint, double, float, real, decimal, char, varchar(size), longvarchar, date, time, timestamp, blob, and clob)
required: Set it to true if you want the column to be required
index: Set it to true if you want to create an index for the column or to unique if you want a unique index to be created on the column.

lets try symfony

Symfony is an excellent framework which make programmer’s life more easier. fully structured, easy to build, debug and extend application.
First donwload symfony and extract into your web root.
Database: Some tools allow you to build a database graphically (for instance Fabforce’s Dbdesigner) and generate directly a schema.xml (with DB Designer 4 TO Propel Schema Converter).

Category: Symfony  Leave a Comment