Monday, February 22, 2010

Free Webhostings

Below link provids list of free web hosting provider of php-mysql webhostingclick here for free hosting

Wednesday, October 7, 2009

Uses for Stored Procedures

You might already have a good idea of what can be done with stored procedures.However, probably much more can be done with stored procedures than you've everthought of. Truthfully, probably quite a bit more can be done than I have ever thought of. The great thing about stored procedures is that, as a developer, you cancreate stored procedures that do whatever you need them to do. The following is alist of some of what you can do with stored procedures and reasons for using them.Most of these items are covered in this book; over time, you will discover others.

? Encapsulation of Queries— One of the first uses I discovered for stored procedures was to encapsulate queries so that I didn't have to worry aboutwhere they were saved, and I could execute them from anywhere on the network. The first queries I wrote were simple SELECT statements that returned extremely simple information. At that time, the only query tool available to the users of the system I was working with was ISQL/w, the precursor to Query Analyzer, so I also used stored procedures to roll out the queries to the users. All the users had to do was log in to the system and execute the stored procedure and they would get all the results they needed.
? Parameterized Queries— After I figured out how basic stored procedure worked and mastered the SELECT statement, the next thing that I did was start to work on parameterized queries. These stored procedures accepted one or two parameters and returned a subset of the information in the tables in which the user was interested. This enabled the users to return only those results that were important to them.

? Encapsulation of Data Modification Statements— Another great use of stored procedures is to encapsulate data modification statements. When you type data modification statements into a query window and execute them,there is a possibility that you will mistype something and cause severe problems in the database. If you encapsulate the data modification statements into a stored procedure that has been adequately tested, you are able to better control the statement and limit the amount of damage that can be done in the statement.

? Maintainability of Application Logic— One very widespread use of stored procedures is to use them as a container for application logic. This way, you can maintain all your company's business rules and logic in a single location,which makes them extremely easy to maintain. If a business rule changes, all you have to do is change the code in the stored procedure, and all users would have the new code.

? Standardization— If you roll all the data access, data modification, and
business logic statements into stored procedures, you are virtually guaranteed that all access to your database will be standardized. That means if a user accesses a particular table, you know exactly what he is doing and how he is doing it.

? Ease of Troubleshooting— This point closely follows the previous point. If you standardize all your database access through a common set of stored procedures, troubleshooting is much easier. This ease is because you have only one place to look to find the problems and, when the problem is fixed,one place to roll the changes to.

? Security— One of the best, but least implemented, uses for stored procedures is as a security measure. If you create a stored procedure that accesses a table, you can revoke access to that table; the only way your users can access that table is through the stored procedure you've created.This is an extremely powerful method for locking down the server andkeeping users from accessing information they aren't supposed to.

? Automation of Administration Tasks— The most fun and most types of stored procedures to write (for me at least) are procedures that assist in the automation of the SQL Server. Like system stored procedures,the core set of procedures installed with SQL Server, these procedures are used to perform low-level system functions and to return information about the server and the objects on the server. I call these procedures utility stored procedures. Later in this book, I present some of the most useful utility stored procedures that I have written for you to use and learn from.

Relational Database Management Systems

SQL Server 2000, the latest and greatest of the SQL Server platforms, is still a relational database management system (RDBMS). All RDBMSs share some qualities.These features are the basics of what make up any RDBMSs, and include thefollowing:

? As its name implies, the purpose of an RDBMS is to manage relational databases. A relational database is a grouping of tables. The tables are broken down into rows, also known as records, and the records are broken down into columns, also known as fields. Without these, you would have nothing to manage.

? All RDBMSs use SQL, or a variation of it, to manipulate the data contained in any of the databases. SQL (correctly pronounced S-Q-L) was developed at IBM in the late 1970s.

? RDBMSs must maintain data integrity. In other words, every relational database needs to ensure that if data in multiple tables is updated, all the updates take place. For example, imagine a banking system that contains two tables: one for your savings account and one for your checking account. You call your bank and ask to transfer $100 from savings to checking. This process involves subtracting $100 from your savings account and adding $100 to your checking account. If the bank loses power after the $100 is deleted from the table, what happens? If there is no data integrity, you have just lost $100. With data integrity, when the server is powered back on, the RDBMS realizes that the subtraction completed but that the addition didn't,and it cancels the whole transaction.

? Most RDBMSs strive to maintain separation between the actual data and the business logic that ensures that the data in the database is maintained in a constant state. In most cases, you will want to try to limit the amount of business functionality that you maintain in the database server.

