Wednesday, March 24, 2010

Daniel Roth and the future of money

Daniel Roth and the future of money

Saturday, March 20, 2010

Cool Or Hot? Linux really making your coffee, live a linux coffee machine

Too bad it's only for professional use the HGZ Linux based coffee machine. I'd love to have on of these. A Dream come true. The Linux coffee maker.
Embedded Linux on a coffee machine, touch screen. Build on Qt framework.
Have Linux brew your coffee, finally a stable cup of coffee.
Demo-ed at the Embedded World in Nurmberg Germany by Qt:

And some images from the presentation of Qt:







Source: http://www.handlewithlinux.com

Friday, March 19, 2010

Building a Windows Phone 7 Twitter Application using Silverlight

Building a “Hello World” Windows Phone 7 Application

First make sure you’ve installed the Windows Phone Developer Tools CTP – this includes the Visual Studio 2010 Express for Windows Phone development tool (which will be free forever and is the only thing you need to develop and build Windows Phone 7 applications) as well as an add-on to the VS 2010 RC that enables phone development within the full VS 2010 as well.
After you’ve downloaded and installed the Windows Phone Developer Tools CTP, launch the Visual Studio 2010 Express for Windows Phone that it installs or launch the VS 2010 RC (if you have it already installed), and then choose “File”->”New Project.”  Here, you’ll find the usual list of project template types along with a new category: “Silverlight for Windows Phone”. The first CTP offers two application project templates. The first is the “Windows Phone Application” template - this is what we’ll use for this example. The second is the “Windows Phone List Application” template - which provides the basic layout for a master‑details phone application:
image
After creating a new project, you’ll get a view of the design surface and markup. Notice that the design surface shows the phone UI, letting you easily see how your application will look while you develop. For those familiar with Visual Studio, you’ll also find the familiar ToolBox, Solution Explorer and Properties pane.
image For our HelloWorld application, we’ll start out by adding a TextBox and a Button from the Toolbox. Notice that you get the same design experience as you do for Silverlight on the web or desktop. You can easily resize, position and align your controls on the design surface. Changing properties is easy with the Properties pane. We’ll change the name of the TextBox that we added to username and change the page title text to “Hello world.”
image
We’ll then write some code by double‑clicking on the button and create an event handler in the code-behind file (MainPage.xaml.cs).
image
We’ll start out by changing the title text of the application. The project template included this title as a TextBlock with the name textBlockListTitle (note that the current name incorrectly includes the word “list”; that will be fixed for the final release.)  As we write code against it we get intellisense showing the members available.  Below we’ll set the Text property of the title TextBlock to “Hello “ + the Text property of the TextBox username:
image
We now have all the code necessary for a Hello World application.  We have two choices when it comes to deploying and running the application. We can either deploy to an actual device itself or use the built‑in phone emulator:
image
Because the phone emulator is actually the phone operating system running in a virtual machine, we’ll get the same experience developing in the emulator as on the device. For this sample, we’ll just press F5 to start the application with debugging using the emulator.  Once the phone operating system loads, the emulator will run the new “Hello world” application exactly as it would on the device:
image
Notice that we can change several settings of the emulator experience with the emulator toolbar – which is a floating toolbar on the top right.  This includes the ability to re-size/zoom the emulator and two rotate buttons.  Zoom lets us zoom into even the smallest detail of the application:
image
The orientation buttons allow us easily see what the application looks like in landscape mode (orientation change support is just built into the default template):
image
Note that the emulator can be reused across F5 debug sessions - that means that we don’t have to start the emulator for every deployment. We’ve added a dialog that will help you from accidentally shutting down the emulator if you want to reuse it.  Launching an application on an already running emulator should only take ~3 seconds to deploy and run.
Within our Hello World application we’ll click the “username” textbox to give it focus.  This will cause the software input panel (SIP) to open up automatically.  We can either type a message or – since we are using the emulator – just type in text.  Note that the emulator works with Windows 7 multi-touch so, if you have a touchscreen, you can see how interaction will feel on a device just by pressing the screen.
image
We’ll enter “MIX 10” in the textbox and then click the button – this will cause the title to update to be “Hello MIX 10”:
image
We provide the same Visual Studio experience when developing for the phone as other .NET applications. This means that we can set a breakpoint within the button event handler, press the button again and have it break within the debugger:
image

Building a “Twitter” Windows Phone 7 Application using Silverlight

Rather than just stop with “Hello World” let’s keep going and evolve it to be a basic Twitter client application.
We’ll return to the design surface and add a ListBox, using the snaplines within the designer to fit it to the device screen and make the best use of phone screen real estate.  We’ll also rename the Button “Lookup”:
image
We’ll then return to the Button event handler in Main.xaml.cs, and remove the original “Hello World” line of code and take advantage of the WebClient networking class to asynchronously download a Twitter feed. This takes three lines of code in total: (1) declaring and creating the WebClient, (2) attaching an event handler and then (3) calling the asynchronous DownloadStringAsync method.
In the DownloadStringAsync call, we’ll pass a Twitter Uri plus a query string which pulls the text from the “username” TextBox. This feed will pull down the respective user’s most frequent posts in an XML format. When the call completes, the DownloadStringCompleted event is fired and our generated event handler twitter_DownloadStringCompleted will be called:
image
The result returned from the Twitter call will come back in an XML based format.  To parse this we’ll use LINQ to XML. LINQ to XML lets us create simple queries for accessing data in an xml feed. To use this library, we’ll first need to add a reference to the assembly (right click on the References folder in the solution explorer and choose “Add Reference):
image
We’ll then add a “using System.Xml.Linq” namespace reference at the top of the code-behind file at the top of Main.xaml.cs file:
image
We’ll then add a simple helper class called TwitterItem to our project. TwitterItem has three string members – UserName, Message and ImageSource:
image
We’ll then implement the twitter_DownloadStringCompleted event handler and use LINQ to XML to parse the returned XML string from Twitter.  What the query is doing is pulling out the three key pieces of information for each Twitter post from the username we passed as the query string. These are the ImageSource for their profile image, the Message of their tweet and their UserName. For each Tweet in the XML, we are creating a new TwitterItem in the IEnumerable<XElement> returned by the Linq query. 
We then assign the generated TwitterItem sequence to the ListBox’s ItemsSource property:
image
We’ll then do one more step to complete the application. In the Main.xaml file, we’ll add an ItemTemplate to the ListBox. For the demo, I used a simple template that uses databinding to show the user’s profile image, their tweet and their username.
<ListBox Height="521" HorizonalAlignment="Left" Margin="0,131,0,0" Name="listBox1" VerticalAlignment="Top" Width="476">
<ListBox.ItemTemplate>
        <DataTemplate>
           <StackPanel Orientation="Horizontal" Height="132">
              <Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
              <StackPanel Width="370">
                 <TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" />
                 <TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
              </StackPanel>
           </StackPanel>
        </DataTemplate>
     </ListBox.ItemTemplate>
