Rail Frame work

0 comments

A framework is a program, set of programs, and/or code library that writes most of your application for you. When you use a framework, your job is to write the parts of the application that make it do the specific things you want.

When you set out to write a Rails application, leaving aside configuration and other housekeeping chores you have to perform three primary tasks:

  • Describe and model your application's domain: The domain is the universe of your application. The domain may be music store, university, dating service, address book, or hardware inventory. So here you to figure out what's in it, what entities exist in this universe and how the items in it relate to each other. This is equivalent to modeling database structure to keep the entities and their relationship.

  • Specify what can happen in this domain: The domain model is static, Now you have to get dynamic. Addresses can be added to an address book. Musical scores can be purchased from music stores. Users can log in to a dating service. Students can register for classes at a university. You need to identify all the possible scenarios or actions that the elements of your domain can participate in.

  • Choose and design the publicly available views of the domain: At this point, you can start thinking in Web-browser terms. Once you've decided that your domain has students, and that they can register for classes, you can envision a welcome page, a registration page, and a confirmation page etc.Each of these pages, or views, shows the user how things stand at certain point.

Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC) framework.

Ruby on Rails MVC framework:

The Model View Controller principle divides the work of an application into three separate but closely cooperative subsystems.

Model (ActiveRecord ) :

Maintains the relationship between Object and Database and handles validation, association, transactions, and more.

This subsystem is implemented in ActiveRecord library which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables, and so on.

View ( ActionView )

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.

This subsystem is implemented in ActionView library which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.

Controller ( ActionController ):

The facility within the application that directs traffic, on the one hand querying the models for specific data, and on the other hand organizing that data (searching, sorting, massaging it) into a form that fits the needs of a given view.

This subsystem is implemented in ActionController which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).

Pictorial Representation of MVC Framework:

A Pictorial Diagram of Ruby on Rails Framework is given here:

Rails Framework

Directory Representation of MVC Framework:

Assuming a standard, default installation over Linux, you can find them like this:

tp> cd /usr/local/lib/ruby/gems/1.8/gems
tp> ls

You will see subdirectories including (but not limited to) the following:

  • actionpack-x.y.z
  • activerecord-x.y.z
  • rails-x.y.z

Over a windows installation you can find them link this:

C:\>cd ruby\lib\ruby\gems\1.8\gems
C:\ruby\lib\ruby\gems\1.8\gems\>dir

You will see subdirectories including (but not limited to) the following:

  • actionpack-x.y.z
  • activerecord-x.y.z
  • rails-x.y.z

ActionView and ActionController are bundled together under ActionPack.

ActiveRecord provides a range of programming techniques and shortcuts for manipulating data from an SQL database. ActionController and ActionView provide facilities for manipulating and displaying that data. Rails ties it all together.

Ruby on Rails Directory Structure


When you use the rails helper script to create your application, it creates the entire directory structure for the application. Rails knows where to find things it needs within this structure, so you don't have to tell it.

Here is a top level view of directory tree created by helper script at the time of application creation. Except for minor changes between releases, every Rails project will have the same structure, with the same naming conventions. This consistency gives you a tremendous advantage; you can quickly move between Rails projects without relearning the project's organization.

To understand this directory structure let's use demo application created in installation chapter. This can be created using a simple helper command C:\ruby\> rails demo.

Now go into demo application root directory as follows:

C:\ruby\> cd demo
C:\ruby\demo> dir

You will find a directory structure as follows:

demo/
..../app
......../controller
......../helpers
......../models
......../views
............../layouts
..../components
..../config
..../db
..../doc
..../lib
..../log
..../public
..../script
..../test
..../tmp
..../vendor
README
Rakefile

Now let's explain the purpose of each directory

  • app : This organizes your application components. It's got subdirectories that hold the view (views and helpers), controller (controllers), and the backend business logic (models).

  • app/controllers: The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user.

  • app/helpers: The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

  • app/models: The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple!

  • app/view: The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

  • app/view/layouts: Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.rhtml. Inside default.rhtml, call <% yield %> to render the view using this layout.

  • components : This directory holds components tiny self-contained applications that bundle model, view, and controller.

  • config: This directory contains the small amount of configuration code that your application will need, including your database configuration (in database.yml), your Rails environment structure (environment.rb), and routing of incoming web requests (routes.rb). You can also tailor the behavior of the three Rails environments for test, development, and deployment with files found in the environments directory.

  • db: Usually, your Rails application will have model objects that access relational database tables. You can manage the relational database with scripts you create and place in this directory.

  • doc: Ruby has a framework, called RubyDoc, that can automatically generate documentation for code you create. You can assist RubyDoc with comments in your code. This directory holds all theR ubyDoc-generated Rails and application documentation.

  • lib: You'll put libraries here, unless they explicitly belong elsewhere (such as vendor libraries).

  • log: Error logs go here. Rails creates scripts that help you manage various error logs. You'll find separate logs for the server (server.log) and each Rails environment (development.log, test.log, and production.log).

  • public: Like the public directory for a web server, this directory has web files that don't change, such a s JavaScript files (public/javascripts), graphics (public/images), stylesheets (public/stylesheets), and HTML files (public).

  • script: This directory holds scripts to launch and manage the various tools that you'll use with Rails. For example, there are scripts to generate code (generate) and launch the web server (server).

  • test: The tests you write and those Rails creates for you all go here. You'll see a subdirectory for mocks (mocks), unit tests (unit), fixtures (fixtures), and functional tests (functional).

  • tmp: Rails uses this directory to hold temporary files for intermediate processing.

  • vendor: Libraries provided by third-party vendors (such as security libraries or database utilities beyond the basic Rails distribution) go here.

