Thursday, 29 November 2012

Apache Handlers - Running HTML as PHP

Apache handlers allow you to control what Apache will do with certain file types. When Apache sees a file, it has an action built in for that file type, and will perform that action.

If you wish Apache to do a different action, you will need to make a handler to tell Apache to perform that action. For example, if you use a file type that requires a special service to run it, such as a file with server side includes that is not named with a .shtml extension, you need to tell Apache to treat these files differently.

To get regular html pages to handle php code, you need to add this line to your htaccess file.

It is highly recommended that you never allow html pages to automatically handle php or shtml, because this forces all of your html pages to be processed by the server first. Instead, please rename your files to .php or .shtml whenever possible.

System Mime Type defaults
Handler Code File Extensions
application/x-hdf hdf
application/vnd.wap.wbxml wbxml
image/x-xbitmap xbm
image/x-icon ico
image/vnd.djvu djvu djv
application/x-troff-me me
application/perl pl plx ppl perl pm
application/x-tcl tcl
image/bmp bmp
text/x-sql sql
image/png png
text/x-log log
audio/x-realaudio ra
application/x-latex latex
application/x-director dcr dir dxr
text/rtf rtf
application/xhtml+xml xhtml xht
application/vnd.ms-powerpoint ppt
application/x-csh csh
image/svg+xml svg
application/x-troff-ms ms
image/x-rgb rgb
application/x-img img
image/jpeg jpeg jpg jpe
image/x-portable-pixmap ppm
text/plain asc txt
image/cgm cgm
application/x-sh sh
application/andrew-inset ez
application/vnd.wap.wmlscriptc wmlsc
text/x-registry reg
video/vnd.mpegurl mxu
image/ief ief
audio/x-pn-realaudio ram rm
image/x-xpixmap xpm
video/mpeg mpeg mpg mpe
text/tab-separated-values tsv
application/rdf+xml rdf
application/x-httpd-php phtml php php3 php4 php5 php6
x-conference/x-cooltalk ice
image/tiff tiff tif
text/richtext rtx
text/css css
application/ruby rb
application/x-wais-source src
application/xml xml xsl
application/voicexml+xml vxml
image/x-portable-graymap pgm
chemical/x-xyz xyz
model/iges igs iges
application/vnd.mif mif
application/mathml+xml mathml
application/x-ustar ustar
application/x-troff-man man
text/vbscript vbs
text/calendar ics ifb
chemical/x-pdb pdb
application/smil smi smil
application/srgs+xml grxml
image/x-portable-anymap pnm
application/x-shockwave-flash swf
audio/mpeg mpga mp2 mp3
video/x-sgi-movie movie
application/cgi cgi
application/x-cpio cpio
application/x-javascript js
text/x-setext etx
audio/basic au snd
text/sgml sgml sgm
application/x-tar tgz tar
application/vnd.mozilla.xul+xml xul
application/x-futuresplash spl
application/xslt+xml xslt
model/mesh msh mesh silo
application/mac-binhex40 hqx
text/vnd.wap.wml wml
image/x-cmu-raster ras
application/x-sv4cpio sv4cpio
audio/x-aiff aif aiff aifc
application/x-gtar gtar
audio/x-ms-wax wax
audio/x-ms-wma wma
image/x-xwindowdump xwd
application/x-cdlink vcd
application/msword doc
video/quicktime qt mov
application/x-bcpio bcpio
application/x-tex tex
text/x-config cnf conf
application/x-sv4crc sv4crc
application/x-dvi dvi
application/x-troff t tr roff
audio/x-mpegurl m3u
application/x-shar shar
audio/mp4 a-latm m4p m4a mp4
application/pdf pdf
application/mac-compactpro cpt
application/vnd.wap.wmlc wmlc
video/x-msvideo avi
application/ogg ogg
text/html html htm shtml
image/gif gif
audio/midi mid midi kar
application/x-pkcs7-crl crl
application/x-chess-pgn pgn
audio/x-pn-realaudio-plugin rpm
application/srgs gram
application/x-koan skp skd skt skm
image/vnd.wap.wbmp wbmp
application/x-netcdf nc cdf
model/vrml wrl vrml
application/x-httpd-php-source phps
application/vnd.ms-excel xls
application/postscript ai eps ps
application/x-texinfo texinfo texi
application/zip zip
image/x-portable-bitmap pbm
audio/x-wav wav
application/x-x509-ca-cert crt
application/oda oda
application/xml-dtd dtd
application/octet-stream bin dms lha lzh exe class so dll iso dmg
text/vnd.wap.wmlscript wmls
application/x-stuffit sit
 