? Many RDBMSs store data in such a way that redundant data is eliminated through some of type of compression. That doesn't mean data is lost—rather,it means that less storage space is needed.

? All RDBMSs provide some sort of security for the databases they manage.This security is usually at least a two-level process. First, any user who wants to access the system must identify herself with a valid login and password.When she passes this level of authentication, most systems have rules, called permissions, that block a user from accessing data to which she shouldn't have access.

SQL Server in Business Today

SQL Server has made huge inroads into the business market since its inception.The real advances have come since SQL Server 6.5. A huge number of applications in the marketplace have been written to utilize the advantages of SQL Server.A few categories of these systems are as follows:

?Customer Relationship Management (CRM) Software— A number of CRM packages on the market have been designed to take advantage of SQL Server in combination with other Microsoft products such as Exchange and Outlook. CRM products track customer information and all contact that has been made with the customers.

? Data Collection Systems— These applications are designed to capture realtime information and store it away for later processing and summarization.These systems usually require extremely high availability and reliability. To produce these types of results, SQL Server Enterprise Edition used with Windows NT Enterprise Edition in a clustered environment provides a platform with built-in redundancy and support for automatic failover.

?Data Warehouses— A data warehouse stores a large collection of data that can be analyzed for trends that are useful to the company that owns the data.For example, a simple data warehouse could show a company's inventory manager how a specific product has sold during a specific week over the past few years so that when the week in question rolls around, enough of that product is on hand to meet the projected need.Data warehouses were all the rage a few years ago. Support for data
warehouses dwindled because of the large investment it took to create them and their immense size. Smaller data warehouses, known as data marts, have lately begun to reemerge to provide this important information to companies that choose to implement them. SQL Server is a great choice for these types of applications because of built-in OLAP (Online Analytical Processing)support.

? E-Commerce— The surge in popularity of the Internet over the past few years has brought about a new way for companies to buy and sell products.Many companies have chosen SQL Server as the platform they base their ecommerce engines on because of its stability, high availability, and low cost.

SQL Server's History

SQL Server has actually been around for quite a while, in one form or another. SQL Server was originally introduced in 1988. The first version was a joint venture between Sybase and Microsoft, ran only on OS/2, and was a complete flop in themarketplace. In 1993, SQL Server 4.2 for Windows NT Advanced Server 3.1 was
released. This version made some small advances in the marketplace, but still didn't
have what it needed to make it an enterprise-class RDBMS. Microsoft and Sybase went their separate ways in 1994, and shortly afterward Microsoft released SQL Server 6.0. In 1996, SQL Server 6.5 was released. This version of SQL Server succeeded in the marketplace primarily because it had the speed, power, ease-ofuse, and low cost that purchasers and IT staffers were looking for.
In addition to the features that administrators were looking for, part of SQL Server'ssuccess has to do with the direction that the marketplace took around the same time that SQL Server 6.5 was released. For the most part, the market was moving towardfaster and cheaper Intel-based servers running Windows NT Server. This meant that,on abandoning other platforms, when there was a need for an RDBMS, SQL Server
became the natural selection.
SQL Server 7.0, released in early 1999, moved SQL Server into the enterprise database arena. Although previous versions of SQL Server contained large amounts of the original Sybase code, SQL Server 7.0 is said to be 100% Microsoft code.It's even said that Microsoft developers threw a party when the final lines of original code were removed. If SQL Server 7.0 is not a complete rewrite, it is pretty close.The latest version, SQL Server 2000, allows Microsoft to step a little further into the
enterprise database arena. It has a large amount of new features that make it a stronger competitor of the largest, most widely accepted enterprise database—Oracle. SQL Server will probably never completely take over this particular database arena, but it will continue to make strides to do so.

The History of Databases

There probably is a true written account on how databases evolved throughout the last few years. I won't get too far into the specifics here. From a high level, databases have been around for quite some time, just not computerized. Originally, databases were known as ledgers and card catalogs. These were maintained by people and really took a lot of manpower to maintain. When computers came around, it was really a logical progression to move databases to that platform. As processing power and storage increased and overall cost decreased, databases became more prevalent in the business world. Many paper processes became computer- oriented and all the data that would have normally been stored on paper forms in filing cabinets began to be stored in computer databases. Today, almost every business has a database of some sort, whether it be a lower-end Microsoft Access database or a higher-end SQL Server or Oracle database.