Apart from these directories there will be two files available in demo directory.

  • README: This file contains a basic detail about Rail Application and description of the directory structure explained above.

  • Rakefile: This file is similar to Unix Makefile which helps with building, packaging and testing the Rails code. This will be used by rake utility supplied along with Ruby installation.


Ruby on Rails Examples


Subsequent chapters are based on the example given in this chapter. In this example we will create something simple but operational online library system for holding and managing the books.

Now you have to be patient till you go through next few chapters. I'm sure after completing this tutorial you will have complete understanding on Rails.

This application has a basic architecture and will be built using two ActiveRecord models to describe the types of data that is stored:

  • Books, which describes an actual listing.

  • Subject, which is used to group books together.

Workflow for creating Rails applications:

A recommended workflow for creating Rails Application is as follows:

  • Use the rails command to create the basic skeleton of the application.

  • Create a database on the MySQL server to hold your data.

  • Configure the application to know where your database is located and the login credentials for it.

  • Create Rails Active Records ( Models ) because they are the business objects you'll be working with in your controllers.

  • Generate Migrations that makes creating and maintaining database tables and columns easy.

  • Write Controller Code to put a life in your application.

  • Create Views to present your data through User Interface.

So lets start with creating our library application.

Creating an Empty Rails Web Application:

Rails is both a runtime web application framework and a set of helper scripts that automate many of the things you do when developing a web application. In this step, we will use one such helper script to create the entire directory structure and the initial set of files to start our Library System application.

  1. Go into ruby installation directory to create your application.
  2. Run the following command to create a skeleton for library application.
C:\ruby> rails library

This will create a subdirectory for the library application containing a complete directory tree of folders and files for an empty Rails application. Check a complete directory structure of the application. Check Rails Directory Structure for more detail.

Most of our development work will be creating and editing files in the library/app subdirectories. Here's a quick rundown of how to use them:

  • The controllers subdirectory is where Rails looks to find controller classes. A controller handles a web request from the user.

  • The views subdirectory holds the display templates to fill in with data from our application, convert to HTML, and return to the user's browser.

  • The models subdirectory holds the classes that model and wrap the data stored in our application's database. In most frameworks, this part of the application can grow pretty messy, tedious, verbose, and error-prone. Rails makes it dead simple.

  • The helpers subdirectory holds any helper classes used to assist the model, view, and controller classes. This helps to keep the model, view, and controller code small, focused, and uncluttered.

Starting Web Server:

Rails web application can run under virtually any web server, but the most convenient way to develop a Rails web application is to use the built-in WEBrick web server. Let's start this web server and then browse to our empty library application:

This server will be started from the application directory as follows. This runs on port number 3000.

C:\> cd ruby\library 
C:\ruby\library\> ruby script/server

This will start your WEBrick web server.

Now open your browser and browse to http://127.0.0.1:3000. If everything is gone fine then you should see a greeting message from WEBrick otherwise there is something wrong with your setting.

What is next ?

Next session will teach you how to create databases for your application and what is the configuration required to access these created databases.

Further we will see what is Rail Migration and how it is used to maintain database tables.



php 5 Features

0 comments




Features of php 5



1. Robust Support for Object-Oriented Programming

Ever since Zeev and Andi's late-night OOP hack, PHP programmers have clamored for an increasing amount of OO features. However, neither PHP 3 nor PHP 4 truly incorporates objects into its core.

With PHP 5, PHP programmers can at last stop apologizing for PHP's krufty OO support. It offers:

  • Constructors
  • Destructors
  • Public, protected, and private properties and methods
  • Interfaces
  • Abstract classes
  • Class type hints
  • Static properties and methods
  • Final properties and methods
  • A whole suite of magical methods

Additionally, objects are now both assigned--and passed--by reference instead of by value, so the necessity to liberally sprinkle ampersands throughout your code is no more.

If you're a person who enjoys web programming using objects and patterns, then these features alone will make your year. However, PHP 5's just getting started.

2. A Completely Rewritten MySQL Extension

The MySQL database is PHP's partner in crime. Many developers power their web sites with MySQL, yet the MySQL extension is showing its age. In retrospect, some design decisions weren't the best solutions after all.

Also, the latest versions of MySQL, 4.1 and 5.0, introduce many new features, some of which require significant changes to the extension. As a result, PHP 5 comes with a completely new and improved MySQL extension. Dubbed MySQLi, for MySQL Improved. It offers:

  • Prepared statements
  • Bound input and output parameters
  • SSL connections
  • Multi-query functions

MySQLi even takes advantage of PHP 5's new object-oriented support to provide an OO interface to MySQL. On top of that, the latest versions of MySQL now enable subselects, transactions, and replication.

3. A Suite of Interoperable XML Tools

PHP 5 fixes the major problems in PHP 4's XML extensions. While PHP 4 allows you to manipulate XML, its XML tools are only superficially related. Each tool covers one part of the XML experience, but they weren't designed to work together, and PHP 4 support for the more advanced XML features is often patchy.

Not so in PHP 5.

The new XML extensions:

  • Work together as a unified whole.
  • Are standardized on a single XML library: libxml2.
  • Fully comply with W3 specifications.
  • Efficiently process data.
  • Provide you with the right XML tool for your job.