Wednesday, 28 November 2012

Mysql - sql injection prevention


If you have ever taken raw user input and inserted it into a MySQL database there's a chance that you have left yourself wide open for a security issue known as SQL Injection.
SQL injection refers to the act of someone inserting a MySQL statement to be run on your database without your knowledge. Injection usually occurs when you ask a user for input, like their name, and instead of a name they give you a MySQL statement that you will unknowingly run on your database.

Below is a sample string that has been gathered from a normal user and a bad user trying to use SQL Injection. We asked the users for their login, which will be used to run a SELECT statement to get their information.

MySQL & PHP Code:
// a good user's name
$name = "timmy";
$query = "SELECT * FROM customers WHERE username = '$name'";
echo "Normal: " . $query . "<br />";

// user input that uses SQL Injection
$name_bad = "' OR 1'";

// our MySQL query builder, however, not a very safe one
$query_bad = "SELECT * FROM customers WHERE username = '$name_bad'";

// display what the new query will look like, with injection
echo "Injection: " . $query_bad;

Display:

Normal: SELECT * FROM customers WHERE username = 'timmy'
Injection: SELECT * FROM customers WHERE username = '' OR 1''

The normal query is no problem, as our MySQL statement will just select everything from customers that has a username equal to timmy.
However, the injection attack has actually made our query behave differently than we intended. By using a single quote (') they have ended the string part of our MySQL query
  • username = ' '
and then added on to our WHERE statement with an OR clause of 1 (always true).
  • username = ' ' OR 1
This OR clause of 1 will always be true and so every single entry in the "customers" table would be selected by this statement!



Sunday, 25 November 2012

Sending an email containing HTML from within a PHP page

The mail function in PHP allows you to send a plain text email in a single function call from within your script but please read the cautions at the end of this post before you do so!. How do you send out something in HTML format, though?

The mail function takes an additional (fourth) parameter of extra headers ... and one of the headers that you can use is a content-type: which lets you define the data type that's in the email - for example: text/html. There's an example showing how a message may be sent as both plain text and as HTML [here].

Email protocols are intrinsically line based, and 7 bit ... which means that what you send out needs to have a new line character at least once every 80 characters, and it cannot reliably contain high end (special) characters. In theory, that should not be a problem with HTML, but it could be a nuisance to have to split things down, and it could be more than a nuisance if you were sending out things like .jpg images. The solution here is to use a content-transfer-encoding header, with a base64 encoding - and of course to encode the data stream to suit. Full example [here].

Some Common Email Headers

The lines given here are examples of each of the most common types:

Supplied as parameters to the mail function:

To: Graham Ellis <graham@wellho.net>
Subject: A Demonstration of Email Headers

Supplied (if required) as part of the fourth (extra) parameter

From: Well House Consultants <info@wellho.net>
Reply-To: Lisa Ellis <lisa@wellho.net>
Cc: Gypsy <thedog@wellho.net>, Charlie <thecat@wellho.net>
Bcc: copybox@wellho.net, Audit <audittrail@wellho.net>
Date: Thu, 4 Nov 2010 14:30:27 +0000
Precedence: Bulk
Message-ID: 12345
In-Reply-To: wellho-5454
References: 12332, 11001, wellho-5420
MIME-Version: 1.0

A line like this sets up the document to be multipart if you wish:

Content-Type: multipart-alternative;boundary=00112233445566778899aabbccddeeff

The following can be supplied as part of the header or at the head of each section in a multipart email

Content-Type: text/html
Content-transfer-encoding: base64
Content-disposition: inline; filename="mypage.html"

The cautions at the end of this post

Before you start emailing from your server, consider the following:

a) Does the person your sending to REALLY want the email? (If it's confirming an order, the answer will be a resounding "YES", but if you're writing to tell him of your latest gizmo for sale, he might not be so keen!)

b) You're sending out an automated email from your server ... so it may look rather like other automated emails that people send out in bulk from servers (a.k.a. "spam") to many automated filters. How are you going to make your message special enough to be delivered?

c) Check that you are not providing an open emailing platform - that a user of your site is NOT able to enter a recipient's email address and message and use your server to send out unsolicited advertising material without your knowledge / approval. You really don't want to get yourself blacklisted! 

Filtering PHP form inputs

There's a vital need to validate user inputs in PHP - to make sure that users have put something sensible into the boxes on your forms. And there are multiple ways of doing this:

a) You can check the incoming strings against regular expressions. In the old days you may have used the ereg functions, but these days you would use preg functions - slighly more complex, but more powerful and quicker. And the ereg functions have been deprecated. Using regular expressions, you need to define yourself what a particular string should look like - so you have a great flexibility

b) From PHP 5.2, you can use the filter_var function to filter what's in a variable. It will return FALSE if there's no match, or the value that the variable contains if it does match. For example, "does $sample contain an integer?":


  $result = filter_var($sample, FILTER_VALIDATE_INT);
And (sample program [here]) you get results like:
  Looking at 404
  Integer result - 404
  int(404)

and
  Looking at Graham Ellis
  NOT an Integer
  bool(false)


c) If you're using the Zend Framework, there's a validation element available within each form component / widget and you can use that to check is the form have been validly filled in.

So - which of these should you use? If you're using the MVC (Model View Controller) approach, using the Zend Framework, then it's logical to use the functions that are provided by the framework. For major systems, some sort of framework is an excellent idea - whether you use Zend, one of the others, or routines that you write yourself (your own framework) is up to you. If you use your own, then you'll be coding one of the other two options, once only, within your own framework setup as part of your standard.

filter_var is an excellent tool to use for checking specific types - email addreses, integers, IP addresses and the like; they're coded into PHP's functions so you san save yourself a great deal of work in formulating regular expressions, and you know they'll be updated and maitained with future releases as standards may change, rather than you having to update regular expressions yourself.

Saturday, 24 November 2012

Tasting OOP Concepts


If you have not yet entered the realm of Object Oriented Programming, then you are at a disadvantage, and you are falling behind fast.

OOP is essentially a method of programming with the use of classes, or Objects, which tie like things together, remove the need for repetition of code and perform the basic tasks of production very simply. Objects are essentially classes that collect a bunch of functions together and wrap them in a wrapper that can be reused over and over again without the need to rewrite functionality or procedures every time you need to do something.

Procedural Programming works by following a routine from the top to the bottom of each page as the server reads every file on your server. With OOP, there could be one or two objects being instantiated, which, in turn could instantiate a few, a hundred or a thousand other objects which could all perform certain tasks depending on variables passed into the objects. OOP is faster, simpler, easier to debug, uses less server resources, less code, is faster loading and more logical to work with once you figure out the basic principles. Go OOP - It changed my development style forever.

A small hint to make your PHP site much faster

If you've dug through your code to the best of your abilities, and optimized it as far as you can.  If your site is still slow, there are a few things you can do.  The first is install a byte code cacher like eAccelerator or APC.  Both of them store the compiled version of a PHP file in memory, which saves the time it would take for the server to compile the code.  While this is not a GREAT savings, it can be dramatic.  You can save between 5% and 25% off load times depending on your code.  The downside to this is two fold.  First, you must have root level access to the server to compile in the cacher.  The second problem is that they use memory.  And lots of it!  The average Joomla configuration will consume about 15 megs of ram.  PER APACHE CHILD.  One Apache child can serve one request at a time.  You can see how this will quickly limit the amount of traffic you can receive.  The other alternative it install a page cacher, such as my Joomla component.  By storing generated pages between requests, these programs can cut down page load times by over 90% or more.  Don't forget that you don't want to put a band aid on a broken bone, but if all else fails, these methods do work.

In general:

Match your hardware to your load, NOT to your generation time.  To upgrade to a dual Xeon server because your pages take 4 seconds to load on that Celeron is nothing short of a waste of money.  Poor code will run poorly no matter what hardware you put it on!  Optimize your code so that it loads fast on that Celeron (or shared host for that matter), and upgrade to the dual Xeon when your demand requires it!  You can do a lot with a little bit of processing power.  And don't let a host tell you that you need a dedicated server because your site is using too many resources.

Friday, 23 November 2012

General Issues with AJAX

AJAX is growing very fast and that is the reason that it contains many issues with it. We hope with the passes of time they will be resolved ab AJAX will be ideal for web applications. We are listing down few issues which AJAX has as a challenge.
Complexity is increased
  • Server side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic
  • Page developers must have JavaScript technology skills
AJAX-based applications can be difficult to debug, test, and maintain
  • JavaScript is hard to test - automatic testing is hard
  • Weak modularity in JavaScript
  • Lack of design patterns or best practice guidelines yet
Toolkits/Frameworks are not mature yet
  • Most of them are in beta phase
No standardization of the XMLHttpRequest yet
  • Future version of IE will address this
No support of XMLHttpRequest in old browsers
  • Iframe will help
JavaScript technology dependency & incompatibility
  • Must be enabled for applications to function
  • Still some browser incompatibilities