</ListBox>
Now, pressing F5 again, we are able to reuse the emulator and re-run the application. Once the application has launched, we can type in a Twitter username and press the  Button to see the results. Try my Twitter user name (scottgu) and you’ll get back a result of TwitterItems in the Listbox:
image
Try using the mouse (or if you have a touchscreen device your finger) to scroll the items in the Listbox – you should find that they move very fast within the emulator.  This is because the emulator is hardware accelerated – and so gives you the same fast performance that you get on the actual phone hardware.

Summary

Silverlight and the VS 2010 Tools for Windows Phone (and the corresponding Expression Blend Tools for Windows Phone) make building Windows Phone applications both really easy and fun. 
At MIX this week a number of great partners (including Netflix, FourSquare, Seesmic, Shazaam, Major League Soccer, Graphic.ly, Associated Press, Jackson Fish and more) showed off some killer application prototypes they’ve built over the last few weeks.  You can watch my full day 1 keynote to see them in action. I think they start to show some of the promise and potential of using Silverlight with Windows Phone 7.  I’ll be doing more blog posts in the weeks and months ahead that cover that more.

Source: weblogs.asp.net

Installation of Drupal and Ubercart 2.x

Installation of Drupal and Ubercart 2.x
This article is a quick installation reference for Drupal, the required Drupal modules, and Ubercart. Ubercart is not a standalone e-commerce application, but it comes as a Drupal module. That means you have to first install Drupal and all the required Drupal modules on a server with the minimum requirements, before installing Ubercart. The topics that we will discuss in this article by George Papadongonas and Yiannis Doxaras, authors of Drupal E-commerce with Ubercart 2.x, are:
  • Minimum requirements for Ubercart installation
  • Creating a local environment using a web server, PHP, and a database server
  • Using a commercial hosting service
  • Downloading and installing Drupal and Ubercart
  • Using UberDrupal, an Ubercart installation profile
You don't have to be an expert programmer or a system administrator in order to complete the following process. We'll first give you a brief explanation of the underlying technologies, and then we'll continue with a step-by-step guide. At the end of this article, you'll have the online store installed on your local or remote machine and you'll be ready to make all the required customizations to the frontend and the backend, depending on your needs.

Minimum requirements for Ubercart installation

In order to successfully install and use your online store, your system must meet the following requirements:
  • Operating system: Drupal works fine in almost every operating system. Actually, you can transfer your Drupal installation from one operating system to another within minutes and no customization is required at all. All you have to do is to move the files and the database without altering any configuration files. For example, you can install Drupal on your local Windows or Mac computer, do all the customizations there, and then upload it to a Linux server to go live.
  • Web server: The web server is the software that accepts HTTP requests from browsers and delivers web pages to the users of our site. The most popular web server is Apache and we'll use it for our installation. It's secure, extensible, fast, and easy to customize. If you're not an expert in another web server, there is no reason to think of any other solution, because most of the available information and support is about Apache.
  • Database: The purpose of the database is to store, organize, manage, and retrieve all the data of our website in a structured way. When referring to data, we mean not only the content that you put in your pages, but also every piece of information that Drupal uses for all its functions. In this book, we're using MySQL as a database. Today, it's the #1 open source database, and it's used in millions of websites and applications, from small personal web pages to enterprise systems with millions of users.The MySQL database of a basic installation contains about 50 tables and every new installed module creates one or more new tables. If you check your database after the installation of Ubercart, you'll find that there are 100 tables in your database. These tables contain data such as pages, products, images, categories, orders, payments, caching information for your pages, theming information, comments from your visitors, menus, user information, and so on.
  • PHP: PHP is a scripting language, ideal for web development. It began as a small personal project, but soon became a very popular scripting language. Drupal is written in PHP, so it's absolutely necessary and there is no alternative to it. Some PHP extensions are needed for our installation. We'll mention them briefly here, so you can consult your hosting provider or examine your local system to check that everything is fine. The easiest way to check your PHP parameters is to use phpinfo. It's a function that returns information about the PHP environment on your server. All you have to do is to create a blank file named phpinfo.php in your server and insert the following code using a text editor:
    <?php
    phpinfo ();
    ?>
    This is a small PHP script that runs the phpinfo function and displays the results on your screen. If you browse to phpinfo.php, you'll see a page with your PHP configuration.
The basic PHP requirements are:
  • PHP memory requirements: 1 6 MBs are enough for basic sites; however, 64 MBs are recommended for more complex installations.
  • GD2 library: GD2 is an image manipulation library for PHP. Ubercart needs this library, so if we want to put images to our products, it has to be installed.
  • Register Globals: This is actually a depreciated PHP feature, but some hosting providers with old systems still use it. It's a security risk, so it has to be disabled for Drupal to install.
  • Safe mode: Drupal 6 doesn't support PHP's safe mode, because it causes problems to file uploads, so it also has to be turned off.