Additionally, following the PHP tenet that creating web applications should be easy, there's a new XML extension that makes it simple to read and alter XML documents. The aptly named SimpleXML extension allows you to interact with the information in an XML document as though these pieces of information are arrays and objects, iterating through them with for-each loops, and editing them in place merely by assigning new values to variables.

In short, SimpleXML kicks ass!

If you know the document's format ahead of time, such as when you're parsing RSS files, REST results, and configuration data, SimpleXML is the way to go.

And if you're a DOM fan, you'll be pleasantly surprised with PHP 5's DOM extension, which is light-years beyond what you're using in PHP 4.

4. An Embedded Database with SQLite

While MySQL is greater than ever, it's actually "too much database" for some jobs. SQLite is an embedded database library that lets you store and query data using an SQL interface without the overhead of installing and running a separate database application.

When your application needs a server-side storage mechanism but you can't rely upon the presence of a specific database, turn to SQLite. It correctly handles locking and concurrent accesses, the two big headaches with homebrewed flat files.

PHP 5 bundles SQLite, providing developers with a database that's guaranteed to work on all PHP 5 installations. Despite the name, SQLite is nowhere close to a "lite" database. It supports:

  • Transactions
  • Subqueries
  • Triggers
  • And many other advanced database features

You can even write user-defined functions in PHP and call them from within SQLite. This is by far and away the coolest feature available in any PHP database extension.

5. Cleaner Error Handling with Exceptions

PHP 5 offers a completely different model of error checking than what's available in PHP 4. It's called exception handling. With exceptions, you're freed from the necessity of checking the return value of every function. Instead, you can separate programming logic from error handling and place them in adjoining blocks of code.

Exceptions are commonly found in object-oriented languages such as Java and C++. When used judiciously, they streamline code, but when used willy-nilly, they create spaghetti code.

Right now, only a few PHP extensions use exceptions, but they're slowly being phased in. However, they're available today for any PHP code you write.

6. A First-Class SOAP Implementation

SOAP is a key component of the fast-growing web services field. This extension lets developers create SOAP clients with or without a Web Services Description Language (WSDL) file, and also implement SOAP servers in PHP.

PHP 4's SOAP support is only fair. While there are a few SOAP packages, the most mature ones are written in PHP instead of C. Therefore, they are slow, and you have to download and install them yourself.

With PHP 5, there's finally a usable SOAP extension written in C. Currently, this extension implements most, but not all, of SOAP 1.2. This is a significant improvement over previous C extension, and future pieces will be added in time.

Particularly in comparison with .NET and Java, PHP's SOAP support has always lagged behind the curve. Whether you love or hate SOAP, PHP needs to offer a first-class SOAP extension, and I'm excited to finally see some momentum in this direction.

7. Iterators

Iterators are a completely new PHP 5 feature. They allow you to use a for-each loop to cycle through different types of data: directory listings, database results, and even XML documents. SPL -- Standard PHP Library -- is a collection of iterators that provide this functionality and also filter, limit, cache, and otherwise modify iterator results.

Iterators are an incredibly handy way to abstract away messy details from your code.

For example, the DirectoryIterator turns directory iteration from this:


$dir = opendir($path);
while (false !== ($file = readdir($dir))) {
print "$file\n";
}
closedir($dir);

Into this:


foreach (new DirectoryIterator($path) as $file) {
print "$file\n";
}

There are no directory handles to mess about with, nor ugly conditions to check inside a while loop.

These are my top seven favorite features of PHP 5, but they're by no means the only ones. Besides what I've already highlighted, PHP 5 also offers:

  • Enhanced streams, wrappers, and filters.

    First introduced in PHP 4.3, streams are an underutilized part of PHP. They allow you to place a file interface on reading and writing data using protocol-specific objects known as wrappers. Streams also let you modify the data flowing through them by attaching filters.

  • Code introspection using the Reflection classes.

    This set of classes lets you examine classes, methods, parameters, and more, to discover object attributes. It is now simple and easy to create PHP class browsers, debuggers, and other tools that rely on gathering details about objects and functions.

  • Compliant HTML output thanks to Tidy.

    The Tidy extension makes it easy to ensure that your output is valid HTML and XHTML. Its smart parser brings even the most unruly of files into compliance with the latest W3C specifications.

  • Superior command-line processing.

    The PHP5 command-line version now allows individual line processing, similar to Perl and awk. You can specify code to be run at the beginning, on, and at the end of each line in a file.

MySQL Downloads

0 comments


MySQL Downloads

MySQL Community Server

MySQL 5.1—Generally Available (GA) release for production use

Beta Releases

MySQL 5.4—Beta

Upcoming Releases

Snapshots — source code snapshots of the development trees
Glassfish+MySQL bundle — developers edition

Older Releases

MySQL 5.0 — Previous GA release
MySQL 4.1 — Previous GA release
Archives of Older Releases


MySQL Cluster

MySQL Cluster is the world's most popular carrier grade database due to its high performance, high availability, scalability and ease of integration with existing systems and tools. MySQL Cluster has a low TCO due to its support for open standards, COTs hardware and low licensing costs.

MySQL Workbench

MySQL Workbench is a next-generation visual database design application that can be used to efficiently design, manage and document database schemata.

MySQL Tools

MySQL also develops Graphical User Interface applications for administering MySQL Server and working with data.

  • MySQL GUI Tools — single bundle including all GUI tools (MySQL Administrator, MySQL QueryBrowser and MySQL MigrationToolkit)

MySQL Proxy

