Archive | April, 2009

Apache: Setting virtual host on local system

24 Apr

It was up to this task since yesterday. I haven’t done this before, setting sub domain- virtual host on local system. I tried a lot yesterday but in vain, however when I came to office today I configured it successfully.

As I was stuck in the middle and feel lot of pain, so I better write it for those facing the same issue.

Why I was up to this task?

Well, actually my client was facing problem and reported that session is not working properly on domain and sub domain. So I was having no way other than setting virtual host.

However before leaving yesterday, I talked to my client that I am unable to solve this problem. He told me that I shouldn’t be worried about it because he will take care of this issue. The more important thing is that when I arrived today, I found that the problem has already been solved. Thanks to him for giving my favor.

Thought the problem has been solved, but still is worthy to write a small post here because I have successfully solved the problem.

Before going to discuss it, I would like to tell you that the configuration has been taken place on window so the paths may not be same.

Let have a look.

First of all you will need to open.

C:\xampp\apache\conf\extra\httpd-vhosts.conf

I assumed that you have install xampp.

And add following lines to httpd-vhosts.conf file.

NameVirtualHost *:80

<VirtualHost *:80>

ServerName localhost

DocumentRoot “C:/xampp/htdocs/”

ServerAdmin admin@localhost

</VirtualHost>

<VirtualHost *:80>

ServerName mysite.com.localhost

DocumentRoot “C:/xampp/htdocs/mysite/”

ServerAdmin admin@mysite.com.localhost

<Directory “C:/xampp/htdocs/mysite/”>

Options Indexes FollowSymLinks

AllowOverride FileInfo

Order allow,deny

Allow from all

</Directory>

</VirtualHost>

Here I have defined server localhost pointing to my default htdocs directory and another host mysite.com.localhost pointing to “C:/xampp/htdocs/mysite/”.

Another important thing is <VirtualHost *:80>

Here you would need to specify the port. In  my case its 80.

If you don’t specify the port on which apache listen, apache may take you to the same page for both the server. So be careful.

Next go to your Window/system32/dirvers/etc/ and open hosts file.

You will find

127.0.0.1       localhost

At the end of the file. Add following line next to it.

127.0.0.1         mysite.com.localhost

Reboot your system and you are done.

Advertisements

Zend Framework: Select statement and where clause examples

17 Apr

When it comes to retrieving data, nothing can be done unless using select statement. Sql is as easy as simple English, however we technical people don’t know much about languages and when think as functions, classes and objects. We love to use functions, modules, classes and objects. In sql

SELECT * FROM table_name

WHERE condition

Statement can easily be understood, however, how if we do the same things using functions and objects etc. It would be great, no doubt.

You’d be glad to work in Zend Framework if you think as I think. I feel comfortable using functions and objects. Another important thing is, you don’t need to learn sql if you don’t want, but only need to learn functions that do everything under the hood.

Zend Framework team has done a fabulous job, providing methods for interacting with database. Though all the database related things are impossible to cover in single post, I’d discuss the usage of select statement here.

I always encourage creation of separate php file for each of your database table in your models directory and create a custom class extending from Zend_Db_Table or Zend_Db_Table_Abstract.

The code can be written as

<?php

class Users extends Zend_Db_Table

{

protected $_name = ‘tbl_users’;

}

I assume that you have a table named “tbl_users”.

After extending your class from Zend_Db_Table, you get access to all the methods defined in Zend_Db_Table as well as Zend_Db_Table_Abstract, because Zend_Db_Table extends Zend_Db_Table_Abstract. The method available are in those two table are insert, update, delete etc.

Although you can use these methods provided by ZF in your controller by creating object of your own class. The code might be

$users = new Users();

$users->insert(array());

Keep in mind that here I have given an empty array, you can give associative array to insert specific values in specific columns of the tbl_users.

Although built-in function exist, however sometime you need to define your own custom methods.

Like

function getUserDataById($id) {

}

This function return data based on the id given. The code it may contain

Public function getUserDataById($id) {

$select = $this->_db->select()

->from($this->_name)

->where(‘id = ?’, $id);

$result = $this->getAdapter()->fetchAll($select);

return $result;

}

This is what I was intending to tell you. The from and where clauses. Its all seems simple. You don’t need to care how ZF build query for you.

The first line say, select and then from method is called, getting the name of the table. The where clause tells that id should be set to what we have sent as parameter.