Installation of Drupal and Ubercart 2.x
This article is a quick installation reference for Drupal, the required Drupal modules, and Ubercart. Ubercart is not a standalone e-commerce application, but it comes as a Drupal module. That means you have to first install Drupal and all the required Drupal modules on a server with the minimum requirements, before installing Ubercart. The topics that we will discuss in this article by George Papadongonas and Yiannis Doxaras, authors of Drupal E-commerce with Ubercart 2.x, are:
  • Minimum requirements for Ubercart installation
  • Creating a local environment using a web server, PHP, and a database server
  • Using a commercial hosting service
  • Downloading and installing Drupal and Ubercart
  • Using UberDrupal, an Ubercart installation profile
You don't have to be an expert programmer or a system administrator in order to complete the following process. We'll first give you a brief explanation of the underlying technologies, and then we'll continue with a step-by-step guide. At the end of this article, you'll have the online store installed on your local or remote machine and you'll be ready to make all the required customizations to the frontend and the backend, depending on your needs.

Minimum requirements for Ubercart installation

In order to successfully install and use your online store, your system must meet the following requirements:
  • Operating system: Drupal works fine in almost every operating system. Actually, you can transfer your Drupal installation from one operating system to another within minutes and no customization is required at all. All you have to do is to move the files and the database without altering any configuration files. For example, you can install Drupal on your local Windows or Mac computer, do all the customizations there, and then upload it to a Linux server to go live.
  • Web server: The web server is the software that accepts HTTP requests from browsers and delivers web pages to the users of our site. The most popular web server is Apache and we'll use it for our installation. It's secure, extensible, fast, and easy to customize. If you're not an expert in another web server, there is no reason to think of any other solution, because most of the available information and support is about Apache.
  • Database: The purpose of the database is to store, organize, manage, and retrieve all the data of our website in a structured way. When referring to data, we mean not only the content that you put in your pages, but also every piece of information that Drupal uses for all its functions. In this book, we're using MySQL as a database. Today, it's the #1 open source database, and it's used in millions of websites and applications, from small personal web pages to enterprise systems with millions of users.The MySQL database of a basic installation contains about 50 tables and every new installed module creates one or more new tables. If you check your database after the installation of Ubercart, you'll find that there are 100 tables in your database. These tables contain data such as pages, products, images, categories, orders, payments, caching information for your pages, theming information, comments from your visitors, menus, user information, and so on.
  • PHP: PHP is a scripting language, ideal for web development. It began as a small personal project, but soon became a very popular scripting language. Drupal is written in PHP, so it's absolutely necessary and there is no alternative to it. Some PHP extensions are needed for our installation. We'll mention them briefly here, so you can consult your hosting provider or examine your local system to check that everything is fine. The easiest way to check your PHP parameters is to use phpinfo. It's a function that returns information about the PHP environment on your server. All you have to do is to create a blank file named phpinfo.php in your server and insert the following code using a text editor:
    <?php
    phpinfo ();
    ?>
    This is a small PHP script that runs the phpinfo function and displays the results on your screen. If you browse to phpinfo.php, you'll see a page with your PHP configuration.
The basic PHP requirements are:
  • PHP memory requirements: 1 6 MBs are enough for basic sites; however, 64 MBs are recommended for more complex installations.
  • GD2 library: GD2 is an image manipulation library for PHP. Ubercart needs this library, so if we want to put images to our products, it has to be installed.
  • Register Globals: This is actually a depreciated PHP feature, but some hosting providers with old systems still use it. It's a security risk, so it has to be disabled for Drupal to install.
  • Safe mode: Drupal 6 doesn't support PHP's safe mode, because it causes problems to file uploads, so it also has to be turned off.


Creating a local environment using a web server, PHP, and a database server