MySQL Proxy is a simple program that sits between your client and MySQL server(s) that can monitor, analyze or transform their communication. Its flexibility allows for unlimited uses; common ones include: load balancing; failover; query analysis; query filtering and modification; and many more.

Drivers and Connectors

Note: Connector version numbers do not correlate with MySQL Server version numbers.

While many programming languages have included support for connecting to MySQL server, additional drivers are available:

MySQL Connector/J — for connecting to MySQL from Java

MySQL Connector/Net — for connecting to MySQL from .NET

Connector/ODBC - MySQL ODBC driver

MySQL Connector/MXJ — for embedding MySQL server in Java applications

MySQL Connector/C++ — for connecting to MySQL from C++

MySQL Connector/C (libmysql) — A client library for C development

mysqlnd

Contributed APIs

  • DBI — for connecting to MySQL from Perl
  • Ruby — for connecting to MySQL from Ruby
  • Python — for connecting to MySQL from Python
  • .NET — for connecting to MySQL from .NET
  • MySQL++ — for connecting to MySQL from C++
  • Ch — for connecting to MySQL from Ch (C/C++ interpreter)

Configurring PHP Web Development Platform

0 comments

Wamp Server 2.0

WampServer is a Windows web development environment. It allows you to create web applications with Apache, PHP and the MySQL database. It also comes with PHPMyAdmin to easily manage your databases.

WampServer installs automatically (installer), and its usage is very intuitive. You will be able to tune your server without even touching the setting files.

WampServer is the only packaged solution that will allow you to reproduce your production server. Once WampServer is installed, you have the possibility to add as many Apache, MySQL and PHP releases as you want.


Download Wamp 2.0

Installing 'wamp'


Double click on the downloaded file and just follow the instructions. Everything is automatic. The WampServer package is delivered whith the latest releases of Apache, MySQL and PHP.

Once WampServer is installed, you can add other releases by downloading them on this website. They will then appear in the WampServer menu and you will be able to switch releases with a simple click.
Each release of Apache, MySQL and PHP has its own settings and its own files (datas for MySQL).





Building a LAMP Server



Installing LAMP on Debian



  • Apache 2 - Linux Web server
  • MySQL 5 - MySQL Database Server
  • PHP4/5 - PHP Scripting Language
  • phpMyAdmin - Web-based database admin software.

Note: Linux + Apache + MySQL + PHP/Perl together commonly known as LAMP Server.

First, let us prepare a system that has a minimum requirement of Debian/Ubuntu version of linux with atleast 256MB of RAM available. Anything less than this minimum ram will cause lot of problems since we are running a server along especially mysql and webmin requires lot of RAM to run properly. Mysql will give you this nasty error "cannot connect to mysql.sock" if you dont have enough memory in your server.

I love debian/ubuntu based linux because of my enormous affinity towards this command apt-get. As a starter knowing this one command, It is so easy to install packages and you dont need to worry about package dependency and configuration. You need to buy a dedicated server or a VPS package if you want to setup your own server. If you want to experiment with the server and installation it is recommended to buy a vps package from various hosts. I prefer vpslink because of their pricing. Believe it or not it is so easy to install and configure your server yourself eventhough you are new are to linux and dedicated/vps hosting.

First download PuTTy if you are accessing your server through SSH. Just enter the IP of your server with root login to access your host. As you probably know, Webmin is a freely available server control panel and we will setup this once we have completed the LAMP server and Mail Server. Webmin makes more easier for us to fine tune our linux box.

Before proceeding to install, update the necessary packages with debian with this command.

apt-get install update

1. Installing Apache + PHP

Apache is one of the most famous web server which runs on most linux based servers. With just few commands you can configure apache to run with PHP 4 or PHP 5.

If you want to install PHP 4, just apt-get

apt-get install apache2 php4 libapache2-mod-php4

To install PHP5, just run the following on linux shell. Note that if you dont specify packages with '4', PHP5 will be automatically installed.

apt-get install apache2 php5 libapache2-mod-php5

Apache configuration file is located at: /etc/apache2/apache2.conf and your web folder is /var/www.

To check whether php is installed and running properly, just create a test.php in your /var/www folder with phpinfo() function exactly as shown below.

nano /var/www/test.php

# test.php

Point your browser to http://ip.address/test.php or http://domain/test.php and this should show all your php configuration and default settings.

You can edit necessary values or setup virtual domains using apache configuration file.

2. Installing MySQL Database Server

Installing mysql database server is always necessary if you are running a database driven ecommerce site. Remember running mysql server to a fair extend requires atleast 256mb of RAM in your server. So unless you are running database driven sites you dont absolutely need mysql. The following commands will install mysql 5 server and mysql 5 client.


apt-get install mysql-server mysql-client php5-mysql

Note: If you have already installed php4, you should make a slight change like this.

apt-get install mysql-server mysql-client php4-mysql

The configuration file of mysql is located at: /etc/mysql/my.cnf

Creating users to use MySQL and Changing Root Password

By default mysql creates user as root and runs with no passport. You might need to change the root password.

To change Root Password

mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET Password=PASSWORD('new-password') WHERE user='root';
mysql> FLUSH PRIVILEGES;

You must never use root password, so you might need to create a user to connect to mysql database for a PHP script. Alternatively you can add users to mysql database by using a control panel like webmin or phpMyAdmin to easily create or assign database permission to users. We will install Webmin and phpmyadmin during later once we complete basic installation.

3. PhpMyAdmin Installation