JavaScript code is visible to a hacker
  • Poorly designed JavaScript code can invite security problem

AJAX - A Closer Look


AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
Conventional web application trasmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.

Technologies Used in AJAX

JavaScript

  • Loosely typed scripting language
  • JavaScript function is called when an event in a page occurs
  • Glue for the whole AJAX operation

DOM

  • API for accessing and manipulating structured documents
  • Represents the structure of XML and HTML documents

CSS

  • Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript

XMLHttpRequest

  • JavaScript object that performs asynchrous interaction with the server

Thursday, 22 November 2012

Conditional Logic


Conditional Logic is all about asking "What happens IF ... ". When you press a button labelled "Don't Press this Button - Under any circumstance!" you are using Conditional Logic. You are asking, "Well, what happens IF I do press the button?"

You use Conditional Logic in your daily life all the time:
"If I turn the volume up on my stereo, will the neighbours be pleased?"

"If spend all my money on a new pair of shoes, will it make me happy?"
"If I study this course, will it improve my web site?"

Conditional Logic uses the "IF" word a lot. For the most part, you use Conditional Logic to test what is inside of a variable. You can then makes decisions based on what is inside of the variable. As an example, think about the username again. You might have a variable like this:
$User_Name = "My_Regular_Visitor";
The text "My_Regular_Visitor" will then be stored inside of the variable called$User_Name. You would use some Conditional Logic to test whether or not the variable $User_Name really does contain one of your regular visitors. You want to ask:
"IF $User_Name is authentic, then let $User_Name have access to the site."
In PHP, you use the "IF" word like this:
if ($User_Name = = "authentic") {

//Code to let user access the site here;
}

Without any checking, the if statement looks like this:
if ( ) {
}
You can see it more clearly, here. To test a variable or condition, you start with the word "if". You then have a pair of round brackets. You also need some more brackets - curly ones. These are just to the right of the letter "P" on your keyboard (Well, a UK keyboard, anyway). You need the left curly bracket first { and then the right curly bracket } at the end of your if statement. Get them the wrong way round, and PHP refuses to work. This will get you an error:
if ($User_Name = = "authentic") }

