Saturday, November 20, 2010

Php hacking techniques part 1

Techniques for securing user input, then extended those techniques to applications where database input and output is required, looking at some SQL security issues. next is to deal with file operations and file uploads, looking specifically at the security issues involved with accessing files based on some user supplied filename, and user-supplied files (uploaded files).


What Are Sessions?
Sessions are a PHP construct allowing persistent data to be retained across HTTP connections. In English, sessions allow you to store the values of certain variables across page visits. This is achieved by serializing the data (converting it to some binary representation) and writing it out to a file (or a database, or wherever you tell it), when a page is finished processing in PHP. When the next page (or that same page some time later) is processed, and PHP is told to start a session, it will check if the user already has a session, and read their data back in, unserializing it and assigning the variables. This allows you to keep track of a user across multiple visits, or while browsing multiple pages on your site.

For example, you can create a shopping cart using sessions, storing an array of items added to the cart in a session variable, and loading it on every page. When the user clicks 'Add to cart' you can add the item to the array, and it will be saved for the next page the user goes to. The whole array can be fetched on your checkout page and appropriate processing will take place.

How Do Sessions Work?
As many probably know, HTTP is a stateless protocol. By stateless, I mean that any HTTP connection is unaware of previous connections made by the same client, to the same server (persistent connections excepting). There are two useful ways in which PHP can pass identification information between pages in order to uniquely associate a user with a session.

PHP can use cookies to store a session ID. The cookie value is sent on every request, so PHP can match that up to its session data and retrieve the correct set of variables for that user. Another way is to pass the session ID in URLs. In order to do this, URL rewriting must be enabled.

Passing session data in URLs is not recommended since it is possible to pass your session onto another user if you give them a link which contains your session ID, and the session ID data is more easily attackable than in a cookie. URL-based session tracking should be used only where cookies cannot.

Using $_SESSION
PHP provides a super-global variable named $_SESSION. By super-global I mean it is a global variable which you may access without going via $_GLOBALS or stating global $_SESSION within a function. In this way, it behaves like $_GET and $_POST.

$_SESSION is, in fact, an associative array. The keys are variable names, and the values are the stored session data for that variable name.

Using $_SESSION is preferred over the use of session_register() to register ordinary global variables as session variables, especially when register_globals is enabled, since global variables may be more easily changed inadvertently than the contents of $_SESSION. It is still possible to alias ordinary global variables to their equivalents within $_SESSION,

$username = &$_SESSION["username"];

Here, the & indicates a reference, or alias. It is then possible to use $username instead of $_SESSION["username"], but note that $username is an ordinary variable, and you will have to access as $_GLOBALS["username"] or global $username from within a function.

Trusting Session Data
Since a session ID can be spoofed, it is always wise to perform some extra validation where possible. The simplest mechanism would be to store the IP address of the client to whom the session ID was issued, and compare the client IP against that stored IP every session. This will prevent the basic security problems associated with passing links between computers (though not if the computers are on a private network and share a single public IP address).

Session data is also stored in files on the server. The default location is /tmp on UNIX, or the system temporary file directory on Windows. If /tmp is world-writable (or, in some cases, world-readable), or there are multiple websites hosted on a single server, storing session data in a public location is not secure. PHP provides a way to change the way session data is stored.

Changing The Session File Path
The location in which PHP saves session data can be set using the php.ini directive session.save_path, or the string below in httpd.conf or a virtual host configuration.

php_value session.save_path "/home/test/sessions/"

It is important to ensure that your session data path is included in the paths allowed by open_basedir, if you have open_basedir settings or PHP Safe Mode enabled.