PhpMyAdmin is a nice web based database management and administration software and easy to install and configure under apache. Managing databases with tables couldnt be much simpler by using phpmyadmin.

All you need to do is:

apt-get install phpmyadmin

The phpmyadmin configuration file is located at: /etc/phpmyadmin folder.

To set up under Apache all you need to do is include the following line in /etc/apache2/apache2.conf:

Include /etc/phpmyadmin/apache.conf 

Now restart Apache:

/etc/init.d/apache2 restart

Point your browser to: http://domain/phpmyadmin

That's it! MySQL and phpMyAdmin are ready. Log in with your mysql root password and create users to connect to database from your php script.

This tutorial was written and contributed to HowToForge by Scott who currently runs MySQL-Apache-PHP.com. Permission is fully granted to copy/republish this tutorial in any form, provided a source is mentioned with a live link back to the authors site.



LAMP On Red Hat

Linux, Apache web server, MySQL database and PHP scripting (LAMP) is very popular platform for web solutions. This tutorial shows how to install and configure Apache web server, MySQL database and scripting language. Linux, Apache, MySQL, PHP (LAMP) is very popular platform for web solutions. LAMP is Free, stable, easy to learn and well documented.

Apache Web Server

To install servers, you first have to become root with su -. Install the actual web server program

yum install httpd

If you don't have yum, you can use rpm -i httpd*.i386.rpm or apt-get install httpd.

Start web server, make it start automatically on boot

/etc/init.d/httpd start
chkconfig httpd on

Now your web server should be running. When you surf to http://localhost, you should see a test page.

mozilla http://localhost

Localhost usually works even without hole in the firewall. If you do not see your test page right away, click shift-reload (ctrl-shift-R or shift-F5) to bypass cache.

Hide the testpage, so that your computer does not look like a punching bag for wannabe crackers

echo "go away" > /var/www/html/index.html

Make a hole into firewall to make your web server visible to others.

iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT
iptables-save > /etc/sysconfig/iptables