//Code to Let user access the site here;
{

And so will this:
if ($User_Name = = "authentic") {

//Code to Let user access the site here;
{

The first one has the curly brackets the wrong way round (should be left then right), while the second one has two left curly brackets.
In between the two round brackets, you type the condition you want to test. In the example above, we're testing to see whether the variable called $User_Name has a value of "authentic":
($User_Name = = "authentic")
Again, you'll get an error if you don't get your round brackets right! So the syntax for the if statement is this:
if (Condition_or_Variable_to_test) {

//your code here;
}

In the next lesson, we'll use if statements to display an image on the page.
We'll use the print statement to "print out" HTML code. As an example, take the following HTML code to display an image:
<IMG SRC =church.jpg>
Just plain HTML. But you can put that code inside of the print statement:
print ("<IMG SRC =images/church.jpg>");
When you run the code, the image should display. Of course, you'll need an image called church.jpg, and in a folder called images.

What a PHP variable depicts?


A variable is just a storage area. You put things into your storage areas (variables) so that you can use and manipulate them in your programmes. Things you'll want to store are numbers and text.
If you're ok with the idea of variables, then you can move on. If not, think of them like this. Suppose you want to catalogue your clothing collection. You enlist two people to help you, a man and a woman. These two people are going to be your storage areas. They are going to hold things for you, while you tally up what you own. The man and the woman, then, are variables.
You count how many coats you have, and then give these to the man. You count how many shoes you have, and give these to the woman. Unfortunately, you have a bad memory. The question is, which one of your people (variables) holds the coats and which one holds the shoes? To help you remember, you can give your people names! You could call them something like this:
mr_coats
mrs_shoes
But it's entirely up to you what names you give your people (variables). If you like, they could be called this:
man_coats
woman_shoes
Or
HimCoats
HerShoes
But because your memory is bad, it's best to give them names that help you remember what it is they are holding for you. (There are some things your people balk at being called. You can't begin their names with an underscore (_), or a number. But most other characters are fine.)
OK, so your people (variables) now have name. But it's no good just giving them a name. They are going to be doing some work for you, so you need to tell them what they will be doing. The man is going to be holding the coats. But we can specify how many coats he will be holding. If you have ten coats to give him, then you do the "telling" like this:
mr_coats = 10
So, the variable name comes first, then an equals sign. After the equals sign, you tell your variable what it will be doing. Holding the number 10, in our case. (The equals sign, by the way, is not really an equals sign. It's called an assignment operator. But don't worry about it, at this stage. Just remember that you need the equals sign to store things in your variables.)
However, you're learning PHP, so there's something missing. Two things, actually. First, your people (variables) need a dollar sign at the beginning (people are like that). So it would be this:
$mr_coats = 10
If you miss the dollar sign out, then your people will refuse to work! But the other thing missing is something really picky and fussy - a semi-colon. Lines of code in PHP need a semi-colon at the end:
$mr_coats = 10;
If you get any parse errors when you try to run your code, the first thing to check is if you've missed the semi-colon off the end. It's very easy to do, and can be frustrating. The next thing to check is if you've missed out a dollar sign. But back to our people (variables).
So the man is holding ten coats. We can do the same thing with the other person (variable):
$mrs_shoes = 25;
So, $mrs_shoes is holding a value of 25. If we then wanted to add up how many items of clothes we have so far, we could set up a new variable (Note the dollar sign at the begining of the new variable):
$total_clothes
We can then add up the coats and the shoes. You add up in PHP like this:
$total_clothes = $mr_coats + $mrs_shoes;
Remember, $mr_coats is holding a value of 10, and $mrs_shoes is holding a value of 25. If you use a plus sign, PHP thinks you want to add up. So it will work out the total for you. The answer will then get stored in our new variable, the one we've called $total_clothes. You can also add up like this:
$total_clothes = 10 + 35;
Again, PHP will see the plus sign and add the two together for you. Of course, you can add up more than two items:
$total_clothes = 10 + 35 + 7 + 38 + 1250;
But the idea is the same - PHP will see plus signs and then add things up. The answer is then stored in your variable name, the one to the left of the equals sign.

Quick Cooking For PHP


Before you can write and test your PHP scripts, there's one thing you'll need - a server! Fortunately, you don't need to go out and buy one. In fact, you won't be spending any extra money. That's why PHP is so popular! But because PHP is a server-sided scripting language, you either have to get some web space with a hosting company that supports PHP, or make your computer pretend that it has a server installed. This is because PHP is not run on your PC - it's executed on the server. The results are then sent back to the client PC (your computer).
Don't worry if this all sounds a little daunting - we've come across an easier way to get you up and running. We're going to be using some software called Wampserver. This allows you to test your PHP scripts on your own computer. It installs everything you need, if you have a Windows PC. We'll explain how to get it installed in a moment, and where to get it from. But just a word for non-windows users.

Apple Users
If you have OS X, then try these sites to get up and running with PHP:
http://www.onlamp.com/pub/a/mac/2001/12/07/apache.html
http://www.entropy.ch/software/macosx/php/
What you're doing here is getting the apache server up and running, so that you can run PHP scripts offline. Pay particular attention to where files are stored, and to the "localhost" address.
Linux Users
There are quite a few sites out there to help Linux users get up and running with the Apache server and PHP. Here are three sites that are worth checking out:
http://en.wikipedia.org/wiki/LAMP_(software_bundle)
http://www.php-mysql-tutorial.com/wikis/php-tutorial/installing-php-and-mysql.aspx
http://www.phpfreaks.com/tutorials/12/0.php
If you know any better ones, we'd be interested in hearing from you!
Windows Users
OK, back to Wampserver and Windows. First, you need to download the software. You can get it from here (this site is nothing to do with ours, by the way):
Be sure to click the link for Presentation, as well as the link for Downloads. The Presentation page shows you how to install the file.

Wednesday, 21 November 2012

Dynamic vs. Static Web pages


The "Hello, World" example we chose would certainly not require you to use PHP. That's because it is static,meaning its display will always remain the same. But what if you wanted to greet the world in any number of ways? Say, for example, "Bonjour, World!", or "Yo, World!" and so on.

Since HTML tags are purely descriptive they cannot function as a variable. Nor can they convey even the
simplest of uncertainty such as a "Bonjour" or a "Yo". You need a command language to handle variability in a web page. Based on either a conditional statement or direct user input, a command language can generate the "static" HTML necessary to correctly display a Web page's content.

Let us reconsider example #3. This time we want to let the user decide how to greet the world:
Example 4: PHP embedded within HTML revisited!
<?php print $greeting, ", "; ?> World!

From the above example, $greeting is assigned a value, and together with the comma and the word "World!", this value is sent to the browser. Dynamic Web page design, however, is more than just about inserting variables. What if you wanted not only to greet the world in French, but also to present the page using the colors of the French flag? Both a Web page's structure as well as its content can be customized. This means dynamic Web page programming can also entail on-demand Web page building.    No static, here!