The data representation used for saving session data to files can be controlled with the session.serialize_handler directive in php.ini. By default, PHP uses its own built in format, but the WDDX ( http://www.wddx.org ) format can be used also. Set the type using one of the lines below.

(in php.ini ...)

session.serialize_handler wddx

or

session.serialize_handler php

(or in httpd.conf ...)

php_value session.serialize_handler wddx

or

php_value session.serialize_handler php

Storing Session Data In A Database
When you use on-disk files to store session data, those files must be readable and writeable by PHP. On a multi-user hosting system, it is possible for other users to access your session data through the PHP process (but see the commentary on open_basedir in part 5 of this series. The best way to secure your session data is to store it in a database.

Unfortunately, there is no direct way to store session data in a database using the php.ini directives, but luckily PHP provides a mechanism for customised session storage handlers. The function session_set_save_handler() allows you to register handler functions for session management. These functions must be written in PHP (or made available as a PHP extension).

session_set_save_handler(open_fn, close_fn, read_fn, write_fn,

destroy_fn, gc_fn)

To use these user-supplied session storage handlers, you must set session.save_handler to the value user, and the value of session.save_path should be the name of the database into which you're saving session data (so that the session save handler functions you define can locate and use that database). The value of session.name can be used as the name of the table within the database.

(httpd.conf)



php_value session.save_handler user

php_value session.save_path dbname

php_value session.name session_data



Next, a table for storing session data must exist in the database. At the minimum, your session handler should keep track of the session ID, the expiration time, and the serialized session data. The SQL below creates a simple table for storing this data.

CREATE TABLE session_data (

sessionid text not null PRIMARY KEY,

expiration timestamp,

sessiondata text not null

);

The final task is to create the functions which manage this session store, and register them with session_set_save_handler(). The open_fn must open the database connection, the close_fn must close it and perform any associated cleanup tasks, and the read_fn and write_fn functions must read and write session data respectively. destroy_fn is called when a session ends and is destroyed, and gc_fn is called when session data is garbage collected. These operations must be mapped into database queries by your PHP code. The prototypes for the functions are given below, and parameters passed are explained.

function open_fn($save_path, $session_name)

$save_path is the value of session.save_path, $session_name is the value of session.name

function close_fn()

Takes no arguments

function read_fn($session_id, $data)

$session_id is the session ID for which PHP requests the associated session data to be returned

function write_fn($session_id)

$session_id is the session ID for which PHP requests that $data be associated with in the session store (database)

function destroy_fn($session_id)

$session_id is the ID of a session which may be removed from the store

function gc_fn($max_time)

$max_time is the oldest last modified time to retain in the session store. Sessions with an older modified time than this are to be removed from the store.
-- Continued in Next pPrt

Leia Mais…

Php hacking techniques part 2

Implementing the above functions, you are not limited simply to database connections. You could, for instance, connect to some other data storage application, or store the session data in an encrypted virtual filesystem, or on a network file server.

Further Securing Sessions
There are a few remaining PHP directives for controlling sessions, several of these have security implications. Firstly, the session name (set with session.name) should be changed from the default to avoid collisions, especially on servers with multiple users.

The session.cookie_path directive determines the default cookie path, the path for which cookies will be sent in an HTTP request. If you have a forum at somedomain.com/forum, and somedomain.com/ does not require session management, you can change session.cookie_path as shown below.



php_value session.cookie_path /forum/



This prevents sections of your site which do not require the session cookie from being sent it, and limits exposure of the session IDs to those parts of a site where sessions are actually being used. This is especially important if some sections of your site have pages provided by other users, who could use those pages to steal session IDs from your visitors.

Setting session.use_only_cookies to true disables the passing of session IDs in URLs, at the cost of losing sessions support for users with cookies disabled, or on browsers not supporting cookies. Setting session.cookie_domain to the most restrictive domain name possible (e.g. forum.somesite.com instead of somesite.com) also helps to minimise exposure of session IDs. Of course, if you have a single login for an entire range of subdomains, you will have to set the domain as somedomain.com to ensure that the sessions are correctly managed across all of the subdomains.

Finally, it is possible to set the hash function used when creating session IDs. The default is to use MD5 (hash function 0), but SHA1 may also be used (hash function 1). SHA1 is a 160-bit hash function, whereas MD5 is only a 128-bit hash function, so using SHA1 for session hashes improves security slightly over using MD5. You can set the hash function using This setting was introduced in PHP 5.

php_value session.hash_function 1

Beyond PHP Security
Everything I've covered so far has been directly related to PHP and SQL security. The best situation we can manage here is PHP Safe Mode, which uses self-imposed restrictions to improve security. That this is the best we can achieve is due to the server architecture currently in use. There are, however, a few options for taking security a little further, and imposing the restrictions at a lower level than PHP itself. To conclude this series, I'll mention some of these briefly here.

Chroot
Chroot changes the "root" directory that a process can see. This effectively locks it into a certain directory structure within the overall filesystem. With this approach, you can lock a web server into some directory such as /home/www and it will not be able to access anything outside of that structure.

There are several advantages to doing this. The first is that the web server, PHP, any user scripts, and also any attackers, will be contained within this chroot "jail", unable to access files outside of it. Furthermore, you can remove all but the most essential software from the chroot environment. Removing any shells from the environment prevents a large number of exploits which attempt to invoke a remote shell. The minimal environment inside a chroot makes life very difficult for attackers, no matter whether their method of attack is through a vulnerability in your PHP code, or a vulnerability in the underlying web server.

Apache mod_security and mod_chroot
mod_security and mod_chroot are extension modules specifically for the Apache web server. These two modules provide chroot support for Apache without externally applying a chroot technique. mod_security also provides several other security features. Further information is available at http://www.modsecurity.org/ for mod_security and at http://core.segfault.pl/~hobbit/mod_chroot/ for mod_chroot.

suEXEC and Multiple Server Instances
Using a chroot to lock your web server into a restricted environment helps to prevent some security problems, but one of the big issues is shared hosting. Running multiple websites on the same server requires that the web server process has access to each user's files. If the web server has access, so do the other users (subject to PHP Safe Mode restrictions, of course). There are two ways around this, one which is Apache specific, and one which may be deployed on any server environment.

suEXEC, specific to Apache, switches an Apache process to be owned by the same user as the script it is executing, losing any escalated permissions. This locks that Apache instance into the permissions held by that user, rather than the permissions held by the master web server process itself. This mechanism allows a return to the more traditional permissions system, and each user can be reasonably sure his or her files are protected. The cost of this is that an Apache process may not then be promoted back to regain permissions and switch user again to serve a different user's files. This system works best when there will be many requests for pages owned by the same user. suEXEC is explained in more detail at http://httpd.apache.org/docs/1.3/suexec.html

The alternative is to use multiple instances of the web server, each one running with the permissions of a different user. Each server then only has the permissions it needs to serve a single website, so a reverse proxy must be used as a front to all of these server instances, redirecting requests for a virtually hosted website to the Apache instance responsible for actually serving that site. This solution is the most secure, but also the most resource-hungry. Information about using Apache as a reverse proxy is available at http://httpd.apache.org/docs/1.3/mod/mod_proxy.html

How to check for PHP vulnerabilities
The best way to check whether your web site & applications are vulnerable to PHP security attacks is by using a Web Vulnerability Scanner. A Web Vulnerability Scanner crawls your entire website and automatically checks for vulnerabilities to PHP attacks. It will indicate which scripts are vulnerable so that you can fix the vulnerability easily. Besides PHP security vulnerabilities, a web application scanner will also check for SQL injection, Cross site scripting & other web vulnerabilities.

The Acunetix Web Vulnerability Scanner scans for SQL injection, Cross site scripting (XSS), Google hacking and many more vulnerabilities. For more information & a trial download click here.

Check if your website is vulnerable to attack with Acunetix Web Vulnerability Scanner

Acunetix Web Vulnerability Scanner ensures website security by automatically checking for SQL injection, Cross site scripting and other vulnerabilities. It checks password strength on authentication pages and automatically audits shopping carts, forms, dynamic content and other web applications. As the scan is being completed, the software produces detailed reports that pinpoint where vulnerabilities exist. Take a product tour or download the evaluation version today!

Scanning for XSS vulnerabilities with Acunetix WVS Free Edition!
To check whether your website has cross site scripting vulnerabilities, download the Free Edition from http://www.acunetix.com/cross-site-scripting/scanner.htm. This version will scan any website / web application for XSS vulnerabilities and it will also reveal all the essential information related to it, such as the vulnerability location and remediation techniques. Scanning for XSS is normally a quick exercise (depending on the size of the web-site).

Final Words
This concludes the tour of PHP and SQL security. There is much more information available on the web about each security issue covered in this series, and many other issues also. In particular, several Apache modules exist for improving security through chrooting, reverse proxies, or simply checking requests for attacks such as directory traversal.

The PHP manual over at php.net points out any security concerns relating to most functions, and the comments posted by users below the reference pages often contain useful security hints and code samples

Leia Mais…

Tuesday, June 29, 2010

Cookies in PHP

The better and simple solution for sending the user input values from one page to another page is using COOKIES. We can send data easily from page to page and can be easily retrieved and used.

Setting Cookies

setcookie():This method is used for creating the Cookies. Important note is that Cookies are sent with the HTTP headers,so setcookie() must be called before any output is generated.

Example:
setcookie('Variable','Value');

This is the default syntax declaration, We have another parameters which has its own importance but they are not mandatory.

The third argument to setcookie() is an expiration time,expressed as an epoch timestamp.For example, this cookie expires at noon GMT on December 3, 2004:

setcookie('flavor','chocolate chip',1102075200);

If the third argument to setcookie() is missing (or empty),the cookie expires when
the browser is closed. Also,many systems can’t handle a cookie expiration time
greater than 2147483647,because that’s the largest epoch timestamp that fits in a
32-bit integer

The fourth argument to setcookie() is a path. The cookie is sent back to the server
only when pages whose path begin with the specified string are requested. For example, the following cookie is sent back only to pages whose path begins with /products/:

setcookie('flavor','chocolate chip','','/products/');

The page that’s setting this cookie doesn’t have to have a URL that begins with /products/, but the following cookie is sent back only to pages that do.

The fifth argument to setcookie() is a domain. The cookie is sent back to the server
only when pages whose hostname ends with the specified domain are requested. For
example,the first cookie in the following code is sent back to all hosts in the example.com domain,but the second cookie is sent only with requests to the host test.example.com:
setcookie('variable','value','','','.example.com');
setcookie('variable','value','','','test.example.com');

If the first cookie’s domain was just example.com instead of .example.com,it would
be sent only to the single host example.com (and not www.example.com or test.
example.com).

The last optional argument to setcookie() is a flag that if set to 1,instructs the
browser only to send the cookie over an SSL connection. This can be useful if the
cookie contains sensitive information,but remember that the data in the cookie is
stored in the clear on the user’s computer.

Reading Cookie Values
A cookie’s value isn’t available in $_COOKIE during the request in which the cookie isset. In other words,the setcookie() function doesn’t alter the value of $_COOKIE. On subsequent requests,however,each cookie is stored in $_COOKIE. If register_globals
is on, cookie values are also assigned to global variables.

When a browser sends a cookie back to the server,it sends only the value. You can’t
access the cookie’s domain,path,expiration time,or secure status through $_COOKIE
because the browser doesn’t send that to the server.
To print the names and values of all cookies sent in a particular request,loop
through the $_COOKIE array:

foreach ($_COOKIE as $cookie_name => $cookie_value) {
print "$cookie_name = $cookie_value
";
}

Deleting Cookies
Call setcookie() with no value for the cookie and an expiration time in the past:

setcookie('flavor','',time()-86400);

It’s a good idea to make the expiration time a few hours or an entire day in the past,in case your server and the user’s computer have unsynchronized clocks. For example,if your server thinks it’s 3:06 P.M. and a user’s computer thinks it’s 3:02 P.M.,a cookie with an expiration time of 3:05 P.M. isn’t deleted by that user’s computer even though the time is in the past for the server.
The call to setcookie() that deletes a cookie has to have the same arguments (except
for value and time) that the call to setcookie() that set the cookie did,so include the path, domain, and secure flag if necessary.

Different browsers handle cookies in slightly different ways,especially with regard to how strictly they match path and domain strings and how they determine priority
between different cookies of the same name.

Leia Mais…

Wednesday, June 16, 2010

PHP working with Files and Directory

Below are some of the important methods used when working or manipulating the files or folders

parse_ini_file($filename)
parse_ini_file() loads in the ini file specified in filename, and returns the settings in it in an associative array.
Example
// Parse without sections
$ini_array = parse_ini_file("sample.ini");
print_r($ini_array);

// Parse with sections
$ini_array = parse_ini_file("sample.ini", true);
print_r($ini_array);
O/P
Array
(
[one] => 1
[five] => 5
[animal] => Dodo bird
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
[phpversion] => Array
(
[0] => 5.0
[1] => 5.1
[2] => 5.2
[3] => 5.3
)

)
Array
(
[first_section] => Array
(
[one] => 1
[five] => 5
[animal] => Dodo bird
)

[second_section] => Array
(
[path] => /usr/local/bin
[URL] => http://www.example.com/~username
)
)

basename($path)
Given a string containing a path to a file, this function will return the base name of the file.
Example
$path = "/home/httpd/html/index.php";
$file = basename($path); // $file is set to "index.php"

dirname($path)
Given a string containing a path to a file, this function will return the name of the directory.
example
$path = "/etc/passwd";
$file = dirname($path); // $file is set to "/etc"

pathinfo($_SERVER['PHP_SELF'])
pathinfo() returns an associative array containing information about path.
Example
$path_parts = pathinfo('/www/htdocs/inc/lib.inc.php');

echo $path_parts['dirname'], "\n"; //www/htdocs/inc
echo $path_parts['basename'], "\n"; //lib.inc.php
echo $path_parts['extension'], "\n"; //php
echo $path_parts['filename'], "\n"; // lib.inc

realpath($path)
realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input path and return the canonicalized absolute pathname
Example
echo realpath('/windows/system32'); //C:\WINDOWS\System32

getcwd()
Gets the current working directory.

file_exists
hecks whether a file or directory exists

Leia Mais…

Tuesday, June 15, 2010

PHP Magic Methods

These are the following magic methods available

__construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state and __clone are magical in PHP classes.

PHP reserves all function names starting with __ as magical.

__sleep
serialize() checks if your class has a function with the magic name __sleep. If so, that function is executed prior to any serialization. It can clean up the object and is supposed to return an array with the names of all variables of that object that should be serialized. If the method doesn’t return anything then NULL is serialized and E_NOTICE is issued.

__wakeup
Conversely, unserialize() checks for the presence of a function with the magic name __wakeup. If present, this function can reconstruct any resources that the object may have.

Example:
class Connection {
protected $link;
private $server, $username, $password, $db;

public function __construct($server, $username, $password, $db)
{
$this->server = $server;
$this->username = $username;
$this->password = $password;
$this->db = $db;
$this->connect();
}

private function connect()
{
$this->link = mysql_connect($this->server, $this->username, $this->password);
mysql_select_db($this->db, $this->link);
}

public function __sleep()
{
return array('server', 'username', 'password', 'db');
}

public function __wakeup()
{
$this->connect();
}
}

__tostring
The __toString method allows a class to decide how it will react when it is converted to a string.

Example
class Member
{
private $m_szEmail;
private $m_szUsername;

public function __construct($szUsername, $szEmail)
{
$this->m_szUsername = $szUsername;
$this->m_szEmail = $szEmail;
}
}

$pMember = new Member('Karl', 'karl@talkphp.com');

echo $pMember;

O/P is object.

Usually, most people would achieve this with code like:

echo $pMember->getUsername() . " (" . $pMember->getEmail() . ")";

However, what we can do is use the __toString() function to change the default behaviour of the object to string conversion. This would allow us to specify exactly
Add this method in your class

public function __toString()
{
return sprintf('%s (%s)', $this->m_szUsername, $this->m_szEmail);
}

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

__invoke() this method is called when a script tries to call an object as a function.

__set_state() This static method is called for classes exported by var_export() since PHP 5.1.0.

The only parameter of this method is an array containing exported properties in the form array('property' => value, ...).

Leia Mais…

Tuesday, June 1, 2010

PHP 5 OOPS concepts Key Words

Extends
In PHP a class a class can inherit methods, functions and members of other class by using the extends keyword in the declaration. In PHP it is not possible to inherit from multiple classes, a class can inherit from only one base class.

The class from which inheritance is done is called the parent class or base class and the class which inherits is called the child class.

Final
The final keyword prevents the child classes from overriding a method. This can be done by prefixing the method with the keyword final. If the complete class is being defined as final then that class cannot be extended.

Abstract
A new concept of abstract classes and methods has been introduced in PHP5. When a class is defined as abstract then it is not allowed to create the instance of that class. A class that contains at least one abstract method must also be abstract. The methods defined as abstract cannot define the implementation; they just declare the method’s signature.

When a child class is inheriting from an abstract parent class, then all the methods marked abstract in parent class declaration must also be additionally defined by the child class. These methods must be defined with the same or weaker access. This means that if an abstract method is declared as protected in the parent class then it must be declared either as protected or public in the child class.

Static
When class members or methods are declared as static then there is no need to instantiate that class. These members and methods are accessible without the instantiation of the class. If a member is declared as static then it cannot be accessed by an instantiated class object, but a method declared as static can be accessed by an instantiated class object.

The static declaration of a class must be after the visibility declaration (means that after the member or method has been declared as public, protected, or private).

The static method calls are resolved at compile time and static properties cannot be accessed through the object through the arrow operator (->).

Interfaces
Object interfaces allow the creation of a code which specifies that which method a class must implement, without having to define how these methods have to be handled.

Interfaces are defined in the same way as a class is defined. These interfaces are defined with the keyword “interface”. In the interface the contents of the methods do not have to be defined and all the methods declared in the interface must be declared as public.

Implementation of Interfaces
To implement an interface, the implements operator is used. The methods must be defined before implementation and all the methods in the interface must be implemented within a class.

Leia Mais…

Wednesday, April 28, 2010

Introduction of SOAP Architecture

Simplified Object Access Protocol (SOAP) is a specification that enables applications to communicate with other applications. It provides a framework for connecting Web sites and applications to create Web services. These Web services link different sites and applications together to perform functions that the individual components or sites are not capable of. SOAP provides a mechanism by which each service can expose its features and communicate with other services. Using SOAP, one can link services offered by different systems together as components and use these components to build a complex information system application in a much shorter timeframe.

High-Level diagram of SOAP in a distributed system

Advantages of SOAP
1. SOAP is an open standard that is built upon open technologies such as XML and HTTP. It is not vendor-specific and therefore less intimidating to smaller players in the industry. As a result it is being accepted uniformly by the industry, thus improving its chances of being the de-facto standard for true distributed interoperability.
2. SOAP based distributed systems are loosely-coupled. As a result they are easier to maintain because they can be modified independently of other systems.
3. When used over HTTP protocol, SOAP packets can easily bypass firewalls if their content is not deemed malicious.

Disadvantages of SOAP
1. SOAP’s relied on HTTP for transport of XML data in the version 1.0 of its specification. HTTP requires a stateless request/response architecture that is not appropriate under all circumstances. While one can work around the state problem it requires additional coding.
2. All SOAP data is serialized and passed by value and currently there is no provision for passing data by reference. This could lead to synchronization problems if multiple copies of the same object are being passed at the same time.

SOAP Architecture

Leia Mais…

Tuesday, April 27, 2010

Configure Virual host in Apache

Virtual hosting is a method for hosting multiple domain names on a computer using a single IP address. This allows one machine to share its resources, such as memory and processor cycles, to use its resources more efficiently.

One widely used application is shared web hosting. Shared web hosting prices are lower than a dedicated web server, because this allows many customers to be hosted on a single server.

Setting Up A Virtual Host in Apache
Setting up a virtual host in the Apache web server is not exactly a PHP topic, but many PHP developers use the Apache web server to test web pages on their development machine.

There is a lot of information around on how to do this, but the first time I tried it, I found the existing information to be more confusing than helpful. Hopefully, this page will simplify the process a bit. Please note that this information pertains to setting up a virtual host in Apache on a Windows machine for use as a local testing server.

Configuring Apache

The first file we'll need to edit is the Apache httpd.conf file. If you installed the Apache software using the download from the Apache web site, you should have a menu item that will open this file for editing. Click Start->Programs->Apache HTTP Server->Configure Apache Server->Edit the Apache httpd.conf Configuration File. If you don't have that start menu item, start your text editor and open the file. It will be in a sub-folder named conf of your Apache folder. For example, mine is here:

C:\Program Files\Apache Group\Apache\conf\httpd.conf

Notes for Apache Server Versions Since 2.2 Configuration

Note that Apache changed the preferred method for configuring the Apache server with the release of Apache 2.2. For versions beginning with 2.2, the peferred configuration is more modular. Setting up a virtual host as described here will still work with the newer versions, but to follow the modular approach, the editing of httpd.conf is only to uncomment (remove the # from the beginning of the following line:

#Include conf/extra/httpd-vhosts.conf

Everything else is entered in the file httpd-vhosts.conf, which will be located in the extra folder below the below the folder containing httpd.conf. As mentioned, the method described here will still work.
Security

Version 2.2 also changed some of the default security configuration parameters. To set things up the way you'll need them, you'll need to add the following block to either your httpd.conf file, just above the virtual hosts, or to your httpd-vhosts.conf file:

<Directory "C:\ My Sites ">
Order Deny,Allow
Allow from all
</Directory>

Simple Steps are:

1. Open the vhosts file in the apache folder and create a virtual path and the name which will be map the related folder and the server name for example

<VirtualHost 127.0.0.1>
DocumentRoot "C:\My Sites\Site1"
ServerName original
</VirtualHost>

<VirtualHost 127.0.0.1>
DocumentRoot "C:\My Sites\Site2"
ServerName testing
</VirtualHost>

2. Open 'hosts' file which is present in path "C:\WINNT\system32\drivers\etc\hosts"
add the server name to them. This will tell the apache that both the server
names should be responded For example

127.0.0.1 original
127.0.0.1 testing

Restart the apache server and your done

Leia Mais…

Tuesday, April 20, 2010

PHP OOPS - Polymorphism

What is Polymorphism?
Polymorphism in PHP5 is a technique where the function to be called is detected based on the class object calling it at runtime. The basis of Polymorphism is Inheritance and function overridden.


Example – Basic Polymorphism


class BaseClass
{
public function myMethod()
{
echo "BaseClass method called";
}
}

class DerivedClass extends BaseClass
{
public function myMethod()
{
echo "DerivedClass method called";
}
}

function processClass(BaseClass $c)
{
$c->myMethod();
}

$c = new DerivedClass();
processClass($c);

Output:
DerivedClass method called

Here i am declaring BaseClass and DerivedClass but i am calling the the processClass with the Derived Class Object.

Leia Mais…

Monday, April 19, 2010

Jooma Events

The events triggered in Joomla! are:

These are the related methods trigged when a particular event occurs

Authentication

* onAuthenticate

Content

* onPrepareContent
* onAfterDisplayTitle
* onBeforeDisplayContent
* onBeforeContentSave (new in 1.5.4)
* onAfterContentSave (new in 1.5.4)

Editors

* onInit
* onGetContent
* onSetContent
* onSave
* onDisplay
* onGetInsertMethod

Editors XTD (Extended)


* onDisplay

Seach

* onSearch
* onSearchAreas

System

* onAfterInitialise
* onAfterRoute
* onAfterDispatch
* onAfterRender

User

* onLoginUser
* onLoginFailure
* onLogoutUser
* onLogoutFailure
* onBeforeStoreUser
* onAfterStoreUser
* onBeforeDeleteUser
* onAfterDeleteUser

XML-RPC

* onGetWebServices

Leia Mais…

What is DTD? Types of DTD?

The doctype declaration should be the very first thing in an HTML document, before the html tag.

The doctype declaration is not an HTML tag; it is an instruction to the web browser about what version of the markup language the page is written in.

The doctype declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers can render the content correctly.

Doctypes Available in the W3C Recommendations
HTML 4.01 Strict

This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.

HTML 4.01 Transitional

This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed.

HTML 4.01 Frameset

This DTD is equal to HTML 4.01 Transitional, but allows the use of frameset content.

XHTML 1.0 Strict


This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.

XHTML 1.0 Transitional

This DTD contains all HTML elements and attributes, INCLUDING presentational and deprecated elements (like font). Framesets are not allowed. The markup must also be written as well-formed XML.

XHTML 1.0 Frameset

This DTD is equal to XHTML 1.0 Transitional, but allows the use of frameset content.

Leia Mais…

Saturday, April 17, 2010

What is Http? Types of Headers in HTTP

The Hypertext Transfer Protocol (HTTP) is an Application Layer protocol for distributed, collaborative, hypermedia information systems.

HTTP is a request-response standard typical of client-server computing. In HTTP, web browsers or spiders typically act as clients, while an application running on the computer hosting the web site acts as a server. The client, which submits HTTP requests, is also referred to as the user agent. The responding server, which stores or creates resources such as HTML files and images, may be called the origin server. In between the user agent and origin server may be several intermediaries, such as proxies, gateways, and tunnels.

HTTP is not constrained in principle to using TCP/IP, although this is its most popular implementation platform. Indeed HTTP can be "implemented on top of any other protocol on the Internet, or on other networks." HTTP only presumes a reliable transport; any protocol that provides such guarantees can be used.

Resources to be accessed by HTTP are identified using Uniform Resource Identifiers (URIs)—or, more specifically, Uniform Resource Locators (URLs)—using the http or https URI schemes.

Requests Headers:
These are the following request headers:
Accept Content-Types that are acceptable
Accept-Charset Character sets that are acceptable
Accept-Encoding Acceptable encodings
Accept-Language Acceptable languages for response
Cache-Control Used to specify directives that MUST be obeyed by all caching
mechanisms along the request/response chain
Content-Type The mime type of the body of the request (used with POST and PUT
requests)
Host The domain name of the server (for virtual hosting), mandatory since
HTTP/1.1
Pragma Implementation-specific headers that may have various effects
anywhere along the request-response chain.

Responses
These are the response headers

Accept Content-Types that are acceptable
Accept-Charset Character sets that are acceptable
Accept-Encoding Acceptable encodings
Accept-Language Acceptable languages for response
Cache-Control Used to specify directives that MUST be obeyed by all caching
mechanisms along the request/response chain
Content-Type The mime type of the body of the request (used with POST and PUT
requests)
Host The domain name of the server (for virtual hosting), mandatory since
HTTP/1.1
Pragma Implementation-specific headers that may have various effects
anywhere along the request-response chain.
WWW-Authenticate Indicates the authentication scheme that should be used to access
the requested entity.
Set-Cookie an HTTP cookie

Leia Mais…

Send Mail using SMTP Authentication

Sending Mail from PHP Using SMTP Authentication - Example

require_once "Mail.php";

$from = "Sandra Sender ";
$to = "Ramona Recipient ";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "mail.example.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
echo("

" . $mail->getMessage() . "
");
} else {
echo("Message successfully sent!
");
}
?>

Sending Mail from PHP Using SMTP Authentication and SSL Encryption - Example

require_once "Mail.php";

$from = "Sandra Sender ";
$to = "Ramona Recipient ";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";

$host = "ssl://mail.example.com";
$port = "465";
$username = "smtp_username";
$password = "smtp_password";

$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'port' => $port,
'auth' => true,
'username' => $username,
'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
echo("" . $mail->getMessage() . "
");
} else {
echo("Message successfully sent!
");
}
?>
Reference URL is http://www.9lessons.info/2009/10/send-mail-using-smtp-and-php.html

Leia Mais…

Wednesday, January 20, 2010

Sql Comands DDL , DML ,DCL , TCL

In Sql(Structured Query Language) we have different type of commands available:

DDL

DDL (Data Definition Language)

These statements are used to define the database structure or schema. Some examples:

* CREATE - to create objects in the database
* ALTER - alters the structure of the database
* DROP - delete objects from the database
* TRUNCATE - remove all records from a table, including all spaces allocated for the records are removed
* COMMENT - add comments to the data dictionary
* RENAME - rename an object

DML

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

* SELECT - retrieve data from the a database
* INSERT - insert data into a table
* UPDATE - updates existing data within a table
* DELETE - deletes all records from a table, the space for the records remain
* MERGE - UPSERT operation (insert or update)
* CALL - call a PL/SQL or Java subprogram
* EXPLAIN PLAN - explain access path to data
* LOCK TABLE - control concurrency

DCL

Data Control Language (DCL) statements. Some examples:

* GRANT - gives user's access privileges to database
* REVOKE - withdraw access privileges given with the GRANT command

TCL

Transaction Control (TCL) statements are used to manage the changes made by DML statements. It allows statements to be grouped together into logical transactions.

* COMMIT - save work done
* SAVEPOINT - identify a point in a transaction to which you can later roll back
* ROLLBACK - restore database to original since the last COMMIT
* SET TRANSACTION - Change transaction options like isolation level and what rollback segment to use

Leia Mais…

Friday, January 15, 2010

PHP & MQUERY


MQUERY


mQuery is a dynamic image generation script written in PHP with heavy bindings to ImageMagick. I insist that anyone be able to use it, which is why I've decided to make available under an open source BSD 2-clause license.

Why

I often found myself having to strugle with the GUIs of a certain pair of industry standard vector and scalar graphics editors to generate relatively simple images, mQuery aims to streamline the generation of images used within CSS to produce complex designs without the need for an editor.

It's not a complete replacement, especially for heavy path-based designs and artwork that requires constant visual feedback, but in most cases a finely crafted URI can produce the same results with much less effort, while minimizing the grunt work that coincides with evolutionary-design to a simple query tweak.

mQuery is arguably even more useful for manipulating images that must be generated dynamically, such as user-submitted photos.

Known Issues

mQuery is currently in pre-alpha. Not ready for production use. Some vital features are not fully implemented. Here is a list of known issues:

* stroke() on groups strokes all subshapes, rather than the collective group.
ImageMagick's stroking is limited to only a center-aligned variable width stroke. To make aligned, offset, inner and outer strokes I composite multiple center strokes of different width together. It's hacky and creates a lot of problems. I should be able to make this work with groups but I will have to rewrite the stroke algorithm when I get the time.
* 1 pixel strokes are too wide or too thin.
Again the stroke() implementation is hacky. I think this is a rounding error in ImageMagick. The only workaround right now is to use decimal widths like 1.1 or 0.9 to get it looking right. I am still debating weather or not to do this number fudging in the implementation.
* Text gets cut off
Apparently some fonts don't respect their bounding box and exceed the clipping region. Please let me know if you have a particular font that does this a lot, as it would help me debug the problem. I attemped to fix this by painting into a buffer 1 pixel too large on each side and correcting if any of the sides were not empty, but it was too slow, and tended to make the resulting font size incredibly small (explains why the fonts do it). I think the best solution may be to allow the overflow and then give text shapes special treatment for painting, but this is complicated and requires some architectural changes. It will also create new corner cases in certain brushes.
* No multiline text
I have to implement this on my side because ImageMagick's implementation is buggy. Different text alignments paint strokes in the wrong position.
* contrast() has a limited range
For some reason this is how ImageMagick is. I might be able to make this work with composition, or if need be an fx expression. It's on the list.
* rotate()
The ImageMagick rotate API doesn't take an origin, so I need to do the math myself and haven't gotten to it yet.

For futher Details Please visit Mquery

Leia Mais…