Check your ip number (it's not 127.0.0.1)

/sbin/ifconfig/

and surf to that address, for example http://10.0.0.1. If you see your test page, congratulations, you just installed your web server!

Other servers in Linux are installed just like above: install the program, start it and make it start automatically, and make a hole in the firewall.

User homepages

Web server content directory /var/www/html/ is not writable by normal users, and you don't want to edit web pages as root. That's why users create homepages in /home/foo/public_html. Homepages are shown in http://localhost/~foo

Allow users to create homepages

Edit web server configuration with your favourite text editor. If you don't have pico, you can install it yum install pine

pico /etc/httpd/conf/httpd.conf

Find the section about homepages by searching ctrl-W for public_html, then comment out the line with UserDir disable and remove the comment char "#" from the line UserDir public_html.

Activate your changes by restarting the web server.

/etc/init.d/httpd restart

Your users can now create homepages.

Create a homepage as a user

If you are still root (if you have a # in your prompt), exit.

Create a directory for homepages. Home directory, public_html and all directories under public_html must be executable (x) by all, so that web server can access files under them if it knows their name. Files must be readable by the web server.

cd $HOME
mkdir public_html
echo "my homepage" > public_html/index.html
chmod a+x $HOME $HOME/public_html
chmod a+r $HOME/public_html/index.html

If you have a lot of users (10+), automate this by putting public_html and index.html to /etc/skel and check default home dir permissions.

Browse to your home page. If your name is "user", it is located in http://localhost/~user. If you can see "my homepage", you are now a happy owner of a homepage.

PHP scripting

PHP is a powerfull scripting language with a C++ like syntax, many readymade classes, good examples and great documentation.

Install PHP scripting

yum install php

Because php is a module, you must restart a web server to load it.

/etc/init.d/httpd restart

Hello PHP World

As a normal user, write a sample php page

cd $HOME/public_html
pico hello.php

Write this sample code to hello.php


Text outside code block is printed normally to web page.

Usually there is a normal html web page outside the .

Browse to http://localhost/~user/hello.php. Put your own login name instead of user. If you see "Hello PHP World, 2+2 is 4", you have installed php and written your first program.

MySQL database

Install mysqld just like any server, but don't make a hole for it in the firewall. It is only used locally by Apache.

yum install mysql-server mysql /etc/init.d/mysqld start chkconfig mysqld on

Try your new SQL server

mysqlshow

+-----------+
| Databases |
+-----------+
| mysql |
| test |
+-----------+

Two databases. mysql contains database management system internal data, so don't edit it. test is a safe sandbox to play with.

mysqlshow test

Database: test
+--------+
| Tables |
+--------+
+--------+

If for some reason you do not have database test, create it CREATE DATABASE test; and then USE test;

No tables in database test yet. Let's CREATE some.

mysql

On the prompt mysql>, you can type mysql commands (USE, SHOW) or sql queries (CREATE, INSERT, SELECT).

USE test;
SHOW tables;
CREATE TABLE persons( name VARCHAR(50), email VARCHAR(50) ); SHOW tables;
DESC persons;
INSERT INTO persons VALUES('Tero Karvinen', 'karvinen iki.fi');
SELECT * FROM persons;
INSERT INTO persons VALUES('Sample Person', 'recycle@nosuch.invalid');
SELECT * FROM persons;
QUIT

After the two INSERTs, the last SELECT should return a table with two records

+---------------+---------------------------+
| name | email |
+---------------+---------------------------+
| Tero Karvinen | karvinen iki.fi |
| Sample Person | recycle@nosuch.invalid |
+---------------+---------------------------+
2 rows in set (0.01 sec)

You have now installed a database management system, and you also know some SQL.

PHP program using MySQL database

A database by itself is not very usefull - it needs a user interface. To create a web interface to database, we use PHP scripting language.

yum install php-mysql
/etc/init.d/httpd restart

Let's write a simple program to display our database. Use pico $HOME/public_html/mysql.php to copy this script to a file


PHP database example - http://iki.fi/karvinen.

iki.fi, adapted from php.net
* See http://iki.fi/karvinen Linux Apache MySQL PHP tutorial. */

/* Connect to database */
$link = mysql_connect("localhost", "root", "")
or die("Could not connect : " . mysql_error());
print "Connected successfully";
mysql_select_db("test") or die("Could not select database");

/* Perform SQL query */
$query = "SELECT * FROM persons";
$result = mysql_query($query)
or die("Query failed : " . mysql_error());

/* Print results in HTML */
print "
\n";
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
print "\t\n";
foreach ($line as $col_value) {
print "\t\t\n";
}
print "\t\n";
}
print "
$col_value
\n";
mysql_free_result($result);

/* Close connection */
mysql_close($link);
?>

Browse to http://localhost/~user/database.php. Use your own login name instead of user

CSS How To

0 comments

Examples

How to Insert a Style Sheet

When a browser reads a style sheet, it will format the document according to it. There are three ways of inserting a style sheet:

External Style Sheet

An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the link tag. The link tag goes inside the head section:



The browser will read the style definitions from the file mystyle.css, and format the document according to it.

An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below:

hr {color:sienna}
p {margin-left:20px}
body {background-image:url("images/back40.gif")}

Remark Do not leave spaces between the property value and the units! "margin-left:20 px" (instead of "margin-left:20px") will only work in IE6, but it will not work in Firefox or Opera.

Internal Style Sheet

An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section by using the

The browser will now read the style definitions, and format the document according to it.

Note: A browser normally ignores unknown tags. This means that an old browser that does not support styles, will ignore the

Inline Styles

An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly, such as when a style is to be applied to a single occurrence of an element.

To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph:

This is a paragraph.


Multiple Style Sheets

If some properties have been set for the same selector in different style sheets, the values will be inherited from the more specific style sheet.

For example, an external style sheet has these properties for the h3 selector:

h3
{
color:red;
text-align:left;
font-size:8pt
}

And an internal style sheet has these properties for the h3 selector:

h3
{
text-align:right;
font-size:20pt
}

If the page with the internal style sheet also links to the external style sheet the properties for h3 will be:

color:red;
text-align:right;
font-size:20pt

The color is inherited from the external style sheet and the text-alignment and the font-size is replaced by the internal style sheet.

CSS Syntax

1 comments

Syntax

The CSS syntax is made up of three parts: a selector, a property and a value:

selector {property:value}


The selector is normally the HTML element/tag you wish to define, the property is the attribute you wish to change, and each property can take a value. The property and value are separated by a colon, and surrounded by curly braces:

body {color:black}


Note: If the value is multiple words, put quotes around the value:

p {font-family:"sans serif"}


Note: If you want to specify more than one property, you must separate each property with a semicolon. The example below shows how to define a center aligned paragraph, with a red text color:
p {text-align:center;color:red}


To make the style definitions more readable, you can describe one property on each line, like this:

p
{
text-align:center;
color:black;
font-family:arial
}

Grouping

You can group selectors. Separate each selector with a comma. In the example below we have grouped all the header elements. All header elements will be displayed in green text color:


h1,h2,h3,h4,h5,h6
{
color:green
}


The class Selector

With the class selector you can define different styles for the same type of HTML element.

Say that you would like to have two types of paragraphs in your document: one right-aligned paragraph, and one center-aligned paragraph. Here is how you can do it with styles:


p.right {text-align:right}
p.center {text-align:center}


You have to use the class attribute in your HTML document:

This paragraph will be right-aligned.


This paragraph will be center-aligned.



Note: To apply more than one class per given element, the syntax is:

This is a paragraph.



The paragraph above will be styled by the class "center" AND the class "bold".

You can also omit the tag name in the selector to define a style that will be used by all HTML elements that have a certain class. In the example below, all HTML elements with class="center" will be center-aligned:
.center {text-align:center}

In the code below both the h1 element and the p element have class="center". This means that both elements will follow the rules in the ".center" selector:

This heading will be center-aligned


This paragraph will also be center-aligned.



Remark Do NOT start a class name with a number! It will not work in Mozilla/Firefox.
Add Styles to Elements with Particular Attributes

You can also apply styles to HTML elements with particular attributes.

The style rule below will match all input elements that have a type attribute with a value of "text":
input[type="text"] {background-color:blue}

The id Selector

You can also define styles for HTML elements with the id selector. The id selector is defined as a #.

The style rule below will match the element that has an id attribute with a value of "green":
#green {color:green}

The style rule below will match the p element that has an id with a value of "para1":
p#para1
{
text-align:center;
color:red
}

Remark Do NOT start an ID name with a number! It will not work in Mozilla/Firefox.
CSS Comments

Comments are used to explain your code, and may help you when you edit the source code at a later date. A comment will be ignored by browsers. A CSS comment begins with "/*", and ends with "*/", like this:
/*This is a comment*/
p
{
text-align:center;
/*This is another comment*/
color:black;
font-family:arial
}

CSS Introduction

0 comments

What you should already know?

Before you continue you should have a basic understanding of the following:

* HTML / XHTML

If you want to study these subjects first, find the tutorials on our Home page.

What is CSS?

* CSS stands for Cascading Style Sheets
* Styles define how to display HTML elements
* Styles are normally stored in Style Sheets
* Styles were added to HTML 4.0 to solve a problem
* External Style Sheets can save a lot of work
* External Style Sheets are stored in CSS files
* Multiple style definitions will cascade into one

CSS demo

An HTML document can be displayed with different styles: See how it works.


Multiple styles will cascade into one

Style sheets allow style information to be specified in many ways.

Styles can be specified:

* inside an HTML element
* inside the head section of an HTML page
* in an external CSS file

Tip: Even multiple external style sheets can be referenced inside a single HTML document.
Cascading order - What style will be used when there is more than one style specified for an HTML element?

Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:

1. Browser default
2. External style sheet
3. Internal style sheet (in the head section)
4. Inline style (inside an HTML element)

So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the tag, or in an external style sheet, or in a browser (a default value).

If the link to the external style sheet is placed after the internal style sheet in HTML , the external style sheet will override the internal style sheet!

Download Ruby

0 comments




Ruby Source Code

Installing from the source code is a great solution for when you are comfortable enough with your platform and perhaps need specific settings for your environment. It’s also a good solution in the event that there are no other premade packages for your platform.

  • Ruby 1.9.1-p129 (md5: c71f413514ee6341c627be2957023a5c) Stable Version (recommended)
  • Stable Snapshot This is tar’ed and gzip’ed file of the latest stable SVN. It should be better than the last stable release.
  • Nightly Snapshot This is tar’ed and gzip’ed file of the latest SVN. It may contain unfixed problems.

For information about the Ruby Subversion repository, see our Ruby Core page.

Ruby on Windows

The Windows platform has several options for installing Ruby. The first option is simply installing the compiled binaries. The second option is to use the one-click installer. If you’re unsure about how to install Ruby, the one-click installer may be the best option for you. (In addition to Ruby, the one-click installer also comes with a bunch of additional libraries built in.)

Ruby On Linux

Depending on the distribution you are using, there are several ways to install Ruby. The first option is simply to download the source code above and compile by hand. However, on some platforms, there are package management solutions that make installing Ruby extremely easy.

For example, on Debian or Ubuntu apt-get provides an easy and elegant solution:

% sudo apt-get install ruby irb rdoc

For irb and rdoc you will need to enable the universe repository.

Ruby On OS X

Ruby 1.8.6 is fully supported in Mac OS X Leopard including Ruby on Rails, Mongrel, Capistrano, and many other popular Ruby gems (packages). For details, see the Ruby wiki at MacOS Forge.

Mac OS X Tiger is packaged with version 1.8.2 of Ruby, but, for those who haven’t upgraded to Leopard, there are a number of options for installing the latest version of Ruby. Locomotive is a nice choice if you are looking for something to get you up and running quickly for Rails development. Using MacPorts or Fink might be a little nicer for the more technically savvy.

On MacPorts, you can install Ruby with…

% port install ruby

Fink has a graphical interface (using Fink Commander) for installing Ruby.

Also, since OS X is based on Unix, downloading and installing from the source is just as easy and effective as the other solutions.

For a detailed look at installing Ruby (and Rails), Dan Benjamin’s excellent articles for Tiger and for Leopard will get you up and running very quickly.

Ruby On Solaris and OpenSolaris

Ruby 1.8.7 is available for Solaris 8 through Solaris 10 on Sunfreeware and Ruby 1.8.6 is available at Blastwave. An optimized Ruby on Rails stack for Solaris 10 is available as Coolstack from Sun’s Cooltools project.

To install Ruby on OpenSolaris, please use the Image Packaging System, or IPS client. This will install the latest Ruby binaries and Rubygems directly from the OpenSolaris network repository. It’s easy:

% pfexec pkg install SUNWruby18

This will install Ruby, Rubygems, common extensions and their supporting libraries. This package also contains DTrace support and performance optimizations. The locations of various artifacts are described in the Ruby OpenSolaris ARC Case.

The other OpenSolaris distribution, called the Solaris Express Community Edition or SXCE comes with Ruby preinstalled. The version, location etc., are the same as with the vanilla OpenSolaris distribution, and are documented in the above mentioned ARC case.

To install SVR4 packages manually, please visit the RubyOpenSolaris project @ Rubyforge.

Ruby-The Red Diamond of Programming Languages

0 comments

Ruby is a language of careful balance. Its creator, Yukihiro “matz” Matsumoto, blended parts of his favorite languages (Perl, Smalltalk, Eiffel, Ada, and Lisp) to form a new language that balanced functional programming with imperative programming.

He has often said that he is “trying to make Ruby natural, not simple,” in a way that mirrors life.Building on this, he adds:
Ruby is simple in appearance, but is very complex inside, just like our human body1.

About Ruby’s Growth

Since its public release in 1995, Ruby has drawn devoted coders worldwide. In 2006, Ruby achieved mass acceptance. With active user groups formed in the world’s major cities and Ruby-related conferences filled to capacity.


The TIOBE index, which measures the growth of programming languages, ranks Ruby as #9 among programming languages worldwide. Much of the growth is attributed to the popularity of software written in Ruby, particularly the Ruby on Rails web framework2.

Ruby is also totally free. Not only free of charge, but also free to use, copy, modify, and distribute.


Seeing Everything as an Object

Initially, Matz looked at other languages to find an ideal syntax. Recalling his search, he said, “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python3.”

In Ruby, everything is an object. Every bit of information and code can be given their own properties and actions. Object-oriented programming calls properties by the name instance variables and actions are known as methods. Ruby’s pure object-oriented approach is most commonly demonstrated by a bit of code which applies an action to a number.

5.times { print "We *love* Ruby -- it's outrageous!" }

In many languages, numbers and other primitive types are not objects. Ruby follows the influence of the Smalltalk language by giving methods and instance variables to all of its types. This eases one’s use of Ruby, since rules applying to objects apply to all of Ruby.

Ruby’s Flexibility

Ruby is seen as a flexible language, since it allows its users to freely alter its parts. Essential parts of Ruby can be removed or redefined, at will. Existing parts can be added upon. Ruby tries not to restrict the coder.

For example, addition is performed with the plus (+) operator. But, if you’d rather use the readable word plus, you could add such a method to Ruby’s builtin Numeric class.

class Numeric
def plus(x)
self.+(x)
end
end

y = 5.plus 6
# y is now equal to 11

Ruby’s operators are syntactic sugar for methods. You can redefine them as well.
Blocks, a Truly Expressive Feature

Ruby’s block are also seen as a source of great flexibility. A programmer can attach a closure to any method, describing how that method should act. The closure is called a block and has become one of the most popular features for newcomers to Ruby from other imperative languages like PHP or Visual Basic.

Blocks are inspired by functional languages. Matz said, “in Ruby closures, I wanted to respect the Lisp culture4.”

search_engines =
%w[Google Yahoo MSN].map do |engine|
"http://www." + engine.downcase + ".com"
end

In the above code, the block is described inside the do ... end construct. The map method applies the block to the provided list of words. Many other methods in Ruby leave a hole open for a coder to write their own block to fill in the details of what that method should do.
Ruby and the Mixin

Unlike many object-oriented languages, Ruby features single inheritance only, on purpose. But Ruby knows the concept of modules (called Categories in Objective-C). Modules are collections of methods.

Classes can mixin a module and receive all its methods for free. For example, any class which implements the each method can mixin the Enumerable module, which adds a pile of methods that use each for looping.

class MyArray
include Enumerable
end

Generally, Rubyists see this as a much clearer way than multiple inheritance, which is complex and can be too restrictive.
Ruby’s Visual Appearance

While Ruby often uses very limited punctuation and usually prefers English keywords, some punctuation is used to decorate Ruby. Ruby needs no variable declarations. It uses simple naming conventions to denote the scope of variables.

* var could be a local variable.
* @var is an instance variable.
* $var is a global variable.

These sigils enhance readability by allowing the programmer to easily identify the roles of each variable. It also becomes unnecessary to use a tiresome self. prepended to every instance member.
Beyond the Basics

Ruby has a wealth of other features, among which are the following:

* Ruby has exception handling features, like Java or Python, to make it easy to handle errors.

* Ruby features a true mark-and-sweep garbage collector for all Ruby objects. No need to maintain reference counts in extension libraries. As Matz says, “This is better for your health.”

* Writing C extensions in Ruby is easier than in Perl or Python, with a very elegant API for calling Ruby from C. This includes calls for embedding Ruby in software, for use as a scripting language. A SWIG interface is also available.

* Ruby can load extension libraries dynamically if an OS allows.

* Ruby features OS independent threading. Thus, for all platforms on which Ruby runs, you also have multithreading, regardless of if the OS supports it or not, even on MS-DOS!

* Ruby is highly portable: it is developed mostly on GNU/Linux, but works on many types of UNIX, Mac OS X, Windows 95/98/Me/NT/2000/XP, DOS, BeOS, OS/2, etc.

PHP

0 comments

PHP

PHP is a powerful tool for making dynamic and interactive Web pages.

PHP is the widely-used, free, and efficient alternative to competitors such as Microsoft's ASP.

In our PHP tutorial you will learn about PHP, and how to execute scripts on your server.




PHP is a server-side scripting language.


What You Should Already Know

Before you continue you should have a basic understanding of the following:

  • HTML/XHTML
  • JavaScript

If you want to study these subjects first, find the tutorials on our


What is PHP?

  • PHP stands for PHP: Hypertext Preprocessor
  • PHP is a server-side scripting language, like ASP
  • PHP scripts are executed on the server
  • PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)
  • PHP is an open source software
  • PHP is free to download and use

What is a PHP File?

  • PHP files can contain text, HTML tags and scripts
  • PHP files are returned to the browser as plain HTML
  • PHP files have a file extension of ".php", ".php3", or ".phtml"

What is MySQL?

  • MySQL is a database server
  • MySQL is ideal for both small and large applications
  • MySQL supports standard SQL
  • MySQL compiles on a number of platforms
  • MySQL is free to download and use

PHP + MySQL

  • PHP combined with MySQL are cross-platform (you can develop in Windows and serve on a Unix platform)

Why PHP?

  • PHP runs on different platforms (Windows, Linux, Unix, etc.)
  • PHP is compatible with almost all servers used today (Apache, IIS, etc.)
  • PHP is FREE to download from the official PHP resource: www.php.net
  • PHP is easy to learn and runs efficiently on the server side

Where to Start?

To get access to a web server with PHP support, you can:

  • Install Apache (or IIS) on your own server, install PHP, and MySQL
  • Or find a web hosting plan with PHP and MySQL support




Advertisement

 

Copyright 2009 All Rights Reserved SITS