Saturday, August 1, 2009

PHP Session Management

Session Management
There are several parameters that can be manipulated to change the behavior of the PHP session management. These parameters are set in the php.ini file in the section headed [Session].

session.save_handler


This parameter specifies the method used by PHP to store and retrieve session variables. The default value is files, to indicate the use of session files, as described in the previous sections. The other values that this parameter can have are: mm to store and retrieve variables from shared memory, and user to store and retrieve variables with user-defined handlers. In Appendix D we describe how to create user-defined handlers to store session variables in a MySQL database.

session.save_path

This parameter specifies the directory in which session files are saved when the session.save_handler is set to files. The default value is /tmp. When implementing user-defined save_handler methods, the value of this parameter is passed as an argument to the function that opens a session.

session.use_cookies

This parameter determines if PHP sets a cookie to hold the session ID. Setting this parameter to 0 stops PHP from setting cookies and may be considered for the reasons discussed in the previous section. The default value is 1, meaning that a cookie stores the session ID.

session.name

This parameter controls the name of the cookie, GET attribute, or POST attribute that is used to hold the session ID. The default is PHPSESSID, and there is no reason to change this setting unless there is a name collision with another variable.

session.auto_start

With the default value of 0 for this setting, PHP initializes a session only when a session call such as session_start( ) or session_register( ) is made. If this parameter is set to 1, sessions are automatically initialized if a session ID is found in the request. Allowing sessions to autostart adds unnecessary overhead if session values aren't required for all scripts.

session.cookie_lifetime

This parameter holds the life of a session cookie in seconds and is used by PHP when setting the expiry date and time of a cookie. The default value of 0 sets up a session cookie that lasts only while the browser program is running. Setting this value to a number of seconds other than 0 sets up the cookie with an expiry date and time. The expiry date and time of the cookie is set as an absolute date and time, calculated by adding the cookie_lifetime value to the current date and time on the server machine.[2]

[2] The actual expiry of the cookie is performed by the browser, which compares the expiry date and time of the cookie with the client machine's date and time. If the date and time are incorrectly set on the client, a cookie might expire immediately or persist longer than expected.

session.cookie_path

This parameter sets the valid path for a cookie. The default value is /, which means that browsers include the session cookie in requests for resources in all paths for the cookie's domain. Setting this value to the path of the session-based scripts can reduce the number of requests that need to include the cookie. For example, setting the parameter to /winestore instructs the browser to include the session cookie only with requests that start with http://www.webdatabasebook.com/winestore/.

session.cookie_domain

This parameter can override the domain for which the cookie is valid. The default is a blank string, meaning that the cookie is set with the domain of the machine running the web server, and the browser includes the cookie only in requests sent to that domain.

session.cookie_secure

This parameter sets the secure flag of a cookie, which prevents a browser from sending the session cookie over nonencrypted connections. When this setting is 1, the browser sends the session cookie over a network connection that is protected using the Secure Sockets Layer, SSL. We discuss SSL in the next chapter and provide installation instructions in Appendix A. The default value of 0 allows a browser to send the session cookie over encrypted and nonencrypted services.

session.serialize_handler

This parameter sets up the method by which variables are serialized, that is, how they are converted into a stream of bytes suitable for the chosen session store. The default value is php, which indicates use of the standard PHP serialization functions. An alternative is wddx, which uses the WDDX libraries that encode variables as XML.

session.gc_probability

This parameter determines the probability that the garbage collection process will be performed when a session is initialized. The default value of 1 sets a 1% chance of garbage collection. See the discussion in the previous section for a full explanation of garbage collection.

session.gc_maxlifetime

This parameter sets the life of a session in number of seconds. The default value is 1440, or 24 minutes. Garbage collection destroys a session that has been inactive for this period. See the discussion in the previous section for a full explanation of garbage collection.

session.referer_check

This parameter can restrict the creation of sessions to requests that have the HTTP Referer: header field set. This is a useful feature if access to an application is allowed only by following a hypertext link from a particular page such as a welcome page. If the HTTP Referer header field doesn't match the value of this parameter, PHP creates a session, but the session is marked as invalid and unusable. The default value of a blank string applies no restriction.

session.entropy_file