Its very simple, isn’t it?

Wow, a question comes to mind how this query looks like in sql. Well, I want to say that ZF will create the following query for you.

SELECT * FROM tbl_users

WHERE id = 3

Yes if you have sent 3 as parameter. You can sent any number and the query will retrieve data based on that id.

Let’s make this query a bit complex, actually simple.

How if you want to select specific column only?

It will easy to do than say using ZF.

$select = $this->_db->select()

->from($this->_name,array(‘col2′,’col3’))

->where(‘id = ?’, $id);

I have made only one change, an additional array is sent as parameter to the from method.

Here col2 and col3 are the name of the column in the table tbl_users.

Another question can also come straight to mind.

How to And two condition? Like

WHERE id = 3 and name = ‘a’

It again very simple, write something like this.

$select = $this->_db->select()

->from($this->_name,array(‘col2′,’col3’))

->where(‘id = ?’, $id)

->where(‘name = ?’ , ‘a’);

Keep in mind that you can place “=” with any valid sql operator.

This will make an “AND” query.

What if you want to make “OR” query?

Its simple is that.

$select = $this->_db->select()

->from($this->_name,array(‘col2′,’col3’))

->where(‘id = ?’, $id)

->orwhere(‘name = ?’ , ‘a’);

I replaced where with orwhere, as simple as this.

Hopefully I’ll discuss some more magic of Zend_Db in coming days.

Cheers.

Zend Framework: Uploading and renaming multiple files

16 Apr

Waf!, I used Zend_File component about two month back. Did I test that before writing an article, yes surely, I did. But what, I did that for only one file, though I was intending to upload multiple files. I didn’t check my directory, however no exception was thrown and no error message jumped out. I thought that I have successfully completed my job and now its time to write an article to help those needed.

Sorry gays, I was completely wrong. The example, if you have used upload only one file.

A person once post his/her comments that It won’t upload multiple files, however I was having enough time to test my code again.

But today I decided that I will need to do something and make this example working as I was intending to make it. So I’m here to tell you how to upload multiple files.

An addition to uploading multiple files, I’d show you how to rename files.

In the first example I’d tell you how to upload multiple files and then in the second example I’d tell you how to rename them if you like.

So let have a look.

First of all, create your form as

<?php

class CustomForm extends Zend_Dojo_Form

{

public function init()

{

$this->setMethod(‘post’);

$this->setAttrib(‘enctype’, ‘multipart/form-data’);

$ this ->addElement(‘file’,’file1′,array(‘label’=>’File1’));

$ this ->addElement(‘file’,’file2′,array(‘label’=>’File1’));

$ this ->addElement(‘submit’,’submit’);

}

}

In the code above we have done thing more than creating a form, setting its method, enctype, add two file elements and submit button.

Now in controller write

$form = new CustomForm();

$this->view->form = $form;

if($this->getRequest()->isPost()) {

if  ($form->isValid($_POST)) {

$adapter=new Zend_File_Transfer_Adapter_Http();

$uploadDir=dirname(__File__);

$adapter->setDestination($uploadDir);

foreach ($adapter->getFileInfo() as $info) {

if(!$adapter->receive($info[‘name’])){

$this->view->msg=$adapter->getMessages();

return;

}

}

}

}

Okay, the entire logic is written in the above code. First we create our own custom form instance and assign it to the view template. Then we check if the form is submitted by using isPost() method. In the next condition we check if the form is validly posted. I yes, we create an adapter. You will need to create transfer adapter.

In the next line we set our destination directory, directory we want to upload our files.

Foreach loop is compulsory for uploading multiple files, if you want to upload single file then there is no need to use this loop.

After the foreach loop we call receive method giving name of each file.

That’s it, we have done.

Renaming files will take some extra code. Make the following changes in your controller.

$form = new CustomForm();

$this->view->form = $form;

if($this->getRequest()->isPost()) {

if  ($form->isValid($_POST)) {

$adapter=new Zend_File_Transfer_Adapter_Http();

$uploadDir=dirname(__File__);

$adapter->setDestination($uploadDir);

$i= 1;

foreach ($adapter->getFileInfo() as $info) {

$ext = $this->_findexts($info[‘name’]);

$fileName = ‘file’.$i.time().”.”.$ext;

$i++;

$adapter->addFilter(‘Rename’,

array(‘target’ => $uploadDir.DIRECTORY_SEPARATOR.$fileName,

‘overwrite’ => true));

if(!$adapter->receive($info[‘name’])){

$this->view->msg=$adapter->getMessages();

return;

}

}

}

}