When you start building your online store, it's better to do it on a local environment. There, you can do all the tests, experiment, try different options and solutions, and correct all the problems in a closed and secure environment before going live.
You have two basic choices: manually install and configure all the components, or use a complete web server package.
The advantage of the first choice is that you have the absolute control of the entire process, but its disadvantage is that it's time consuming and sometimes difficult to configure it right. We prefer the second method, because it's fast, easy, and reliable.
We recommend XAMPP (http://www.apachefriends.org/en/xampp.html), a free distribution package for Linux, Windows, and Mac OS X, containing Apache, PHP, MySQL, OpenSSL for Secure Sockets Layer support, ProFTPD FTP server (FileZilla in the Windows version), and phpMyAdmin for the administration of MySQL databases. It's free, easy to install and uninstall, needs little or no configuration, easy to use, and very fast and stable.
So let's start the installation process:
  1. Go to http://www.apachefriends.org/en/xampp.html. This is the download page for XAMPP. You'll see there that there are four basic distributions for Linux, Windows, Mac OS X, and Solaris. Here, we'll show you how to install it for Windows, but the process is almost the same for every other operating system.
  2. Select the appropriate distribution for your operating system. You will be transferred to a new page, where you can see specific details, frequently asked questions, some basic installation instructions, and configuration options. Click on the name of the file and select OK to download the file on your computer. It takes only a few minutes, depending on your Internet connection.
  3. When the download is completed, double-click on the file in your computer to open it and start XAMPP Setup Wizard. Leave the default settings and click on Next> until the installation process is finished.
    If you check the root folder of your hard disk, you'll now see a new folder named xampp. Inside, there are all the files of the package. Among all the others there is one application file named xampp-control, which opens the control panel for XAMPP.
  4. Double-click on xampp-control and open it. The Control Panel opens in a new window. It has a very simple layout, showing the three main applications (Apache, MySQL, and FTP), an indicator about the status for each one of them, and a button to turn them ON or OFF. If everything is OK, you'll see green indicators showing that all XAMPP components are Running.
  5. Now it's time to test that everything works. Using your browser, open the following URL: http://localhost. Select your language and you'll be transferred to the home page of XAMPP. On the left, there is a menu for all the basic actions. You can check the status of the applications, check the security of your installation and your pages, read online documentation about Apache, PHP, and MySQL, test and see the source code of some very interesting demo applications, and use some very useful tools like phpMyAdmin for the administration of MySQL databases and Webalizer for Web Stats.
  6. Before you download Drupal, you have to create a blank MySQL database. This database will be used by Drupal to store all the data of your site. So, from the left menu of the XAMPP home page, select phpMyAdmin, located at the bottom of the page. It will open in a new window. Under the label Create new database, enter the name of your database and click on the Create button to continue. If you haven't changed anything, the default MySQL username is root and there is no password.
That's it! Now your local environment is ready to install Drupal. If you're not going to use a commercial hosting service immediately, skip the next section and go to the Downloading and installing Drupal section.

Using a commercial hosting service

If you're in a hurry, or you just don't want to mess about with local web server installations, you can find a commercial hosting service and host your online store there. Nowadays, most companies support Drupal without any problem, because it's very popular and there is high demand for it. Look for a provider with reliability and speed of access, with plenty of web space and bandwidth. You need FTP access to upload the required files, and enough privileges to create a new database and to edit .htaccess and php.ini files.
Go to http://drupal.org/hosting to find a list of companies that provide Drupal hosting services.When you select your hosting company and sign up, they'll give you a username and password and a link to access the Control Panel of your package and manage your website. In this section, we'll work with cPanel, but the process is almost identical for the other GUI control panels such as Plesk.
Before installing Drupal, you have to create a database. We'll show you here how to create a MySQL database, but a similar process is followed for a PostgreSQL database.
  1. Browse to the URL of your cPanel (usually http://www.mysite.com/cpanel). Enter your username and password.
  2. You'll be redirected to the home page of cPanel. Select MySQL® Databases from the menu.
  3. Enter a name for your database and click on the Create Database button.
  4. Enter a username and a password and click on the Create User button.
  5. Check the ALL Privileges box and click on the Add Users to Your Databases button.
  6. Don't forget to take a note of the database name, the username, and the password; we'll use them during the Drupal installation.

Downloading and installing Drupal

No matter if you decided to use a hosting service or to set up a local server; the process for installing Drupal is almost the same. There are only minor differences, which will be mentioned as we proceed with the installation.
The first step is to download, install, and customize Drupal. Click on Latest Release from the home page (http://drupal.org) for immediate download of the latest version of Drupal, or browse to http://drupal.org/project/drupal to check all the versions available. The installation file comes as a compressed file under the format drupal-6.x.tag.gz. If you are a Linux or Mac user you can immediately open the file, but if you are using Windows you may need a program like 7-Zip (http://www.7-zip.org).
Unzipping the file will create a Drupal-6.x folder in your machine. If you check this folder, you'll see that it has more folders in it and that it contains all the files of the Drupal installation.
If you go to sites and select the default folder of our Drupal installation, you'll find only a file there, named default.settings.php. Copy this file to settings.php and remember not to delete the original file, because we need both files in order to install Drupal. Uncheck the read only property of settings.php file if you're working locally, or change the permissions to 666 with the file manager, if you're using a hosting service, so that the file is writable for Drupal installer.
Now, it's time for action; the installation begins! Browse to the root folder of your installation. You'll see the first screen of Drupal installer. Select Install Drupal in English. If you want to install Drupal in another language, you have to first download the appropriate language package from Drupal.org and follow the instructions.
There is a possibility of facing an error message at this stage. It shows up when register_globals is enabled. This is a security risk for your website and you have to solve it before continuing. You have to create a file named php.ini in you root folder and add the following line:
register_globals = Off
This disables register_globals and now you can safely continue. If this doesn't work, you may not have enough privileges in your hosting account and you will have to contact your provider to fix it.
Drupal installer verifies that your system meets all the basic requirements, and then you proceed to the next screen. There, you have to write the database name, username, and password that you inserted when you created the database. (You DID take a note of them, didn't you?) Click on Save and continue and you'll see the installer progress bar. When all the files are installed, it's time for the basic configuration screen.
Here, you have to insert the site name and the primary site e-mail address.
Then, you have to create the administrator account. The administrator is a "super user" who has all the privileges and has access to every operation of your website. You have to keep the administrator credentials in a safe place. If you lose them, it's possible to lose the control of your website. Insert the administrator's username, e-mail address, and password.
In the last section of the page, you have to select time zone, decide if you want clean URLs enabled or disabled (enabling clean URLs makes Drupal create shorter and more search engine-friendly URLs), and choose if your system will check for updates automatically. IIS servers need an extra module to create clean URLs. For more information, read http://drupal.org/node/3854.
Click on Save and continue and you're done! Your first Drupal website is ready!
Now you can see the first page of your new site. Of course, it's not very pretty yet, and there is no actual content in it yet, but we took our first big step.

Downloading and installing all the required Drupal modules

Now we have a functional Drupal site. Can we proceed with Ubercart installation? Not yet! First we have to install a few more Drupal modules.
Drupal third-party modules are not part of the core, and they are created by individual programmers or companies. They add extra functionality to Drupal or they enhance an existing functionality. You can see a full list of all the available Drupal modules at http://drupal.org/project/Modules. Actually, the only module that is necessary for Ubercart to work is Token.
As we can read at the home page of this module, http://drupal.org/project/token:
Tokens are small bits of text that can be placed into larger documents via simple placeholders, like %site-name or [user]. The Token module provides a central API for modules to use these tokens, and expose their own token values. Note that Token module doesn't provide any visible functions to the user on its own, it just provides token handling services for other modules. For Drupal 6, the Token module provides a "Token Actions" module which can be enabled separately. This provides several "actions" for the Drupal core Actions/Trigger modules to use that take advantage of the Token replacement functionality.
Ubercart uses Tokens in several functions, like confirmation messages or client e-mails.
The next bunch of modules is required for image support. We want our products to have nice images, and in several sizes. We also wish to enable our clients to magnify these images. Drupal does not provide any out-of-the-box image support, so Ubercart uses not only one, but six different modules. The installation of all these modules seems like a time-consuming and complicated process, but they upgrade Drupal, providing new capabilities required for our e-shop to function. The modules that we have to install are:
  • Content Construction Kit (CCK): This is the most important contributed module for Drupal. It allows the user to create new content types and to add new fields to existing content types, using only the administrator's interface, without the need of any programming knowledge. This module's page is http://drupal.org/project/cck.
  • FileField: This module is an add-on for CCK. It creates a field for file uploads. This module's page is http://drupal.org/project/filefield.
  • ImageField: This module is also an add-on for CCK. It creates an image field. This module's page is http://drupal.org/project/imagefield.
  • ImageAPI and ImageAPI GD2: ImageAPI uses PHP's GD2 image manipulating library. It's extremely useful, because it allows us to take basic actions, such as resizing, rotation, adding watermarks, cropping, or converting to another format directly from the browser, without the need to invest in an image-editing application. This module's page is http://drupal.org/project/imageapi.
  • ImageCache: This module all ows us to create predefined standards for images. Ubercart uses ImageCache to adjust all the images of the products that we upload to specific preset dimensions and dynamically generates the files for product catalog, thumbnails, and shopping cart photos. This module's page is http://drupal.org/project/imagecache.
  • Thickbox: This module brings all the functionality of the jQuery plugin Thickbox (http://jquery.com/demo/thickbox) to Drupal. Clicking on an image loads the full-size version of it in a new layer, without reloading the whole page. It provides automated integration with all of the aforementioned modules. This module's home page is http://drupal.org/project/thickbox.
  • Google Analytics: This module adds the Google Analytics web statistics solution to your website. Not only does it collect general stats such as number of visitors, most popular pages, or bounce rate, but it also tracks transaction data and item data. E-commerce tracking and analytics is a very useful tool that helps you to analyze the performance of your business and to manage your marketing strategy. This module's page is http://drupal.org/project/google_analytics.
  • Views: This module pro vides the site administrator with a web interface that allows easy presentation of the website content. This module's page is http://drupal.org/project/views .
To install all of these modules, first you have to download them from their home page. Then create the sites/all/modules folder, unzip the files, and copy the whole directories there. Finally, browse to http://localhost/admin/build/modules, select these modules from the (long and overwhelming) list and click on save.

Downloading and installing Ubercart

Now that we finished with Drupal installation and have enabled all the required Drupal modules, it's finally time to install Ubercart. Browse to http://www.ubercart.org/downloads and download the latest Ubercart 2.x version for Drupal 6. This also comes as a compressed tar.gz file, so you have to uncompress it just as you did for Drupal 6.
Then, you have to copy it to sites/all/modules directory, as we did with the previous modules. Actually, Ubercart is not just one module, but rather a package of modules. So now, we have plenty of new options on our module page. Some of them are required (Ubercart-core) and some of them are optional (Ubercart-core (optional) and Ubercart-extra, Ubercart-fulfillment, and Ubercart-payment). You don't have to install every single Ubercart module. Spend some time now and think what you need and what you don't. Of course, if you change your mind you can return here and add or remove features, depending on your needs.

Required modules

The most important modules of the Ubercart package are:
  • Cart: Required for a functioning shopping cart
  • Conditional Actions: The conditional actions are required to configure shipping and taxes
  • Order: Required for order management and fulfillment
  • Product: Creates a product content type for your store
  • Store: Required for store setup and management

Optional core modules

You can install a basic but functioning version of Ubercart without using these modules, but in most cases they are needed for a competitive and attractive store:
  • Attribute: Using attributes, you can create a customizable product that differentiates based on specific characteristics, such as size or color.
  • Catalog: This module creates a product catalog with categories and subcategories.
  • File downloads: This module is required if you want to sell downloadable products, such as music or video files.
  • Payment: This module is required for receiving payments at your store.
  • Report: This module creates reports about your store, orders, products, and clients.
  • Roles: A role can give different privileges to different clients.
  • Shipping: This module is required for shipping management.
  • Taxes: This module is required for tax management.

Extra modules

These extra modules add even more functionality to Ubercart, transforming your store into a competitive selling point:
  • Cart Links: This module lets you create specialized links to purchase products from other nodes.
  • Google Analytics: This module installs Google Analytics for Ubercart.
  • Product kit: Using this module you can combine two or more products and sell them together as a product kit.
  • Stock: This module is required if you need to manage the stock levels of your products.
  • Payments: This group of modules adds new payment methods and integrates with payment gateways:
    • Authorize.net: This module integrates your store with the Authorize.net gateway.
    • Credit card: This module allows you to accept credit cards. Pay attention, because this method doesn't offer any kind of encryption for security.
    • CyberSource: This module integrates your store with the CyberSource payment gateway.
    • Google Checkout: This module integrates your store with the Google Checkout payment gateway.
    • PayPal: This module integrates your store with the PayPal gateway.
    • Test Gateway: This payment method exists only for testing purposes, as it doesn't actually processes payments.
  • Fulfillment: This group of modules add new shipping methods:
    • Flatrate: This module adds a flatrate quoting method to your store.
    • U.S. Postal Service: This module integrates your store with the USPS to automatically calculate shipping rates.
    • UPS: This module integrates your store with UPS to automatically calculate shipping rates.
    • Weight Quote: This module adds a weight quote method to calculate shipping based on the total weight of the order.

Using UberDrupal, an Ubercart installation profile

When we create an installation profile, we actually give specific instructions to Drupal installer on what extra modules to install, what language to use, what themes to enable, or what settings to use after the installation. It's a very powerful tool with great potential, as it allows developers to create predefined packages of Drupal, created for a specific purpose, for example blogs, image galleries, magazines, or e-shops. The only disadvantage of this procedure is that it's not fully automated, as you still have to first download all the required modules and then run the installation profile.
A few months ago, a new installation profile was created named UberDrupal. It automatically installs all the core Ubercart and required Drupal modules, which we mentioned earlier. It also allows some basic pre-configuration and creates a store with the default settings.
If you want to use this installation profile, you first have to download all the required Drupal modules and all the Ubercart modules, and put them inside the ../sites/all/modules folder.
Then, download UberDrupal from http://drupal.org/project/uberdrupal, and put it inside the profiles directory. Now, when you run the installer you'll see two options for Select an installation profile: Drupal or UberDrupal. Selecting the second option enables the UberDrupal installation profile.
The starting steps of this installation are identical with the standard Ubercart installation. We choose our language and we enter the details of our database. After the installation, we are able to do some basic configuration of our website, right from the installer. The whole process is not perfect yet, but it's very convenient, especially for novice users.

Summary

In this article, we talked about the technologies that are required for Drupal and Ubercart to work. We discussed how to create a local server to host your installation, or how to use and customize a package from a professional hosting company. Then we showed you how to install Drupal and all the required modules for Ubercart. We also examined the Ubercart package and did a brief analysis of the modules contained in it.
Finally, we presented you with UberDrupal, a Drupal profile for easier and faster installation of Ubercart.


Source: www.packtpub.com

Thursday, March 18, 2010

PHP Security

1. Introduction

Writing PHP applications is pretty easy. Most people grasp the syntax rather quickly and will within short time be able to produce a script that works using tutorials, references, books, and help forum forums like the one we have here at PHP Freaks. The problem is that most people forget one of the most important aspects that one must consider when writing PHP applications. Many beginners forget the security aspect of PHP. Generally, your users are nice people, they will do as they are told and you will have no problem with these people whatsoever. However, some people are not quite as nice. Some people are outright malicious and are seeking to do damage on your website. They will scrutinize your application for security flaws and exploit these holes. Many times the beginner programmer did not know that these things would even be a problem and therefore it might be a problem to fix the holes. In this tutorial we will look at some of these issues so you can learn how to deal with them, and better yet, prevent them. Obviously I will not promise you that by following this tutorial you will never get successfully attacked. As you become bigger you will also become a bigger and therefore more interesting target – something we have experienced ourselves here at PHP Freaks.
On the next page we will look at how we should do our error reporting.
This tutorial is available for download as a PDF file here. That version can be read offline or printed.

2. Error reporting

Error reporting is a good thing, right? It gives you valuable insight into why your application failed. It gives you useful information such as what happened and where it happened. This information is essential in order to fix the bug. However, you might not be the only one who is interested in knowing why your application failed. By giving the user the details from the errors and/or exceptions thrown by PHP you are giving valuable insight into how your application works. Apart from the source itself, this is one of the most valuable intelligence the attacker might gather when looking for vulnerabilities in your application. Therefore, you should never output the error to the screen when your application is running in a production environment (the live setting in which your application runs when it is available for public use). In your development environment (e.g. on your local computer) it is perfectly fine to output the errors because there are nobody but you to see them and it is easier than having to check an error log when something fails unexpectedly.
So what should you do when you have launched your new killer app? Bugs might still appear and you need the before-mentioned information in order to fix them. What you can do, and should do, is write the errors into a log file. Actually, PHP does insert all errors into a log file on the server by default. However, if you are on shared hosting then you will most likely not have access to that file and it will therefore be necessary to write it into your own file. There are a couple of php.ini directives that are relevant to our problem:
  • display_errors this directive controls whether PHP errors should be sent to the screen. In a production environment this should always be turned off.
  • error_reporting this directive controls which errors that should be reported. You should set this to E_ALL and you should fix all issues that appear by doing this.
  • log_errors this controls whether errors should be logged to a file. I would recommend that you always turn this on.
  • error_log this is the path of the file errors should be written to. This is only applies if log_errors is turned on obviously.
Here is how I would recommend that you configure the before-mentioned four directives:
Table 2.1: Recommended Configuration
Directive name: Production: Development:
display_errors Off On
error_reporting E_ALL E_ALL
log_errors On On
error_log varies varies
How error_log should be configured obviously depends on how your directory structure is setup (more on that later in this tutorial).
2.1. Setting the directives
There are a number of different ways you can set the directives in order to achieve the most secure and efficient error handling as I talked about before. If you already know how to do that then you can skip this section.
First and foremost there is changing the values directly in php.ini. However, this is only possible if you are the administrator of the server so for many people this is not an option.
Apache has some configuration files called .htaccess where you can configure Apache directives for the particular folder (and sub-folders) the file is located in. Some hosts do not allow you to use this, but if you can then the PHP module has a directive called php_flag which allows you to set PHP directives. You simply do it like this:
php_flag directive_name directive_value
Note that you cannot use constants like E_ALL so you will have to use their numeric values. E_ALL’s value is currently 8191, but that might change in the future so you should check the new value if you update a major version. You can see the constants regarding error reporting at any time here.
So for our production environment you can do this:
php_flag display_errors off
php_flag error_reporting 8191
php_flag log_errors on
php_flag error_log /home/someone/logs/php_errors.log
A third option is to use to use PHP’s ini_set() function. That function takes two arguments: the name of the directive to set and its new value. You can use the constants here. There is a function called error_reporting() which you can use to set the error reporting instead.

3. SQL injections

One of the most common problems with security in web applications is SQL injection. To begin with I will present this comic for you:

The comic clearly illustrates the problems with SQL injection. If you do not get it, do not worry, you will in just a moment.
SQL injections work by injecting SQL into the queries you have already written in your script. Often you will pass some sort of variable data to your queries; this data might be influenced by user input. In the above comment we might imagine that the school had a query that looks something like this:
  1. $sql = “INSERT INTO Students (name) VALUES (’{$_POST['student_name']}’)”;
The above snippet works. As long as users input data that conforms to an expected format. Now, the mother in the comic did not provide expected data, rather she injected an entire additional query into the existing query. Let’s take a look at how the query looks when we enter the string given by the mother:
  1. INSERT INTO students (name) VALUES (‘Robert’); DROP TABLE Students;–’)
(Note: PHP does not support stacking queries with all DBMSs. MySQL in particular)
As you probably know, a semi-colon ends a query and most times it is actually required, but PHP just adds it automatically if you omit it. Therefore, by closing the string and finishing the query by entering the closing parenthesis and a semi-colon we will be able to add an additional query that drops the student table. The two hyphens at the end make whatever comes after it a comment, so whatever remaining characters that might have been in the original query will simply be ignored.
It should not take too much brain power to figure out why this is a bad thing. Malicious users will basically be able to execute any kind of queries they would like to. This can be done for various purposes. It could be retrieving confidential information or destroying your data just to name a few.
3.1. Protecting your script from SQL injections
Fortunately, protecting yourself from SQL injections is rather easy. It is just a matter of calling a single function which make data safe for use in a query. How you should do this depends on which PHP extension you are using. Many people use the regular mysql extension, so let us start with that one. That particular extension has a function called mysql_real_escape_string(). Let us take a look at how that one works with a simple example that illustrates its usage:
  1. <?php
  2. $db = mysql_connect(‘localhost’, ‘username’, ‘password’);
  3. mysql_select_db(’school’, $db);
  4. $studentName = mysql_real_escape_string($_POST['student_name'], $db);
  5. $queryResult = mysql_query(“INSERT INTO Students (name) VALUE (’{$studentName}’)”);
  6. if ($queryResult) {
  7. echo ‘Success.’;
  8. }
  9. else {
  10. echo ‘Insertion failed. Please try again.’;
  11. }
  12. ?>
As you see, doing it is incredibly easy yet many people fail to do this and only find out when it is too late. Other extensions support something called prepared statements. An example of a such extension is PDO (PHP Data Objects). Let us take a look at how that works:
  1. <?php
  2. $db = new PDO(‘mysql:host=localhost;dbname=school’, ‘username’, ‘password’);
  3. $stmt = $db->prepare(‘INSERT INTO Students (name) VALUES (?)’);
  4. try {
  5. $stmt->execute(array($_POST['student_name']));
  6. echo ‘Success.’;
  7. }
  8. catch(PDOException $e) {
  9. echo ‘Insertion failed. Please try again.’;
  10. }
  11. ?>
If you have many fields you need to use in your query then it might be a little difficult remembering the order of all these different question marks which act as place holders for the data. An alternate syntax is using named parameters. In our case it would look like this:
  1. <?php
  2. $db = new PDO(‘mysql:host=localhost;dbname=school’, ‘username’, ‘password’);
  3. $stmt = $db->prepare(‘INSERT INTO Students (name) VALUES (:name)’);
  4. try {
  5. $stmt->execute(array(‘name’ => $_POST['student_name']));
  6. echo ‘Success.’;
  7. }
  8. catch(PDOException $e) {
  9. echo ‘Insertion failed. Please try again.’;
  10. }
  11. ?>
Obviously, in our case this would not have any benefits, but as I said, if you have many parameters then you might find that more useful. There can be other reasons why using prepared statements would be useful, but I will leave that to research for yourself.
The mysqli (MySQL improved) extension has support for prepared statements as well, so if you are using that then check out its documentation to see the syntax.
The golden rule regarding this is that nothing is to be trusted and all data should be escaped.
Additionally, I mentioned earlier that users should not get information from error messages. Not only is it irrelevant, but it may also be information that may aid people with malicious purposes. You may sometimes be told that you should add or die(mysql_error()) to the end of your query calls to functions like mysql_query(). However, you should not do that. By doing that you are no longer using PHP’s error and exception handling functionality and you remove the opportunity to control whether errors should be displayed or not. In my opinion the best solution would be to use PHP’s exceptions. If you do not want to do that then at least do something like or trigger_error('Query failed: '. mysql_error()). By doing that you are utilizing PHP’s built-in functionality and you will be able to use the methods discussed under Error Reporting. Moreover, ending script execution with die() is simply bad practice. You will not be able to give the user a proper error page and you will not be able to do any cleaning up for the rest of the script.

4. Cross Site Scripting

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. Specifically 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 infinite 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 sofisticated 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).
4.1. 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 corresponding entities. For instance, HTML tags start with a lower-than sign and that particular character will be converted to &lt;. 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 fix 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 entered
[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 first 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 Explorer (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.

5. 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 accessible 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 Facebook. Even big companies with people paid to configure the server apparently sometimes screws up and therefore it is necessary to take some security precautions in order to prevent source leakage if something like that should ever happen (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:
  1. <?php
  2. require ‘../public_index.php’;
  3. ?>
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.

6. Remote file inclusion

Remote file inclusion attacks (sometimes abbreviated RFI) is a vulnerability many people probably do not know of, but it is a very serious issue that also must be addressed. As the name implies, it is when remote files are included, but what exactly does that? Let us look at an example:
  1. <?php
  2. $page = isset($_GET['page']) ? $_GET['page'] : ‘home’;
  3. require $page . ‘.php’;
  4. ?>
This is a very basic front controller that will forward the request to whatever file that should be responsible for that particular request.
Imagine that at http://example.com/malice.php a file exists and our script is located at http://site.com/index.php. The attacker will do this request: http://site.com/index.php?page=http://example.com/malice. This file will get executed when it is included and it will a write a new file to the disk. This file could be a shell which would allow people to execute commands to the terminal from it as well as other things they should not bea ble to. Another thing the attacker can do is set page to http://example.com/malice.php? (note the ending question mark). That will make whatever follows it part of the query string and therefore ignored by the server the file is getting included from. Why this is a security issue should be pretty obvious. People should definitely not be able to execute whatever commands they want on our server, so how can we prevent them?
There are a couple of php.ini directives you can use to prevent this:
  • allow_url_fopen this directive is set to on by default and it controls whether remote files should be includable.
  • allow_url_include this directive is set to off by default and was introduced in PHP 5.2. It controls whether the include(), require(), include_once() and require_once() should be able to include remote files. In versions below PHP 5.2 this was also controlled by allow_url_fopen. Furthermore, if allow_url_fopen is set to off then this directive will be ignored and set to off as well.
Basically those two directives will enable you to set the required security settings you will need. Again, no data that is not from the inside of your system should be trusted. You must validate user input and ensure that people will not enter malformed or unexpected data.
One of our other administrators, Thomas Johnson, has written a small tutorial about how you can use Apache to block RFI attacks called Preventing remote file include attacks with mod rewrite. You might want to check that out as well if you are concerned about RFI vulnerabilities.

7. Session security

Sessions and cookies are also two things where you have to watch out. Although they cannot breach your application’s security they can be used to compromise user accounts.
When you are using sessions, PHP will most often store a cookie on the client computer called PHPSESSID (can be changed by you). This cookie will hold a value, a session identifier, which is associated with some sort of data on the server. If the user has a valid session ID then the data associated with the session will get into the $_SESSION super-global array. Sessions can also be transferred via the URL. In that case it would be something like ?PHPSESSID=id_here.
7.1. Stealing the cookies
Imagine that you have a key for a vault in your bank. If you have the key then you can get whatever is in the vault. The session ID works a bit like that. However, your key for your vault can be stolen and similarly can the session ID of your users (including you) be stolen or intercepted.
For the record, just because I used a vault/key analogy then it does not mean that you should put secret or important data of some sort in your sessions.
Earlier we talked about XSS and I mentioned briefly that it could be used to steal people’s cookies. That is the most common way cookies are stolen. This cookie could be PHPSESSID (or whatever you may have renamed it to. When you steal a session ID and try to use it again it is called session fixation. So… if you can get a valid session ID and that session is used for something like authentication then you will essentially be logged in as that user. Obviously that is not a good thing – especially not if the user is high ranking with administrative privileges.
7.2. Issues with shared hosting
Most people host their website on what is called shared hosting. It is basically when there are multiple people having their websites hosted on a single server. On a server with a Linux operating system session data will by default be stored in the /tmp directory. It is a directory that stores temporary data and it will obviously have to be readable and writable by everyone. Therefore, if your session data is stored in there, which it is by default, then the other users can find it if they look hard enough. This poses the same security issues as with cookies being stolen using XSS.
7.3. Preventing session fixation
Now that we have talked a bit about how the session ID can be stolen then let us talk a bit about how we can minimize the risk session fixation.
One thing we can do is to change the session ID often. If we do that then the chance that the intercepted session ID will be valid will be greatly minimized if that ID changes often. We can use one of PHP’ built-in functions called session_regenerate_id(). When we call this function the session ID will be, no surprise, regenerated. The client will simply be informed that the ID has changed via an HTTP response header called Set-Cookie.
If you are using PHP 5.2+ then you can tell the browser that Javascript should not be given access to the cookie using a flag called httponly. You can set this flag using the php.ini directive called session.cookie_httponly or you can use the session_set_cookie_params() function.
Regarding the issue with the shared hosts, the fix is simple: store the data where only you have access. You can use the directive called session.save_path to set another path for storing them. You can also store them in a database, but then you will have to write your own handler using the function called session_set_save_handler()

8. Cross-site request forgery

Cross-site request forgery (CSRF) is when you trick the user into making a request they have never made. Imagine that in your application it is possible to delete users like this: /user/delete/Joe. That would delete the user with the username “Joe”. A malicious user might place this bit of HTML on his website:
  1. <img src=“http://example.com/user/delete/Joe” height=“1″ width=“1″ />
This will basically trick the user into making a request to that page without them knowing it. Obviously only people who are logged in as administrators should be able to call this URL and therefore it will fail for most users. However, if a logged in administrator goes to the page where the above piece of HTML is located then the request will be successfully completed and “Joe” will be gone.
How can we prevent this? Well, in this case we could simply ask the admin to verify the action with his password before performing it. Yes, I know, this is kind of like Windows Vista’s UAC (User Account Control) that people claim is incredibly annoying and prompts them to verify their action every fifth millisecond, but sometimes you will, unfortunately, have to add just a little amount of nuisance in order to keep your application safe.
Had the account come from a form then we could simply require that the information (in the previous case the username) be submitted using post and read it like $_POST['username']. However, this adds only a minimum of extra security. More sophisticated attacks than the above could just as easily trick the user into performing a POST request instead GET. We could use the “enter your password” method like before, but we could also use another kind of token. Imagine this form:
  1. <?php
  2. session_start();
  3. $_SESSION['token'] = uniqid(md5(microtime()), true);
  4. ?>
  5. <form action=“/delete-user.php” method=“post”>
  6. <input type=“hidden” name=“token” value=”<?php echo
  7. $_SESSION['token'] ?>/>
  8. Username: <input type=“text” name=“username” />
  9. <button type=“submit”>Delete user</button>
  10. </form>
Here we have added a hidden field called token and stored its content in a session. On the next page we can do something like this:
  1. <?php
  2. session_start();
  3. if ($_POST['token'] !== $_SESSION['token']) {
  4. die(‘Invalid token’);
  5. }
  6. // form processing here
  7. ?>
We simply check that it is a valid token and we have then successfully ensured that the request did in fact come from the form.

9. Directory traversal

Imagine the same script we used when talking about RFI attacks:
  1. <?php
  2. $page = isset($_GET['page']) ? $_GET['page'] : ‘home’;
  3. require $page . ‘.php’;
  4. ?>
We will just say that this particular file is stored in the following path: /home/someone/public_html/index.php. The attacker could then do: index.php?page=../secret
That would give us /home/someone/public_html/secret.php which would otherwise have been accessible. I am sure you could think of more dangerous situations than this particular one.
There are a couple of ways you could prevent this with. First of all you could have an array of valid pages, e.g.:
  1. $pages = array(
  2. ‘home’,
  3. ‘login’,
  4. ‘logout’,
  5. // etc.
  6. );
  7. if (!in_array($page, $pages) {
  8. die(‘Invalid page’);
  9. }
Another thing you could do is check that the requested file matches a particular format:
  1. $file = str_replace(‘\\’, ’/‘, realpath($page . ’.php’));
  2. if (!preg_match(‘%^/home/someone/public_html/[a-z]+\.php$%’, $file)) {
  3. die(‘Invalid page’);
  4. }
  5. include $file;
Basically you need to verify that the entered information is valid and conforms to what you expected.

10. Conclusion

So… In this tutorial we have talked about a lot of different security issues that you should consider and we have also talked about how much information about your application you should reveal to your users.
Remember, no information can be trusted so you need to validate, filter and/or escape both input and output that does not come directly from your system.

Source: phpplanet.org