PHP generates the session IDs from a random number seeded by the system date and time. Because the algorithm is known-it can be looked up in the PHP source code-it makes guessing session IDs a little easier. If this parameter is set to the name of a file, the first n bytes from that file (where n is specified by the session.entropy_length parameter) make the ID less predictable. The default value is left blank, meaning the default seeding method is used. One alternative is to use /dev/urandom, a special Unix device that produces a pseudorandom number.

session.entropy_length

This parameter is the number of bytes to use when generating a session ID from the file specified by session.entropy_file. The default value is 0, the required value when no entropy file is set.

session.cache_limiter

This parameter controls how responses can be cached by the browser. The default is nocache, meaning that PHP sets up the HTTP response to avoid browser caching. PHP sets the HTTP/1.1-defined header field Cache-Control to no-cache, the HTTP/1.0 header field Pragma to no-cache, and-for good measure-the Expires header field to Thu, 19 Nov 1981 08:52:00 GMT. Applications that use sessions-and even stateless web database applications-can be adversely affected when browsers cache pages. The other values allowed, private and public, allow responses to be cached. The distinction between private and public is apparent when a proxy server caches responses. See Appendix B for more details about HTTP caching.

session.cache_expire

This parameter is used when caching is allowed; it sets the expiry date and time of the response to be the current system time plus the parameter value in minutes. The default value is 180.

• In Web applications, it is frequently desirable to:
– Remember if a user has visited a site previously
– Remember the sequence of pages visited during a session
– Associate information with a user session
• Like a shopping basket
• To accomplish these things, need to have “stateful” connections between client and server
– That is, association information (state) with the connection
– HTTP was originally designed to not be stateful,leading to the addition of the Cookie mechanism
Cookies
• A mechanism for adding state to HTTP requests.
• Permits name, value pairs to be preserved across multiple HTTP requests.
• Basic approach:
– Server sends a Set-Cookie HTTP header in its response.
– Value of the header includes name, value pairs.
– The client stores the name, value pairs, and proactively sends them to the server (in the Cookie header) with every request thereafter.
– The Cookie protocol piggybacks on top of HTTP
• Information flow is in the reverse direction of most HTTP requests
client server
GET
200 OK // Set-Cookie: name=“value”; name=“value”
GET Cookie: name=“value”; name=“value”
Cookies in PHP
• How Cookies are set in PHP:
– Use built-in setcookie() function. Most simple form is:
– setcookie(name, value)
• It is also possible to specify when the cookie will expire, the URL path and domain for which it applies (defaults to those of request URI).
• Accessing Cookie values:
– $local_variable = $_COOKIE[name]
• To delete a cookie, use setcookie with the same cookie name, and an expiration value in the past.
Problems with Cookies
• Problems with Cookies
– Browsers can refuse to accept cookies.
– Additionally, it adds network overhead to send lots of information back and forth.
– There are also limits to the amount of information that can be sent
– Some information you just don’t want to save on the client’s computer.
PHP Sessions
• The solution: store session information on the server,and have the client only store an identifier for its information as stored on the server.
• The identifier is known as a session ID. The session ID is stored using a cookie (can be passed as a GET parameter as well)
• The server then uses the session ID to retrieve the information it has stored on the server.
• Session information is typically stored in files on theserver, though options
exist for using shared memory,and also writing your own handlers (e.g., to use a
database for storage)
Using Sessions in PHP
• To start a session:
– session_start()
– Creates a session identifier
– Session identifier is passed between client and server either as a Cookie, or in GET parameters
• Then, can create, access, and modify session variables:
– $_SESSION[session_var_name] = value;
– $_SESSION is only available once you call session_start()
– $local_variable = $_SESSION[session_var_name];
– Can check if session variable is set by using isset();
• To end a session:
– session_destroy();
Security of Session Data
• In general, cannot guarantee that session data will remain private
• Often, the session data files can be read by any web application on the same server
• The session ID can be grabbed by looking at the GET parameters (for GET-based passing of the session ID),or by eavesdropping the on-the-wire protocol (to get the
cookie with the session ID)
– If the session holds a password, someone can then “replay” the session ID back to the server
• Cookie data, though stored on the client side, are sent across the wire n-the-clear
– Client machines might be compromised, such as by malicious
software inadvertently downloaded, or by a virus

Cross-Site Scripting (XSS)