protected function _findexts($filename)

{

$filename = strtolower($filename) ;

$exts = split(“[/\\.]”, $filename) ;

$n = count($exts)-1;

$exts = $exts[$n];

return $exts;

}

The only change made are in bold. We have defined a protected method for find the extension.

We call this function to get the file extension, which is concatenated with the name of the file, we are building.

The real part is performed by

$adapter->addFilter(‘Rename’,

array(‘target’ => $uploadDir.DIRECTORY_SEPARATOR.$fileName,

‘overwrite’ => true));

Here if don’t give “overwrite”, zend will generate error if file with the same name already exist.

PHP Extensions: building your extension part 1

15 Apr

Before going to discuss how many files you will need and the code, I’d like to tell that building extension is not a fun, so need a bit of extra concentration.

If someone ask me why I’ve learnt extension development?

I’ll simply say, for fun.

Although it’s my view point, however extension development come handy,if

  1. you want functionality that is not currently available in php
  2. you want to sold your product/application without giving away your code.
  3. functionality available in php but performance is slow,  this is because upperspace code take a bit longer than the code written in c that directly communicate.

Regardless of what is your requirements, in next few articles I would give you inner knowledge of how zend engine handle extension and how to build them.

To build a successful extension, you will need to have latest version of php, apache, pear and phpize install on your system.

Keep in mind that all the examples I’d give build under *nix family, so they will need some extra effort and little bit of changes in your code as well if you want them to build for windows.

Well, I was talking about the installation.

To have latest version of php on your system installed, open your console and write

$ sudo apt-get install php5

follow the instruction, this will install latest version of php.

Next for installing apache, write

$ sudo apt-get install apache2

and for pear

$ sudo apt-get install php-pear

and similarly for phpize, run the following command

$ sudo apt-get install php5-dev

You have now successfully install all the packages needed. Next step is to understand what files you will need to build an extension.

For building php extension, you will minimum of three files

  1. config.m4
  2. header file
  3. c source file

here c mean c language.

Make directory wherever you like and create the following three file

  1. config.m4
  2. php_sample.h
  3. sample.c

Now open config.m4 file and write the following code in it.

PHP_ARG_ENABLE(sample, Whether enable “sample” support,

[ –enable-sample         Enable “sample” support])

if test “$PHP_SAMPLE” = “yes”; then

AC_DEFINE(HAVE_SAMPLE, 1, [Sample exists])

PHP_NEW_EXTENSION(sample, sample.c, $ext_shared)

fi

That’s it we have now created the configuration file. Phpize use this file for extension development.

Next step is to define our header file.

So open php_sample.h and write the following code in it.

#ifndef HAVE_SAMPLE_H

#define HAVE_SAMPLE_H

#endif

#define PHP_SAMPLE_EXTNAME “sample”

#define PHP_SAMPLE_VERSION “1.0”

PHP_FUNCTION(sample_hello);

#ifdef HAVE_CONFIG_H

#include “config.h”

#endif

#include “php.h”

extern zend_module_entry sample_module_entry;

#define php_sample_extptr &sample_module_entry

This is our header file. Defining some micros, declaring a php function that will be defined later in the c source file and including some necessary header files.

Now its time to write the actual code that will having the functionality.

In your sample.c, write the following code.

#include “php_sample.h”

static function_entry php_sample_functions[] = {

PHP_FE(sample_hello, NULL);

{NULL, NULL, NULL}

};

zend_module_entry sample_module_entry = {

#if ZEND_MODULE_API_NO >= 20010901

ZEND_MODULE_HEADER,

#endif

PHP_SAMPLE_EXTNAME,

php_sample_functions,

NULL,

NULL,

NULL,

NULL,

NULL,

#if ZEND_MODULE_API_NO >= 20010901

PHP_SAMPLE_VERSION,

#endif

ZEND_MODULE_PROPERTIES

};

PHP_FUNCTION(sample_hello)

{

RETURN_STRING(“Hello world!”,1);

}

That’s it we have now define all the three file, now its time to build our first php extension.

Open your console and goto the directory where you have created these files using cd command.

Now write

$ sudo phpize

$ sudo ./configure -enable-hello

$ sudo make

