So you’ve discovered the awesomeness of CodeIgniter and you need an ORM. You’ve read about people around StackOverflow and the CodeIgniter forums recommending Doctrine as an object mapper. You’ve tried and tried but Doctrine and CodeIgniter are just not playing nicely together. Well has a stupendous tutorial… for CodeIgniter < 2.0 and Doctrine < 2.0. We need something more recent, eh?

Well, I walked the same rocky road and decided to make my own tutorial. Yah, yah, there’s already a bunch out there. But they either suck or don’t apply to CodeIgniter 2 or Doctrine 2. Mine doesn’t suck. I hope.

So for future reference, here are the versions I am working with during this tutorial, but similarly versions should work just fine:

  • CodeIgniter 2.1.0 (mirror)
  • Doctrine 2.2.1 (mirror)
  • Also, I am running Apache 2.2.20, PHP 5.3.6 (with APC), MySQL 5.1.58, all on Ubuntu Server 11.10.
  • I am assuming you already have a MySQL database (with valid a user) set up.


The following versions have been tested to make sure they fully work with this tutorial:

  • CodeIgniter 2.1.0 and Doctrine 2.2.1
  • CodeIgniter 2.0.2 (mirror) and Doctrine 2.0.5 (mirror)

If you want to work with a different version of CodeIgniter or Doctrine, this tutorial should still be totally fine as long as the version of CodeIgniterand Doctrine are version 2.x.x! You may have to change the paths of downloads a bit (i.e. changing a in a URL to, but everything else will be exactly the same. If you can’t handle that, I’d recommend firing up a WordPress instance and going from there…

Tutorial Context

Also, here are some names I will be using throughout the tutorial. Replace them with whatever paths or names that are relevant to your project.

  • Project Name: Emma Watson Shrine
  • Project Directory: C:\xampp\htdocs\emma_watson_shrine

I am going to try to make this as easy on you as possible, so I will give all of the steps necessary to get this stack up and running. In other words, you shouldn’t even have to read the Doctrine and CodeIgniter documentation, although it is HIGHLY recommended.

“And away we go…”

Download and Configure CodeIgniter

  1. Download the CodeIgniter archive, extract it, and move it to the location that you’d like your project to reside.
    ### go to the web directory
    cd C:\xampp\htdocs
    ### download CodeIgniter from
    ### unzip the archive
    ### remove the archive
    ### rename the extracted archive to the desired project directory
    CodeIgniter_2.1.0  to emma_watson_shrine
  2. Make sure your project’s directory has proper permissions. This kind of depends on your server’s setup, but I set my project’s directory permissions to 755. If you’re not sure about this, skip to the next step. It’s most likely that the permissions are okay if you used an FTP program to upload the CodeIgniter files.
    chmod -R 755 emma_watson_shrine
    Note: For xampp on windows you dont have to worry about permissions.
  3. CodeIgniter still needs some configuration, but it’s running! When you view your project directory in your browser, it should look something like this: screenshot.
  4. Now let’s take some time to configure CodeIgniter. Don’t worry, it’s really quick!
    1. Open CodeIgniter’s config file in the text editor of your choice.
    2. Set the base URL.
      $config['base_url'] = 'http://localhost/emma_watson_shrine/';
    3. Open CodeIgniter’s database config file.
    4. Set up the database information. This is the database that Doctrine will use.
      $db['default']['hostname'] = 'localhost';
      $db['default']['username'] = 'emmawatson';
      $db['default']['password'] = 'ronweasley';
      $db['default']['database'] = 'emmawatson';

And that’s really all there is to it! CodeIgniter, for the win!

Download Doctrine

  1. Download the Doctrine archive, extract it, and move it to your CodeIgniter application’s library directory. Keep in mind that the archive you download has two sub-directories: bin and Doctrine. The Doctrine directory is what you actually need.
    ### go to the libraries directory
    cd C:\xampp\htdocs\emma_watson_shrine\application\libraries
    ### download Doctrine
    ### extract the archive(use winrar)
    ### pull out the directory we need
    ### remove the other stuff we don't need
    DoctrineORM-2.2.1 DoctrineORM-2.2.1-full.tar.gz

Add Doctrine as a CodeIgniter library

This is when things start getting a bit more confusing. So read carefully!

  1. Go to your CodeIgniter applications’s library directory. We need to make a PHP class that will help our CodeIgniter controllers talk use Doctrine’s all-powerful Entity Manager. Create a new file at the following path and open it up in a text editor:
    vim /var/www/emma_watson_shrine/application/libraries/Doctrine.php
  2. Paste this code in. Read the in-code comments for explanation, if you want to learn a thing or two. Here’s a link to Doctrine.php if you just want to download it to the right location.
    class Doctrine
        // the Doctrine entity manager
        public $em = null;
        public function __construct()
            // include our CodeIgniter application's database configuration
            require_once APPPATH.'config/database.php';
            // include Doctrine's fancy ClassLoader class
            require_once APPPATH.'libraries/Doctrine/Common/ClassLoader.php';
            // load the Doctrine classes
            $doctrineClassLoader = new \Doctrine\Common\ClassLoader('Doctrine', APPPATH.'libraries');
            // load Symfony2 helpers
            // Don't be alarmed, this is necessary for YAML mapping files
            $symfonyClassLoader = new \Doctrine\Common\ClassLoader('Symfony', APPPATH.'libraries/Doctrine');
            // load the entities
            $entityClassLoader = new \Doctrine\Common\ClassLoader('Entities', APPPATH.'models');
            // load the proxy entities
            $proxyClassLoader = new \Doctrine\Common\ClassLoader('Proxies', APPPATH.'models');
            // set up the configuration 
            $config = new \Doctrine\ORM\Configuration;
            if(ENVIRONMENT == 'development')
                // set up simple array caching for development mode
                $cache = new \Doctrine\Common\Cache\ArrayCache;
                // set up caching with APC for production mode
                $cache = new \Doctrine\Common\Cache\ApcCache;
            // set up proxy configuration
            // auto-generate proxy classes if we are in development mode
            $config->setAutoGenerateProxyClasses(ENVIRONMENT == 'development');
            // set up annotation driver
            $yamlDriver = new \Doctrine\ORM\Mapping\Driver\YamlDriver(APPPATH.'models/Mappings');
            // Database connection information
            $connectionOptions = array(
                'driver' => 'pdo_mysql',
                'user' => $db['default']['username'],
                'password' => $db['default']['password'],
                'host' => $db['default']['hostname'],
                'dbname' => $db['default']['database']
            // create the EntityManager
            $em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
            // store it as a member, for use in our CodeIgniter controllers.
            $this->em = $em;
  3. Open CodeIgniter’s autoload config file.
    vim /var/www/emma_watson_shrine/application/config/autoload.php

    Add doctrine to the autoloaded libraries.

    $autoload['libraries'] = array('doctrine');
  4. You should be able to view your project directory in your browser at this point without any errors coming up. If you have, double back and make sure you’ve followed all the steps. Furthermore, the page should look exactly as it did before you added Doctrine as a library.

Add Models to Doctrine

From here on, what you need to do really depends on what you would like your website to do. Since I am making a shrine dedicated to Emma Watson, I think I’ll need two models (represented by two tables): a User object and an Article object. The User object will hold information about an individual user. The Article object will have an author (linking to a User object) and other information for displaying an article. Something we need to get straight first is that the models generated by Doctrine are going to be different than CodeIgniter models (i.e. they will not extend the CI_Model class).

  1. Create a Mappings directory in your application’s models directory.
    cd C:\xampp\htdocs\emma_watson_shrine\application\models
    mkdir Mappings
    cd Mappings
  2. Create some YAML mapping files and put them in the Mappings directory. How to do this is outside the scope of this tutorial, but I will provide mine as examples. Here is a link to the Doctrine documentation on how to format these file. Make sure the mapping files have the “.dcm.yml” file extension and the “Entities.” prefix. The extension tells Doctrine that this file is a YAML mapping file, and the prefix tells Doctrine to put the models in the Entity namespace.
    • When declaring the name of your object, make sure to prefix the name with Entities\ to put it in the Entities namespace.
    • Here is the YAML file for my User object. The file name should be Entities.User.dcm.yml.
        type: entity
        table: users
              - email
            type: integer
            id: true
              strategy: AUTO
            type: string
            length: 32
            nullable: false
            type: string
            length: 255
            nullable: false
            column: first_name
            type: string
            length: 255
            nullable: false
            column: last_name
            type: string
            length: 255
            nullable: false
            type: string
            length: 255
            nullable: true
            type: datetime
            nullable: false
    • And here is the YAML file for my Article object. The file name should be Entities.Article.dcm.yml.
        type: entity
        table: articles
            type: integer
            id: true
              strategy: AUTO
            type: string
            length: 255
            nullable: false
            type: text
            nullable: false
            type: datetime
            nullable: false
            targetEntity: User
                referencedColumnName: id
  3. Go back to the models directory and create two more directories: “Entities” and “Proxies“. Proxies is the directory that will hold the proxy classes that Doctrine uses. If you’re really smart, you should be able to figure out what the Entities directory is for. Since this is the Internet, I think it’s safe to assume that I should explain it to you. It’s the directory that holds the Entities!
    cd C:\xampp\htdocs\emma_watson_shrine\application\models
    mkdir Entities Proxies

Configure Doctrine Command Line Tool

To use Doctrine, you need set up the command line tool, which helps you with a lot of tasks, like automatically creating the schema in your database, generating proxy classes, etc.

  1. Go to your application’s application directory and create a file called doctrine-cli.php. This is a PHP file that you will need to run through the command line PHP program. Alternatively, download this file to your application directory and skip the next step. Make sure you change the APPPATH definition in the code to fit your needs!
    cd C:\xampp\htdocs\emma_watson_shrine/application
    vim doctrine-cli.php
  2. Put the following contents in your doctrine-cli.php file. As I said above, make sure you change the APPPATH in the code definition to fit your needs!
    // trailing slash is important!
    define('APPPATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
    define('BASEPATH', APPPATH);
    define('ENVIRONMENT', 'production');
    require APPPATH.'libraries/Doctrine.php';
    $doctrine = new Doctrine();
    $helperSet = new \Symfony\Component\Console\Helper\HelperSet(array(
        'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($doctrine->em->getConnection()),
        'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($doctrine->em)
    $cli = new \Symfony\Component\Console\Application('Doctrine Command Line Interface (CodeIgniter integration by Joel Verhagen)', Doctrine\ORM\Version::VERSION);
        // DBAL Commands
        new \Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
        new \Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
        // ORM Commands
        new \Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
        new \Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
        new \Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
        new \Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
        new \Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
        new \Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
        new \Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
        new \Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
        new \Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
        new \Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
        new \Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
        new \Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
        new \Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
        new \Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
  3. Now run this script through the PHP command-line and should see a list of commands available to you.
    php doctrine-cli.php

    The output should look something like this:

    Doctrine Command Line Interface (CodeIgniter integration by Joel Verhagen) version 2.0.5
      [options] command [arguments]
      --help           -h Display this help message.
      --quiet          -q Do not output any message.
      --verbose        -v Increase verbosity of messages.
      --version        -V Display this program version.
      --ansi           -a Force ANSI output.
      --no-interaction -n Do not ask any interactive question.
    Available commands:
      help                         Displays help for a command (?)
      list                         Lists commands
      :import                      Import SQL file(s) directly to Database.
      :run-sql                     Executes arbitrary SQL directly from the command line.
      :convert-d1-schema           Converts Doctrine 1.X schema into a Doctrine 2.X schema.
      :convert-mapping             Convert mapping information between supported formats.
      :ensure-production-settings  Verify that Doctrine is properly configured for a production environment.
      :generate-entities           Generate entity classes and method stubs from your mapping information.
      :generate-proxies            Generates proxy classes for entity classes.
      :generate-repositories       Generate repository classes from your mapping information.
      :run-dql                     Executes arbitrary DQL directly from the command line.
      :validate-schema             Validate that the mapping files.
      :metadata                    Clear all metadata cache of the various cache drivers.
      :query                       Clear all query cache of the various cache drivers.
      :result                      Clear result cache of the various cache drivers.
      :create                      Processes the schema and either create it directly on EntityManager Storage Connection or generate the SQL output.
      :drop                        Drop the complete database schema of EntityManager Storage Connection or generate the corresponding SQL output.
      :update                      Processes the schema and either update the database schema of EntityManager Storage Connection or generate the SQL output.

Setup Entities, Proxies, and Database Schema

We’re getting close here. Really the last thing you need to do before you can jump into developing your Facebook killer.

  1. For all of the steps in this section, you’ll need to simply call the Doctrine command line tool that you got working in the previous section. The order of these steps does matter!
    cd /var/www/emma_watson_shrine/application
  2. Let’s go ahead and generate the entity classes. Note that we are creating them in the models directory. Doctrine detects that they are in the Entities namespace and automatically puts them in the Entities subdirectory. Keep in mind that these entity classes come with getters/setters for all of the fields you defined in your YAML file but can be modified to add custom methods and such.
    php doctrine-cli.php orm:generate-entities models
  3. Now the proxy classes.
    php doctrine-cli.php orm:generate-proxies
    Note : you may get a error if you are running it using xampp on windows "Fatal error: Call to undefined function Doctrine\Common\Cache\apc_fetch() in 
    /Applications/XAMPP/xamppfiles/htdocs//application/libraries/Doctrine/Common/Cache/ApcCache.php on line".
    solution : You can download php_apc.dll here:
    download the .dll file based on your php version and OS place it under C:\xampp\php\ext folder and put extension=php_apc.dll at php.ini restart xampp.
  4. If you’ve tried this before and your database is not empty, you’ll need to do this step. Otherwise, skip it.
    php doctrine-cli.php orm:schema-tool:drop --force
  5. And finally, let’s create the database tables for Doctrine to store our objects in.
    php doctrine-cli.php orm:schema-tool:create

Using Doctrine in a CodeIgniter Controller

Believe it or not, you’ve just made it through all the hard stuff. With all that stupid configuration stuff out of the way, you can get to coding. Yay! Since we added Doctrine as an autoloaded library, we don’t even need to fool with loading Doctrine every time you create a new controller. Also, the library file (libraries/Doctrine.php) has a auto-load call that makes it so all of the entities you put in the models/Entities directory are automatically available to your controllers! If you know what you’re doing, go ahead and leave this page. Get coding! Otherwise, I’m going to give you a few code samples so you can start using Doctrine.

  1. How do I create a new entity and save it into the database?


    public function createObjects()
        // create a new user object
        $user = new Entities\User;
        $user->setPassword(md5('Emma Watson'));
        $user->setCreated(new DateTime());
        // standard way in CodeIgniter to access a library in a controller: $this->library_name->member->memberFunction()
        // save the object to database, so that it can obtain its ID
        // create a new article object
        $article = new Entities\Article;
        $article->setTitle('Emma Watson is extremely talented, no?');
        $article->setContent('By talented, I mean good at lookin\' good.');
        $article->setCreated(new DateTime());
        // the user object you pass must be persisted first!
        // save the article object to the database
        echo "<b>Success!</b>";
  2. How do I get an entity from the database?

    Child’s play.

    public function getObjects()
        // get an object by ID
        $user = $this->doctrine->em->find('Entities\User', 1);
        echo $user->getFirstName().' '.$user->getLastName().' is a real chill guy.<br />';
        // get a related object
        $article = $this->doctrine->em->find('Entities\Article', 1);
        $user = $article->getUser();
        echo $user->getFirstName().' '.$user->getLastName().' thinks CodeIgniter + Doctrine is real slick. <br />';
        // what happens when we try to get an object that doesn't exist?
        $article = $this->doctrine->em->find('Entities\Article', 9001);
            // the "find" call returns NULL!
            echo 'Dude, that article number 9001 doesn\'t even exist yet.<br />';
        // get an object by another field
        $user = $this->doctrine->em->getRepository('Entities\User')->findOneBy(array('email' => ''));
        echo $user->getFirstName().' '.$user->getLastName().' is glad he isn\'t dealing with Symfony.<br />';
  3. Can I add custom methods to my entities?


    namespace Entities;
     * Entities\User
    class User
        // my custom function :)
        public function getFullName()
            return $this->firstName.' '.$this->lastName;
    original article by : Joel Verhagen

It isn’t obvious at first how to list all the members of a group from a Linux command line (I’m using Ubuntu Server 10.04 Lucid Lynx).

Listing A User’s Groups

It is very easy to list the groups that a user belongs to. Simply use the groups command.

$ groups user

This command will output the user name and a space-delimited list of all the groups that user belongs to, as follows:

user : user dialout cdrom floppy audio dip vido plugdev users fuse lp admin sambashare

Listing a Group’s Members (Users)

If you want to do the opposite, and list the members of a group, you can use the members command. The catch is: the command is not installed by default. Fortunately, it is simple to install:

$ sudo apt-get install members

Once the package is installed, you can issue the members command similarly to how you issue the groups command.

$ members groupname

This will output a space-delimited list of all the members of the group, as follows:

member1 member2 member3

Unlike the groups command, it does not output the name of the group. You may use the optional arguments --primary and --secondary to list only the primary or secondary users within the group.


In the last tutorial, you learnt how to widgetize your wordpress theme to support wordpress widgets. Now this tutorial explains how to create multiple dynamic sidebars to add various combinations of widgets to customize your wordpress theme even more.

I suggest you read how to Widget-Enable WordPress Themes in 3 Easy Steps before reading further as examples will be quoted in the same context.

Edit Functions.php for Multiple Dynamic Sidebars

The functions.php code which helped to widgetize your wordpress theme and support a single dynamic sidebar, now needs to be edited (using any text editor like Notepad) to support multiple sidebars. You remember we had modified the default function.php from


if ( function_exists('register_sidebar') )


to the new code below to support our customized template with h4 subtitles and non-default unordered lists in the sidebar. REMEMBER you need to edit functions.php to match your wordpress theme or it will not work.



<?php if ( function_exists('register_sidebar') ) register_sidebar(array( 'before_widget' => '', 'after_widget' => '', 'before_title' => '<h4>', 'after_title' => '</h4>', )); ?>

To support multiple sidebars, I simply need to specify that multiple sidebars be used and name them as I like. In our case I use Sidebar1, Sidebar2 etc and as many as you like. The code now looks like this –

 <?php if ( function_exists('register_sidebar') ) register_sidebar(array('name'=>'sidebar1', 'before_widget' => '', 'after_widget' => '', 'before_title' => '<h4>', 'after_title' => '</h4>', )); register_sidebar(array('name'=>'sidebar2', 'before_widget' => '', 'after_widget' => '', 'before_title' => '<h4>', 'after_title' => '</h4>', )); ?> 

I personally have extended this capacity to 6 dynamic sidebars on this blog. Here is how it looks like on top of admin panel.

4 Dynamic Widget Sidebars
Now you can drag and drop widgets of your choice to different sidebars and customize the options. Remember to Save Changes or else all customization is lost.

Add Dynamic Sidebars to WordPress Template

Now you need to place the code in the wordpress theme template where you want the relevant wordpress widgets to work. Instead of the previous code, you can place the different dynamic sidebars in different areas of the template.

Sidebar1 code goes like this

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar1') ) : ?> <?php endif; ?>


Sidebar2 code goes like this

<?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('sidebar2') ) : ?> <?php endif; ?>


Save the template and watch your widgets go live. You can add lots of dynamic sidebars with various widget combinations and have truly unique web design concept.

This PHP script will encrypt your PHP script using Base 64 encoding. A maximum limit of 10,000 character in your entire PHP code is allowed.
Copy and paste your script in the text area below (It is suggested to start with “<?php” and end your script with “?>”, to avoid any encoding errors)

Take note that not all PHP scripts can be successfully encoded using this script. It is recommended that you will test the script first in the development server before deploying it on the production server. This will avoid any possibility of having some encoding bugs undetected after encoding.

I use this tool to Encrypt MySQL server information:

<form action="<?php echo $SERVER['PHP_SELF']; ?>"
This tool will encrypt your PHP script using Base 64 encoding.<br />
Copy and paste your script in the text area below (It is suggested to start with "&lt;?php" and end your script with "?>", to avoid any encoding errors)<br />
<p><textarea name="forencrypt" rows="30" cols="30"></textarea></p>
<br />
<input type="submit" name="submit" value="Encrypt this PHP script now">
<a href="/encrypt-php.php">Click here to reset or clear this form</a>
<br />
This tool is developed by: <a href="">PHP Developer. org</a>
<br />
<font color="blue">
//License: Free to use and provided the link to SHOULD not be removed.Thanks.
//check if the form has been submitted
if (isset($_POST['forencrypt'])){
//form has been submitted
//remove space
//count string
$rest = substr($phpcode, 2, $last);
$display= substr($rest, 4);
$string= $display;
$compressed = gzdeflate($string, 9);
$encode = base64_encode($compressed);
echo "&lt;"."?"."php";
echo '<br />';
echo 'eval(gzinflate(base64_decode('.'''.$encode.'''.')));';
echo '<br />';
echo '?'.'>';

original post source »

One of the most common Apache2 questions I’ve seen on Debian mailing lists is from users who wonder how to host multiple websites with a single server. This is very straightforward, especially with the additional tools the Debian package provides.

We’ve previously discussed some of the tools which are included in the Apache2 package, but what we didn’t do was show they’re used from start to finish.

There are many different ways you can configure Apache to host multiple sites, ranging from the simple to the complex. Here we’re only going to cover the basics with the use of the NameVirtualHost directive. The advantage of this approach is that you don’t need to hard-wire any IP addresses, and it will just worktm. The only thing you need is for your domain names to resolve to the IP address of your webserver.

For example if you have an Apache server running upon the IP address and you wish to host the three sites,, and you’ll need to make sure that these names resolve to the IP address of your server.

(This might mean that you need and to resolve to the same address. However that is a choice you’ll need to make for yourself).

Since we’ll be hosting multiple websites on the same host it makes a lot of sense to be very clear on the location of each sites files upon the filesystem. The way I suggest you manage this is to create a completely seperate document root, cgi-bin directory, and logfile directory for each host. You can place these beneath the standard Debian prefix of /var/www or you may use a completely different root – I use /home/www.

If you’ve not already done create the directories to contain your content, etc, as follows:

root@irony:~# mkdir /home/www

root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/

root@irony:~# mkdir /home/www/ 
root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/

root@irony:~# mkdir /home/www/ 
root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/
root@irony:~# mkdir /home/www/

Here we’ve setup three different directory trees, one for each site. If you wanted to have identical content it might make sense to only create one, and then use symbolic links instead.

The next thing to do is to enable virtual hosts in your Apache configuration. The simplest way to do this is to create a file called /etc/apache2/conf.d/virtual.conf and include the following content in it:

#  We're running multiple virtual hosts.
NameVirtualHost *

(When Apache starts up it reads the contents of all files included in /etc/apache2/conf.d, and files you create here won’t get trashed on package upgrades.)

Once we’ve done this we can create the individual host configuration files. The Apache2 setup you’ll find on Debian GNU/Linux includes two directories for locating your site configuration files:

This contains configuration files for sites which are available but not necessarily enabled.

This directory contains site files which are enabled.

As with the conf.d directory each configuration file in the sites-enabled directory is loaded when the server starts – whilst the files in sites-available are completely ignored.

You are expected to create your host configuration files in /etc/apache2/sites-available, then create a symbolic link to those files in the sites-enabled directory – this will cause them to be actually loaded/read.

Rather than actually messing around with symbolic links the Debian package includes two utility commands a2ensite and a2dissite which will do the necessary work for you as we will demonstrate shortly.

Lets start with a real example. Create /etc/apache2/sites-available/ with the following contents:

# (/etc/apache2/sites-available/
<VirtualHost *>

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/

        # CGI Directory
        ScriptAlias /cgi-bin/ /home/www/
        <Location /cgi-bin>
                Options +ExecCGI

        # Logfiles
        ErrorLog  /home/www/
        CustomLog /home/www/ combined

Next create the file

# (/etc/apache2/sites-available/
<VirtualHost *>

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/

        # CGI Directory
        ScriptAlias /cgi-bin/ /home/www/
        <Location /cgi-bin>
                Options +ExecCGI

        # Logfiles
        ErrorLog  /home/www/
        CustomLog /home/www/ combined

Finally create the file

# (/etc/apache2/sites-available/
<VirtualHost *>

        # Indexes + Directory Root.
        DirectoryIndex index.html
        DocumentRoot /home/www/

        # CGI Directory
        ScriptAlias /cgi-bin/ /home/www/
        <Location /cgi-bin>
                Options +ExecCGI

        # Logfiles
        ErrorLog  /home/www/
        CustomLog /home/www/ combined

Now we’ve got:

  • Three directories which can be used to contain our content.
  • Three directories which can be used to contain our logfiles.
  • Three directories which can be used to contain our dynamic CGI scripts.
  • Three configuration files which are being ignored by Apache.

To enable the sites simply run:

root@irony:~# a2ensite
Site installed; run /etc/init.d/apache2 reload to enable.

root@irony:~# a2ensite
Site installed; run /etc/init.d/apache2 reload to enable.

root@irony:~# a2ensite
Site installed; run /etc/init.d/apache2 reload to enable.

This will now create the symbolic links so that /etc/apache2/sites-enabled/, etc, now exist and will be read.

Once we’ve finished our setup we can restart, or reload, the webserver as the output above instructed us to do with:

root@irony:~# /etc/init.d/apache2 reload
Reloading web server config...done.


Here i am going to describe how to enable mod_rewrite in apache2.2 -specaily for debian.

In default installion of apache2.2 on debian never enable mod_rewrite default. So you may need to enable .

First install the apache2.2 with this command :
debian user please use “su” before start this process
ubuntu user please use “sudo su” before start this process

apt-get install apache2 (it will install apache 2.2)

on current debian system you can enable mod_rewrite with simple command

a2enmod rewrite

old style, you can skip this portion

now use locate to find if the is availble on your server


it will found in “/usr/lib/apache2/modules”

new apache follow some folders to enable and disable mods.
so now do this:

cd /etc/apache2/mods-enabled
touch rewrite.load
gedit rewrite.load (you may use any editor to edit this file)

now paste this following line

LoadModule rewrite_module /usr/lib/apache2/modules/

end of old style

Then edit /etc/apache2/sites-available/default or /etc/apache2/sites-available/000-default (check which one available on your system)

Find the following

Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all

and change it to

Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order allow,deny
allow from all

and finally restart Apache

/etc/init.d/apache2 restart
service apache2 restart



This short guide shows some important commands for your daily work on the Linux command line.


Outputs the processor architecture.

$ arch



Outputs the contents of a file.

$ cat lorem.txt

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


Change the working directory.

$ cd /bin


Change group ownership of files.

$ chgrp games moo.txt


Change access permissions of files.

$ chmod +x helloworld


Change file owner and group.

# chown root lorem.txt


Print CRC checksum and byte counts of each file.

$ cksum lorem.txt moo.txt

3570240675 453 lorem.txt
4294967295 0 moo.txt


Copies a file.

$ cp lorem.txt copy_of_lorem.txt


Outputs the current date and time.

$ date

Sat Mar  3 12:07:09 GMT 2007


Reports the amount of disk space used and available on filesystems.

$ df

Filesystem           1K-blocks      Used Available Use% Mounted on<br>
/dev/simfs            39845888    218048  39627840   1% /


List directory contents.

$ dir

copy_of_lorem.txt  lorem.txt  moo.txt  www


Estimate file space usage.

$ du -h /bin

7.8M    /bin


Display a line of text.

$ echo foobar



Cause the shell to exit.

$ exit


Print lines matching a pattern in a file.

$ fgrep “irure dolor” lorem.txt

commodo consequat. Duis aute irure dolor in reprehenderit in voluptate


Search for files in a directory hierarchy.

$ find hello*



Display amount of free and used memory in the system.

$ free

total       used       free     shared    buffers     cached
Mem:       8299892    8287708      12184          0    2641772    1731236
Low:       3581300    3572764       8536
High:      4718592    4714944       3648
-/+ buffers/cache:    3914700    4385192
Swap:      8193140    2335664    5857476


Print lines matching a pattern.

$ grep -i apple fruitlist.txt



Outputs the user groups of which your account belongs to.

$ groups

games users


Output the first part of files.

$ head -2 lorem.txt

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim


Outputs the machines hostname on the network.

$ hostname


Outputs user id, group id, and groups of your account.

$ id

uid=1478(smallfoot) gid=100(users) groups=35(games),100(users)


End a process.

$ kill -9 18298

-bash: kill: (18298) – Operation not permitted


Kill processes by name.

$ killall irssi

irssi(18298): Operation not permitted
irssi(13372): Operation not permitted
irssi(22048): Operation not permitted
irssi: no process killed


Show listing of last logged in users.

$ last -n 3

alice    pts/6     Fri May 18 16:17   still logged in
bob      pts/2   Fri May 18 16:17   still logged in
clare    pts/6      Fri May 18 15:54 – 15:55  (00:01)


Print shared library dependencies.

$ ldd /bin/bash => /lib/ (0x40023000) => /lib/ (0x40065000) => /lib/ (0x40069000)
/lib/ (0x40000000)


Make links between files.

$ ln -s data.txt symlink.txt


Print user’s login name.

$ logname



List directory contents.

$ ls

copy_of_lorem.txt  lorem.txt  moo.txt  www


Opens the manual page for a software or function.

$ man bash


Outputs the MD5 hash sum of a file.

$ md5sum lorem.txt

56da9e37259af34345895883e6fd1a27  lorem.txt


Makes a directory.

$ mkdir foobar


Moves a file.

$ mv lorem.txt ipsum.txt


Number lines of files.

$ nl lorem.txt

1  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
2  tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
3  veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
4  commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
5  velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
6  occaecat cupidatat non proident, sunt in culpa qui officia deserunt
7  mollit anim id est laborum.


List symbols from object files.

$ nm hello_world

080494a0 D _DYNAMIC
08048474 R _IO_stdin_used
w _Jv_RegisterClasses
08049490 d __CTOR_END__
0804948c d __CTOR_LIST__
08049498 d __DTOR_END__


Dump files in octal and other formats.

$ od -t x /bin/sh

2376640 00098020 000054d4 00000000 00000000
2376660 00000020 00000000 000000c7 00000008
2376700 00000003 080e6500 0009d4f4 00004ae8


Find the process ID of a running program.

$ pidof fetchmail



Pings a host.

$ ping -c 2

PING ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=64 time=0.048 ms
64 bytes from icmp_seq=2 ttl=64 time=0.052 ms

— ping statistics —
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.048/0.050/0.052/0.002 ms


Outputs running processes.

$ ps

21542 pts/12   00:00:00 bash
27706 pts/12   00:00:00 ps


Display a tree of processes.

$ pstree

|        `-bash—ctorrent
|        |-bash—vi
|        |-2*[bash]
|        `-bash—lynx
|        `-irssi
|      |-8*[sshd—sshd—bash]
|      |-sshd—sshd—bash—screen
|      |-sshd—sshd
|      `-sshd—sshd—bash—pstree


Outputs the name of current working directory.

$ pwd



Removes a file or directory.

$ rm lorem.txt


Removes a directory.

$ rmdir foobar


Stream editor for filtering and transforming text.

$ echo “My cat’s name is Bob” | sed -e ‘s/Bob/Mittens/g’

My cat’s name is Mittens


Outputs the SHA1 hash sum of a file.

$ sha1sum lorem.txt

c942ddebd142ec8bacac9213d48096e74bab4957  lorem.txt


Bring the system down in a secure way. All logged-in users are notified that the system is going down.

$ shutdown now


List section sizes and total size.

$ size /bin/bash

text    data     bss     dec     hex filename
621233   22712   19176  663121   a1e51 /bin/bash


Outputs file status.

$ stat lorem.txt

File: `lorem.txt’
Size: 453             Blocks: 8          IO Block: 4096   regular file
Device: 77h/119d        Inode: 27312217    Links: 1
Access: (0644/-rw-r–r–)  Uid: ( 1478/smallfoot)   Gid: (  100/   users)
Access: 2007-03-03 12:24:39.000000000 +0000
Modify: 2007-03-03 12:24:39.000000000 +0000
Change: 2007-03-03 12:24:39.000000000 +0000


Print the strings of printable characters in files.

$ strings hello_world

Hello World!


Output the last part of files.

$ tail -2 lorem.txt

occaecat cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.


Talk to another user.

$ talk bob Lookout for the dopefish!


Change a file’s access and modification timestamps. If file does not exist, create it.

$ touch lorem.txt


Outputs the name of the current terminal.

$ tty



Outputs operating system, hostname, kernel version, date and timp, and processor.

$ uname -a

Linux 2.6.9 #1 SMP Wed Jul 19 16:24:18 MSD 2006 i686 Intel(R) Xeon(TM) CPU 2.80GHz GenuineIntel GNU/Linux


Outputs the system uptime.

$ uptime

14:50:26 up 7 days, 17:52, 18 users,  load average: 0.08, 0.02, 0.01


Print the user names of users currently logged in to the current host.

$ users

alice bob charlie eve


List directory contents.

$ vdir

total 8
-rw-r–r– 1 smallfoot users 453 Mar  3 12:32 copy_of_lorem.txt
-rw-r–r– 1 smallfoot users 453 Mar  3 12:24 lorem.txt
-rw-r–r– 1 smallfoot users   0 Mar  3 12:32 moo.txt
lrwxr-xr-x 1 root      root   18 Feb 27 19:33 www -> /var/www/smallfoot


Show who is logged on and what they are doing.

$ w

12:14:30 up 5 days, 15:16, 19 users,  load average: 0.00, 0.00, 0.00
charlie  pts/0     Fri21    3:26m  2.52s  2.52s irssi
alice    pts/2     Wed17   30:21m  0.00s  0.00s -bash
emma     pts/4     11:37   36:57   0.00s  0.00s -bash
frank    pts/5     11:48   11:03   0.00s  0.00s -bash
smallfoo pts/12    12:01    0.00s  0.04s  0.01s w


Send a message to everybody’s terminal.

$ wall next week we change the server for a new one


Counts lines in a file.

$ wc -l lorem.txt

7 lorem.txt


Search the whatis database for complete words.

$ whatis bash

bash                 (1)  – GNU Bourne-Again SHell
bash [builtins]      (1)  – bash built-in commands, see bash(1)


Outputs who is currently logged into the system.

$ who

charlie  pts/0        Mar  2 21:37 (
alice    pts/2        Feb 28 17:48 (
emma     pts/4        Mar  3 11:37 (
frank    pts/5        Mar  3 11:48 (
smallfoot pts/12       Mar  3 12:01 (


Locate the binary, source, and manual page files for a command.

$ whereis bash

bash: /bin/bash /etc/bash /usr/share/man/man1/bash.1.gz


Outputs your username / the name of your account.

$ whoami