Cross-Site Scripting, abbreviated XSS, is another common security issue. This
issue is relevant whenever content that comes from the user will be redisplayed
on the screen. It is essentially when Javascript is injected into the HTML source.
We could for instance imaging a forum. On a forum users will be able to post
messages that will be displayed for other users. We want the users to be able
to format their messages and HTML is just perfect for that, right? There is
just a minor problem. . . Not all users are equally nice. The same kind of people that might want to drop the school's student table from the previous section
might also want to do something here. Speci_cally what they might want to
do is insert Javascript into the source. This might be for various purposes. It
could be simply for annoying by creating an in_nite loop of alert messages which
would force the user to shutdown the browser or it could be redirecting the users
to websites such as goatse or tubgirl (you might not want to check what it is
if you do not already know). Other, more so_sticated attacks, could be writing
a keylogger that logs and sends keystrokes (such as passwords) to an external
website or the injected Javascript could be retrieving the users' cookies (more
on the latter later in this tutorial).
XSS protection As a matter of fact, this is rather easy to protect yourself from as well.
PHP has a nifty function that is useful in this instance which is called htmlentities().
It will simply convert characters which have a meaning in HTML to their cor-
responding entities. For instance, HTML tags start with a lower-than sign and
that particular character will be converted to <. If you care about validation of your HTML (and you should!) then this will also help along with that.
We just have one problem. Our original example was a forum system and we wanted to give the users the opportunity to format their posts. However,the _x we just implemented removed this opportunity so we need to give them an alternate one. One with which we can control what they may do and not do.


A common feature is called bbcodes. It has a syntax very similar to HTML and
I am quite sure you are familiar with it if you have ever frequented any forum.
Be aware though! You might get some additional XSS security holes with some
tags.
A common bbcode tag is the URL tag. We could imagine that someone en-
tered [url=http://www.phpfreaks.com]The best PHP website[/url] which
would be converted to: <a href="http://www.phpfreaks.com">The best PHP
website</a>. At _rst glance there is no issue with allowing that. However,
URLs like javascript:alert('Hi') are also allowed and they will, obviously,
execute the entered Javascript. Similarly, in some lower versions of Internet Ex- plorer (IE6 and below) that URL format is allowed and will execute Javascript
so we have to take care of that as well.
For both the two before mentioned instances we might want to check that
the protocol is one we would allow. It would be better to create a white-list of
allowed protocols instead of creating a black-list of disallowed protocols. Simply select the protocols you want (e.g. http, https and ftp) and disallow all other.
Finally, this XSS cheatsheet might be useful to you. Both when learning
about XSS as well as testing that your application is secure.


Outside File Access


Normally, pages ending with .php will be handled forwarded to PHP by Apache and therefore the code will be hidden from the users. That the source code is hidden is one of the things that characterizes server-side scripting languages such as PHP. However, the PHP module or Apache might fail and the code might be displayed in plain unparsed text to the user. This is definitely not good. First of all, if the source is visible then it is much easier to find security issues in your application. Additionally, some scripts contain configuration files within the document root (the directory in which all files and sub-folders are publicly acessible from the outside world) and those will obviously not be parsed either thus presented to the user if they enter the filename into the URL. Personally I have experienced this before where I was on a small website and suddenly a misconfiguration of some sort displayed the source code to me. The website used a widely used application and I happened to know where the configuration file was. Sure enough, I was able to view that as well and from that I gathered the root password for the server (bad security practice to use the same password for multiple purposes and it is also bad security practice to use the root MySQL user). Being a nice person I did not do anything with it, but other people might not be as nice as I am and if you have the root password for a server then you can essentially do anything with it.
Another instance of this is the popular website Facebook which you have probably heard about in some way or another. What I explained before (server misconfiguration resulting in leaked source code) also has also happened to Face-book. Even big companies with people paid to configure the server apparently sometimes screws up and therefore it is necessary to take some security pre-cautions in order to prevent source leakage if something like that should everhappen (something Facebook apparently did not).
It all has to do with how you layout your directory structure. So, all files within the document root can be retrieved by the user. Therefore we might as well move everything else out of there so people cannot directly access it. This means we might have index.php and some static files such as CSS, Javascript and images laying inside the document root. We can even take it further and do so the only thing that is in index.php is the following:
<?php
require '../public_index.php';
?>
That particular snippet is the only thing the user will ever be able to see
should something happen. So we might have a directory structure that looks
like this:
/application
/controllers
/models
/views
/library
/public_html<-- document root
/index.php
/media
/images
/javascript
/css
/config
/cache
/tmp
/public_index.php
/logs
By laying out your files in this manner you will prevent that people will see
things they are not supposed to see. It is easy to do so there is no reason why
you would not.