these command will create few files and some directories. You extension file (sample.so) will reside under modules directory. Copy this file to your extension directory, make necessary configuration for enabling your extension in php.ini file and restart your apache with the following command.

$ sudo /etc/init.d/apache2 restart

And now open your php file and write the following code

echo sample_hello();

open yor php file using any browser, the browser must show the following contents.

Hello world!

If not, you may have missed something in the code.

Though lot of things aren’t explained here, however I’ll explain them as we move forward.

Why don’t Pakistani IT professionals write blogs?

14 Apr

Blogs really crucial these days, sort of web pages for sharing your knowledge, experience, and even personal information, gossips and even pictures and videos.

This is a kinda trend in developers all around the world to make their blogs and share their knowledge base. I’ve seen plenty of developers around the world, have made networks and writing constantly on their blogs. Blogs also used to increase web pages traffic rank, not of my concern.

Well, whatever the reason is behind writing blog?  The fact is writing blog not only help other and give them lot of relief, but also give the writer lot of skills and techniques of getting out of the problems. One can visit his own blog, when a problem he had faced earlier come to front.

Since I am writing my own blog, I haven’t only helped lot of developers around the world, but I have taken help myself in plenty of cases.

You may feel, while writing on specific topic, that who will read this and who much of them will find it helpful, completely useless, but I’ve seen that topics that were less important to me, where of great importance to others.

So please write and share your knowledge, coz sharing your knowledge with others increase your own knowledge.

Zend Framework: using JSon and Prototype for filling form on fly

2 Apr

I used JSon for the first time in my application today. Zend provide a very easy way to create JSon response.

In this article I would use Prototype to make ajax call. Hopefully you will know a bit about Prototype. Anyway if not, it’d not be a hard job to understand it after reading my article.

So let’s get started.

Consider you have the following form.

Zend Form

Zend Form

The scenario is

When user select name from the dropdown, the entire form is filled with the data from the database for that particular user.

For this purpose you would need to have a controller/Action(s), a model and template file.

In your form attach the following attrib to your name element as

$name = $this->createElement(‘select’,’name’);

$name->addMultioptions(array(

‘select’=>'[select]’,

‘1’ => ‘Faheem’,

‘2’ => ‘Abbas’

));

$name->setAttrib(‘onchange’,’AutoFill(this.value)’);

In the lines above we first create a dropdown give it two values. And then attach javascript function “AutoFill” function using setAttrib method.

In your controller initialize your form and assign it to the view template as

$form = new MyCustomForm();

$this->view->form = $form;

Now in your view template file write the following.

Write the following javascript code.

<script>

function AutoFill(value)

{

new Ajax.Request(

“<?=$this->url(array(‘controller’=>’user’,’action’=>’getdata’))?>”,

{

method:’get’,

parameters: {id: value},

onSuccess: FillForm

}

);

}

function FillForm(rsp)

{

var card = eval(‘(‘ + rsp.responseText + ‘)’);

$(‘address1).value = card.items[0].address1;

$(‘address2’).value = card.items[0].address2;

$(‘postalcode’).value = card.items[0].postalcode;

}

</script>

To get response you will need to create an action and write the following code

<?php

class User extends Zend_Controller_Action

{

public function indexAction()

{

$form = new MyCustomForm();

$this->view->form = $form;

}

public function getdataAction()

{

$this->_helper->layout()->disableLayout();

$users = new Users();

$this->_helper->viewRenderer->setNoRender();

if ($this->getRequest()->isXmlHttpRequest()) {

$id = $this->_getParam(‘id’);

$userData = $ users ->getData($id);

$dojoData= new Zend_Dojo_Data(‘id’,$userData,’id’);

echo $dojoData->toJson();

}

}

}

In the above code getdataAction is called using ajax call. In the first line we have disabled the layout, because we don’t need layout in case of ajax response. Next we create object of our model class(discussed later). Next we tell zend to disable view rendering.

In the next few lines we check for ajax request, get id, call our getData model method.

We then create dojo data object. This object provide a very useful method to convert data retrieved into json format. The method used is toJson().

In our model we have code like the following.

<?php

class Users extends Zend_Db_Table

{

protected $_name = ‘users’;

public function getData($id)

{

$select = $this->_db->select()

->from($this->_name,

array(‘id’,’address1′,’address2’….))

->where(‘id = ?’, $id);

$result = $this->getAdapter()->fetchAll($select);

return $result;

}

}