Sunday, 29 December 2013

Google Bug at least in chrome

I opened chrome today and I think i found a bug / strange feature in google chrome


in the search box i pressed space and the logo and search box disappeared.


Now I have no idea why this is supposed to do this i'm classifying it as a bug though

Tuesday, 24 December 2013

Mac OsX - Screen Sharing

I just accidentally found an absolutely fantastic function on Mac OsX - "Screen Sharing" I had downloaded multiple products and hadn't found one that would let me remote control my mac mini from my mac book air, iphone or ipad easily and effectively.

Well I was on the mac mini configuring the remote access to it once again and I notice on the left of the finder window my laptop.  Now I thought to my self I wonder what shares exist on my laptop.  So I click on the icon and then I notice a share screen button I had never noticed before. Mainly because I had not enabled it on my mac mini but had for some reason on my laptop.  So I clicked the button and was looking at my laptop screen.

A quick search on the help menu for "Share" and the third results is "Share the screen of another Mac" a few click later (Thank you Apple) and i'm in the preferences section tick a box and bingo I can access my Mac Mini sweet.

What a wonderful easy solution, and most importantly Found it on Christmas Eve so bonus Present for me.

Saturday, 7 December 2013

Absolute Tae Kwon-Do Association - website

I've recently had to move the ATKDA website from the excellent web site CMS at http://www.squarespace.com to a new free hosting provider.  This is because the ATKDA is a non-profit organisation.  I must admit that I loved the SquareSpace interface and system and would like to thank them for the IT Support help they have given us over the last year. Unfortunately the annual charge is just too much for our organisation at this time.  So I have moved the blog to a free blogger account and have pointed the domain to the new location.

So please check out the new ATKDA website.

The ATKDA is a Member of the International Tae Kwon-Do Council (ITC) a new governing body designed to unite all versions of Tae Kwon-Do

Sunday, 27 October 2013

So is it worth upgrading to Mavericks?

Well I would have to say yes, I have two machines my oldest machine is a mac mini 2011 and it has definitely become a more responsive machine since upgrading, but the best bit is my Mac Book Air a 2012 model.  I had bought Black Ops for it when it came out and to say that I was depressed by the performance I received we are talking a game that felt that I was getting 15-30 Frames per second and was not very responsive.  After the upgrade of my OS to Mavericks I decided to test BlackOps to see if there are any benefits from the new OS and my initial response would have to be a resounding YES.  The game is still sluggish I would think that I’m getting 30-50 FPS now and it definitely is playable.  Though not blinding fast it is enjoyable to be able to play this game,  I used to play it on a PC with a couple of bad graphics cards,  I was getting 30 -50 fps at that time so it feels the same as at that time.

So if you haven't upgraded to Mavericks whats stopping you,  I downloaded the Upgrade and ran it with no backups made of my computer and vola two new faster machines.

Saturday, 17 August 2013

Password Security how long will a hacker take to crack your passwords


I was sitting today thinking about those password length checkers you see that tell you if your password is weak or strong. So i decided to make one that tells how long a hacker should take to crack it.

https://github.com/IrishAdo/PasswordStrength 

Ok so the way that this works is that it tries to work out how long it would take a hacker to crack a password and show that length rather than weak or strong like most do.  The problem is that according to Moore's Law - Computers should double in speed every 18 months.  So any plugin that you would build would have to take this into account.  Of course I did I added a

The length of time that it might take is based on brute forcing all possible values so you have to work out how many possible values exist for each character.  For example if you have a 6 digit number for a password then for each character there is 10 possible values per digit.  meaning that there are 10^6 possible combinations or in other words 1 million possibilities.

Add a character [a-z] and you can add 26 extra per character bringing the total per character to 36,  Add the 26 Upper case characters [A-Z] and our total now sits at 62.  Add the most common symbols on a keyboard and you can bring that number up an additional 36 characters to 98.  So a six character password that had one of each of these types would be a massive 96^6 or 96*96*96*96*96*96 = 782,757,789,696 or 782.8 trillion possible combinations.

Now your thinking wow that a lot of possibilities that would take ages for a hacker to crack.  Well using the password "aA1!23" which uses all of the possible types.  Well it would take a hacker with a modern PC just less than 12 hours to brute force that password.  A modern PC would be able to brute force 20 million possibilities per second.  In 12 hours thats 864,000,000,000 possible passwords checked.  You need to make your passwords be long enough that we are talking in the millions of years to brute force.

Wait, I mentioned processing 20 million passwords per second.  Well what about in a few years time how many possibilities might a hacker be able to process.  Ok if we assume that 20million per second is correct for 2013, then using Moore's Law we can look back to 1970 and forward to 2031.

Potential number of passwords that can be checked per second.
Date# per second# per hour
1 Jan 19700.04144 per hour
2 Jul 19710.07252 per hour
31 Dec 19720.15540 per hour
1 Jul 19740.301080 per hour
31 Dec 19750.602160 per hour
30 Jun 19771.194284 per hour
30 Dec 19782.388568 per hour
29 Jun 19804.7717,172 per hour
29 Dec 19819.5443,344 per hour
29 Jun 198319.0768.652 per hour
28 Dec 198438.15137,340 per hour
28 Jun 198676.29274,644 per hour
28 Dec 1987152.59549,324 per hour
27 Jun 1989305.181,098,648 per hour
27 Dec 1990610.352.1 Million per hour
26 Jun 19921,220.704.3 Million per hour
26 Dec 19932,441.418.6 Million per hour
26 Jun 19954,882.8117.2 Million per hour
25 Dec 19969,765.6334.4 Million per hour
25 Jun 199819,531.2568.8 Million per hour
25 Dec 199939,062.50137.6 Million per hour
24 Jun 200178,125.00276.2 Million per hour
24 Dec 2002156,250.00552.4 Million per hour
23 Jun 2004312,500.001.1 Billion per hour
23 Dec 2005625,000.002.2 Billion per hour
23 Jun 20071,250,000.004.4 Billion per hour
22 Dec 20082,500,000.008.8 Billion per hour
22 Jun 20105,000,000.0017.6 Billion per hour
22 Dec 201110,000,000.0035.2 Billion per hour
21 Jun 201320,000,000.0070.4 Billion per hour <- when written
21 Dec 201440,000,000.00140 Billion per hour
20 Jun 201680,000,000.00280 Billion per hour
20 Dec 2017160,000,000.00560 Billion per hour
20 Jun 2019320,000,000.001.1 Trillion per hour
19 Dec 2020640,000,000.002.2 Trillion per hour
19 Jun 20221,280,000,000.004.4 Trillion per hour
19 Dec 20232,560,000,000.008.9 Trillion per hour
18 Jun 20255,120,000,000.0017.9 Trillion per hour
18 Dec 202610,240,000,000.0036 Trillion per hour
17 Jun 202820,480,000,000.0072 Trillion per hour
17 Dec 202940,960,000,000.00144 Trillion per hour
17 Jun 203181,920,000,000.00288 Trillion per hour

Now remember the 782.8 trillion possible combinations  in our previous example well of we look at 2019 then we can see that it would only take an hour to crack that password  by 2031 only 10 seconds.  Of course this doesn't take into account other updates to cracking techniques.

Sunday, 14 July 2013

A big Plus 1 for PHP Mess Detector a must tool for all php developers


I've been programming PHP for many years and some bad programming did creep in even though I try to learn and evolve my programming style as often as possible. When leaving my last job they got a company to come in and go over my projects to see if the company would out source the development of my projects.

This was the first time that I had ever had a proper code review of any work that I had done for the company. I was interested in what a outside developer would think of my work. I wasn't to scared that they would go "arrrgh what a pile of ...", so I thought of it as getting some constructive criticism of the projects. The first thing i have to say is in that one day I learnt so much it was amazing the first thing that the guy did was run my project through PHP mess detector (PHPMD.org).

PHP mess detector is a brilliant program it really does detect mess in your coding style. We have all done it when writing complex functions that have many nested if statements and loops. PHPMD scores each file and function for you, too many functions in a php class and your starting to get into the realm of messy code. To many conditions in your function with nested loops and your getting into complex functions which should be split up into multiple functions to make each part easier to read and the initial function easier to read as well as there is less code in it.

It is surprising how reformatting your code to pass PHPMD actually makes for more readable code. Go get it and run it against your projects then try to clean up your files to make them pass the tests. After one or two files you will understand what I mean.

Wednesday, 22 May 2013

Google have finally fixed blogger but not google games

Since the new version of Blogger.com I've had this problem where the web application would crash on my browser (Chrome) when I published a blog post. it was a real pain in the neck as I had to continually edit the address bar to get the home page to load. I was getting a white layer covering the screen and it wouldn't let me do anything on the page.  I'm glad to say after such a long time that the bug seems to have disappeared.

Of course now that I'm saying this it will probably happen when I attempt to publish this page.

My hopes for iTunes 12, fingers crossed

I'm hoping that the next version of iTunes allows purchase to the cloud as an option.  I recently bought the West Wing complete box set in HD.  That's 150 episodes at 1.5Gb each which all wanted to down load straight away.  

I had to cancel all the downloads then get Apple support to remove them from my download queue so that I can now download them as and when I want.


Having the option or even having itunes be a bit more intelligent when you purchase content wouldn't be a hard feature to ass to the next version of iTunes.  iTunes needs to detect that you have purchased multiple items that exceed a user defined level say 2Gb a movie.  So it detects that you have added several Gigabytes to the download queue and displays a popup that lets you know you are about to download X amount of data so for me it was 225Gbytes of information. If it give me the option to download all or store them in my cloud account to download later then that would be brilliant.

With iTunes I now only store the music I listen too on my device the rest of the TV shows & Movies for example are stored on the cloud and I just download them when I want to watch one.

Monday, 22 April 2013

Binding functions to HTML elements using HTML5 data- attributes

Project : https://github.com/IrishAdo/EventManager

Introduction

This project came about from my need to simply link a html element to a javascript function.  I started out by adding click events to each element that I wanted to be able to click.  That quickly became very complex to manage the code as the web application became bigger.

What I wanted was to create a javascript object structure where I could group functionality into parts of the object with each section being a different file so that I was effectively splitting the code base into manageable code blocks  take for example the following example object


<script>
var myObject = {
    subObject = {
        YouClickedSomething(t){
            alert(t.id);
        },
        withParams(t,hello){
            alert("hello "+ hello);
        },
        withExtraParams(t,hello,with){
            alert("hello " + hello + ' hows ' + with);
        }
    }
};
</script>

As you can see this is a rather simple object structure now in my code base I would have a main.js which would be.
var myObject = {
    subObject = {}
};

Then with a subObject.js file containing loaded afterwards.
myObject.subObject = {
        YouClickedSomething(t){
            alert(t.id);
        },
        withParams(t,hello){
            alert("hello "+ hello);
        },
        withExtraParams(t,hello,with){
            alert("hello " + hello + ' hows ' + with);
        }
    };

Now I have three functions in the sub object that I want different events to interact with which and here is the elements in questions.
<button id='button1'>button 1</button>
<input id='field1' value='input 1'/>
<button id='button2'>button 2</button>
<button id='button3'>button 3</button>

This would normally require the developer to write a bit of binding code that links each of the elements to specific functions.  Which means for the developer to maintain the code there is no reference between the elements and the javascript out side the Element Selector used to bind the element to an event.  so what if we changed the text above to the following

<button id='button1' 
       data-click="myObject.subObject.YouClickedSomething"
>button 1</button>
<input id='field1'   
       data-click="myObject.subObject.YouClickedSomething" 
       value='input 1'/>
<button id='button2' 
       data-click="myObject.subObject.withParams" 
       data-argc='1' 
       data-argv1='ted!!!'
>button 2</button>
<button id='button3'
       data-click="myObject.subObject.withExtraParams"
       data-argc='2' 
       data-argv1='ted!!!' 
       data-argv2='james!!!'
>button 3</button>

As you can see the html is now telling the developer what elements are bound to an event and the data-action field is telling us what type of event is required on the element for the function to be called.  Valid values for data-action are click, hover & change.  The best bit of this type of coding is that as a developer you can see the the function that will be called on the click event of the above examples.

The zero indexed parameter of each function will contain the object that fired the event then any additional parameters you want to pass to the destination function.

Saturday, 13 April 2013

Short links and why they are bad


I find it funny that before twitter for example people would inspect a link to see the destination it would take them to and then make a decision as to whether or not to click on the link.  This meant that people became informed and the number of virus that successfully got installed dropped.  With the introduction of twitter and its 140 character limit we saw the increase in short link services and here in lies the problem a short link but definition is as short as we can possibly make it.   The information part of the url has been replaced with some random characters  meaning that people will once again click on links with out knowing where they are going.   I've started to see these short links being used in social media sites where there is no limit on the length of a post.  So lets take a look at how a URL shortening service works.

Ok so you have a URL to a site that you want to share for example  http://www.google.com  so what information do we need to store.  well the url of course and the short url that users will click on.  So lets create a pseudo code table to store this information

CREATE TABLE shortLinks {
        uid AUTO_INCREMENT PRIMARY_KEY,
        url  varchar(2000),
        link varchar(20)
}

Technically we don't need to have the link field as the shorten url is actually an encoded UID value.  Let me explain if we just make our link service supply the UID in the url  so that we use the following

http://shrt.in/12345

Then you can see that BASE_10 uses 5 characters to represent the number 12345 while BASE_2 would be 11000000111001 so not shorter at all so lets go the other way.  BASE_16  which is an of the following values (0-9,A-F) would change this to 3039, which is only saving us 1 character on our url.  So lets go even bigger lets use the following possible characters (0-9,a-z,A-Z) which would be BASE_62,  so for example the following UID's 

61 => Z  (saves 1 character) 
3843 => ZZ  (saves 2 characters) 
238327 => ZZZ  (saves 3 characters)  

so as you can see with base 62 we are approximately reducing the size of the characters used by half to represent the number so as we move up the base to 256 for example we will see even bigger benefits in the length of the url.

So now we understand how a short url is generated we need to understand the how the service works.

User clicks link =>  Short server auto redirects => Destination URL

As you can see there is as far as the user is concerned the short link takes them to the destination so in their minds they are associating that short link with a safe landing page say google.com.  But what happens if a hacker uses a short link to link to a vulnerability after all a lot of hacks require the user to click a link in an email.   The shortening service doesn't stop you before redirecting you and this is wrong it should stop and tell you that you are about to go to the following URL allowing you to choose if you click the link or not.

What should happen is the following


User clicks link =>  Short server shows information about the url with manual click to follow => Destination URL

Conclusion

This is why I will never click a short url generated by a short link service, I have no idea where it is going.


Saturday, 6 April 2013

Testing javascript on different browsers

So today I'm sitting in the Apple store in Birmingham Uk, I decided to play with the new thin Apple iMac 27inch  Late 2012 model.  I was curious on how fast the machine was so I thought to my self how would I go about testing.  Well since I use the web a lot I thought lets test javascript first so I did a search and found the "SunSpider" page which will run some javascript tests on your browser.

So I set up both my Apple MacBook Air  and the iMac to the same page both on the same version of Safari and ran the tests at the same time.  Now I expected the faster iMac to finish the test quicker than the Mac Book Air.  but it was the other way around.  and I cant for the life of me figure out why?

My Laptop has a 1.8Ghz processor and 4 GB Ram while the iMac has 3.2 ghz & 8 GB ram

The Mac Book Air could run the test suite 5.25 times before the iMac finished running the test for the first time.  Now for the results and you will see that the Physical tests the iMac preformed better on each and every test it seems that the iMac paused between tests and that is the bit i'm not understanding.

NOTE:: if any one can test it on their home machine I would be interested in their results my Mac Air took 23 seconds to run the test while the iMac took 2 minutes 20 seconds when I timed them

Assumption
I can only assume that the browser is accessing the harddrive between tests as the MacAir has an SSD hard drive.

Results

Mac Book Air


============================================
RESULTS (means and 95% confidence intervals)
--------------------------------------------
Total:                 184.9ms +/- 9.3%
--------------------------------------------

  3d:                   29.1ms +/- 14.7%
    cube:                9.7ms +/- 32.8%
    morph:               8.7ms +/- 13.4%
    raytrace:           10.7ms +/- 12.2%

  access:               18.1ms +/- 8.8%
    binary-trees:        2.6ms +/- 53.7%
    fannkuch:            7.1ms +/- 7.4%
    nbody:               3.8ms +/- 17.3%
    nsieve:              4.6ms +/- 10.9%

  bitops:                9.4ms +/- 8.2%
    3bit-bits-in-byte:   1.3ms +/- 26.6%
    bits-in-byte:        2.6ms +/- 14.2%
    bitwise-and:         2.4ms +/- 15.4%
    nsieve-bits:         3.1ms +/- 7.3%

  controlflow:           2.2ms +/- 13.7%
    recursive:           2.2ms +/- 13.7%

  crypto:               14.4ms +/- 13.5%
    aes:                 8.8ms +/- 20.5%
    md5:                 3.1ms +/- 7.3%
    sha1:                2.5ms +/- 15.1%

  date:                 24.3ms +/- 15.4%
    format-tofte:       13.0ms +/- 16.0%
    format-xparb:       11.3ms +/- 15.2%

  math:                 13.2ms +/- 5.0%
    cordic:              3.4ms +/- 10.9%
    partial-sums:        7.0ms +/- 4.8%
    spectral-norm:       2.8ms +/- 10.8%

  regexp:                9.2ms +/- 8.0%
    dna:                 9.2ms +/- 8.0%

  string:               65.0ms +/- 12.9%
    base64:              5.5ms +/- 6.8%
    fasta:               8.5ms +/- 16.0%
    tagcloud:           12.7ms +/- 11.9%
    unpack-code:        25.2ms +/- 19.8%
    validate-input:     13.1ms +/- 29.1%

The iMac
============================================
RESULTS (means and 95% confidence intervals)
--------------------------------------------
Total:                 128.4ms +/- 3.1%
--------------------------------------------

  3d:                   19.2ms +/- 5.4%
    cube:                6.4ms +/- 10.6%
    morph:               5.2ms +/- 10.7%
    raytrace:            7.6ms +/- 9.0%

  access:               12.0ms +/- 14.7%
    binary-trees:        1.2ms +/- 46.3%
    fannkuch:            5.4ms +/- 12.6%
    nbody:               2.8ms +/- 19.9%
    nsieve:              2.6ms +/- 26.2%

  bitops:                7.4ms +/- 9.2%
    3bit-bits-in-byte:   0.8ms +/- 69.5%
    bits-in-byte:        2.0ms +/- 0.0%
    bitwise-and:         2.0ms +/- 0.0%
    nsieve-bits:         2.6ms +/- 26.2%

  controlflow:           1.8ms +/- 30.9%
    recursive:           1.8ms +/- 30.9%

  crypto:               10.8ms +/- 5.1%
    aes:                 6.2ms +/- 9.0%
    md5:                 2.6ms +/- 26.2%
    sha1:                2.0ms +/- 0.0%

  date:                 17.0ms +/- 0.0%
    format-tofte:        9.0ms +/- 0.0%
    format-xparb:        8.0ms +/- 0.0%

  math:                 10.4ms +/- 6.5%
    cordic:              3.0ms +/- 0.0%
    partial-sums:        5.4ms +/- 12.6%
    spectral-norm:       2.0ms +/- 0.0%

  regexp:                6.8ms +/- 8.2%
    dna:                 6.8ms +/- 8.2%

  string:               43.0ms +/- 5.4%
    base64:              4.8ms +/- 21.7%
    fasta:               5.8ms +/- 9.6%
    tagcloud:            8.6ms +/- 7.9%
    unpack-code:        16.2ms +/- 3.4%
    validate-input:      7.6ms +/- 9.0%

Thursday, 14 March 2013

Cache is King

One of the thing that I have noticed again and again is that most developers will write fantastically complex solutions. Then when the system starts to come under heavy load they then start to look at what tricks they can implement so that they can relieve the pressure on their servers.

Mostly you will see one or more locations where caching of some form or other is implemented into pages so what can you cache.  Normally you see Dynamic caching implemented.  Dynamic caching is when you cache the results of your page for say 30 minutes or an hour or even only for 5 minutes depending on your need for each page.  With Dynamic caching we still have the problem that when the age of the file is marked as too old we rebuild the complete page with the new content.  The problem is that on most web sites 90%+ of the content could and should be cached as Static content.

The difference between static and dynamic caching is that the static is cached only when the data changes so for example the menu of a web site is can be cached as Static information.  Even if you need to cache out many versions of the static content.

So that covers Static and Dynamic but what other types of caching is there?  Data caching when you cache the some data normally the results of say a recordset or it could be as simple as the result of a  complex function.

So why would you choose between static and dynamic caching surely they are the same thing?  well no with Dynamic caching you are interested in the age of the cache.  So you have to stat the file to see the age of the file before comparing it to the current timestamp.  This is more expensive than the Static Cache which doesn't care about the age of a file it just loads it every single time some other process will recache the files when they are required to be cached.

By using a mix of these three types of caching you can make pages that load fast and efficiently.  All content on a page can be considered a rectangle.  You the developer decide if the content in that rectangle is something that changes often (Dynamic & Static) or something that changes infrequently (Static)  but what about Data caching?

Lets say that your webpage is displaying a list of news articles well the ID's of the latest 10 articles could be cached using the Data caching so that when you are recaching the page via Dynamic caching you load the ids then loop through that small data set and load the static cached news articles.

Notice that in this example the number of database calls for this page has reduced to zero.

Let me introduce you to the PHP Programmers project Edify

https://github.com/phpprogrammers/Edify

In this project you will find a section for Caching with a factory class that take a driver for the type of caching that you want to do.

There are three types of caching drivers Dynamic, Statics & Requires.  As you can probably tell the requires is the data caching this is because we cache the data inside PHP tags therefore to load it the fastest way is to require the file.  This means that we do not have to convert from text to data through some complex means.

Saturday, 9 March 2013

Why you should use Echo rather than Print and how

PHP developers have had two different functions that were always in my mind the same function.  I never really thought about which one was the better to use. I just always preferred to use the print function as I had always associated echo with a command line command so preferred the print syntax to it.  I dont know if I ever used echo in my last job (6 years) but in my new job we were drawing up our programming standards documentation.  Because we have inherited a code base thats over 10 years old.  As part of that we were discussing the usage of echo for printing content.  It turns out that the echo function can take a number of parameters. So what does that really mean.

First you need to understand a few points about concatenation.  First when you concat two strings together you end up with 3 areas of memory being used to store the information with 3 strings you get 5 seperate areas of memory allocated. Lets use an example


$hello = "hello";
$world = "world";
print  $hello . " " . $world;


Ok so both strings are 5 bytes long and when we concat them together we also put them together with a space which makes our final print statement take an area of allocated memory taking up 11 bytes of memory but and heres the kicker there is also the creation of a 1 byte string and a 6 byte string which are both held in memory.  So lets break this down and explain where they come from.

If the variable of $hello put the string at memory positions 1-5 it would use the 5 bytes in a row.  Then the creation of the second variable $world would be in memory positions 6-10 and would use the next 5 bytes of available memory (malloc function) .  Now for the creation of final string that is printed well lets take the first part of the statement  5 bytes + 1byte = a new 6 byte block of data  then we merge with the 5 bytes of the variable $world so now we have the following allocated


  1. 5 bytes holding the string "hello"
  2. 5 bytes holding the string "world" (total 10 bytes allocated)
  3. 1 byte holding the space (total 11 bytes allocated)
  4. 6 bytes holding the string "hello " (total 17 bytes allocated)
  5. 11 bytes holding the string "hello world" (total 28 bytes allocated)


Its important to know that while we have only allocated 28 bytes of information which is nothing with todays memory but think about doing this with more than two variables where your variables are hundreds of bytes long if not thousands of bytes long and if you have 10,000 visitors hitting the page then just for the memory allocation of the hello world example would use 280,000 bytes of memory.   If each of the  two variable held 100 bytes then the memory usage for 10,000 visitors at the same time would be 100+100+1+101+201 = 503 bytes * 10000 = 5,030,000 bytes  as you can see you are suddenly talking about a lot of memory allocation going on.

Garbage collection only kicks in once the page finishes executing the print statement and your memory usage will drop to the 10 bytes allocated by the defined variables as nothing is now using (pointing to) the information allocated at memory position 11 - 28.
If you just change the print statement to an echo statement you would get no benefit as you would still have to allocate the same memory for the function to be able to output the final string.

But if you REMEMBER that I said that the echo can take a list of parameters.

It turns out you can just replace the period (concat) with a comma so the code


print  $hello . " " . $world;
changes to
echo  $hello , " " , $world


With this the script has to allocate a single extra byte of information into memory (the space) and the echo  just outputs each string its given this means that it only allocates 11 bytes of information with our 10,000 visitors we are allocates 110,000 bytes and with our 100 byte strings we are now only allocating 100+100+1 = 201 bytes * 10,000 = 2,010,000.  As you can see memory allocation has decreased significantly.

Remember that php is not just a web scripting language but can be run as a command line program as well.

Its important for new PHPers to know that php is a scripting language that is used predominately in web development but that you can also write command line programs in PHP as well. You must understand how both of these processes work. A web-server is typically a dumb terminal. You ask it for a web page and it knows how to server the contents of a file. It doesn't know anything about the internals of the file but rather it just knows how to open the two types of files that exist and how to serve them those file types are Text files and binary files. So how does a php file get processed? actually this is quite simple the web-server is still as dumb in the regard of serving two types of files but now it checks the extension of the file in question and passes it to an external program that will return a stream of data which could be binary or text based. 

OK so now our web-server knows how to serve a text file, a binary file and how to serve a data stream form an external program. (note if you created an hello world program in any language you could configure a web-server to call that program when any file with an extension of .hello was requested.)

There are different restrictions when you are working with PHP in these two environments. The first environment is in web development. Most PHP development will be done using a Web Server to serve the page. The Second is when you want to run a script on the command line.

WEBSERVER:::
  1. Most web servers will limit your page execution to a max of 30 seconds. Typically you will have scripts that will execute in 1-3 seconds with 5-10 seconds considered long execution times. The 30 second barrier imposed by most web servers is to stop infinity loops killing your web-server These are typically a web-server setting for all scripting languages not a php specific setting. To lengthen the time you need to reconfigure your web-server. After the time limit the web-server will kill the process. 
  2. A web-server might sandbox the php process and limit what it can do. 
  3. Session information a web-server tracks user requests and ip addresses allowing you to have persistant information across page requests. 
  4. The web-server will tell php extra settings that will appear in the $_SERVER variable that are related to the machine that is requesting the page. 
COMMAND LINE:::
  1. There is not timeout on your scripts as they are now considered to have full reign on the machine based on the permissions of the user that is executing the script. 
  2. The session environment does not exist as there is only a single instance. 
  3. You can write a php script to parse a huge data file if you wanted but perl would probably do that job faster and quicker for you. 
I've often needed to batch process a lot of files and have used php to loop through a directory and create me a bat file that will run each set of commands on each file as needed. I'm sure there were probably beter ways of doing it but none quicker. As I knew PHP and knew I could use the directory functions to build the bat file to execute really quickly

Thursday, 7 March 2013

Authenticating users using an intranet on a public website.


I have in the past had to authenticate members of staff on a website that is in an external facing server.

First things to know is that its possible for a server to have more than one network card. For the example that we are going to discuss we will state that NIC#1 is used for visitors to access the server and NIC#2 is the card that people inside the company’s network would travel through if visiting the site. Since we know that staff will be on a internal network IP Range 10.*.*.* we can use the php server variables to detect the visitors IP we can work out that they are a member of staff and let them in but wait thats probably rather insecure. As a hacker could probably fake the IP address.

So how do we allow staff to login with single sign on (SSO) ie the login account they used to logon to their computer. Turns out its quite simple.

You need a webserver that is inside the corporate network to have a page that requires user authentication NTLM this will specify that a user has been authenticated via a trusted system.

So you have now got two servers

Server A : in an external location (DMZ)
Server B : a corporate server located in local LAN (Intranet)

All you need to do is redirect a user from Server A to Server B and have Server B then redirect back to Server A. Server B can then send your Authentication details (username) to the Website on Server A.

Now for added security you should have a password on server A that is used to encrypt the information that is sent to server B then have server B decrypt in the authentication page and then encrypt the information you will send back to server A

This means that if a hacker tried to trick the website on server A that they have authenticated correctly then they would have to find the encryption key on A, The Encryption Key on B to work out what information is being transmitted to truly authenticate a user.

Wednesday, 16 January 2013

Image Search OOPS

Today I was having a laugh with one of the guys at work and I wanted to send him an image of a donkey but I was having a brain dead moment and the only word I could think of for donkey was "Ass".  So I typed it into http://images.google.com and hit return.  Suddenly a lot of pictures of women in and out of underwear covered the screen.  LOL you've never seen anyone hit CTRL+F4 quicker in your life.

Monday, 14 January 2013

Tutorial - Write less code but write it better


One of the main problems with so many application developers is that they are happy to sit and write the same CRUD functions again and again and again.  To my fellow developers I say No More!!!


CRUD stands for CREATE, RETRIEVE, UPDATE & DELETE.  The basic code that we keep writing again and again.  About 10 years ago I wrote the CMS package for Libertas Solutions it was a massive undertaking taking me just under 4 man years work of work and all inside of a 2 year period.  I was working 16-20 hours a day solid for 2 years to produce the CMS.  It was and is completely modular allowing the creation of new modules and had three different experiences depending on the level of functionality that you wanted which was aimed at Small, Medium & Enterprise companies.  It was one application that could server all our clients content in one go it was WAI level 3 compliant and Passed Site Morses WAI level 1 completely first time.  The problem was that each module had massive functions to do the CRUD and I wrote 70 modules in the 2 years that I worked on the project.




One thing that I was sure of was that there had to be a better way of coding one that would produce better and more easily read code.  I think most developers when they hit that wall will come up with what is undoubtably the next step in the thinking of developers and that is to atomise the data you are wanting to save.  You normally end up 1 or 2 tables for your system one table will store each field of an object as a row in the database.  Brilliant you say I can now just dump information into this table and extract it at will.  and while you can do this there is one major flaw searching the data is a pain in the arse.  You can end up with 30+ inner joins on a database just to pull the information you need.  the real solution is actually more straight forward.



First you need to realise that the database model you were using originally is actually the correct one for the job what you weren't doing what managing the handling of the records correctly.


Lets say we have a table that stores the following fields about a person

TABLE Person
   id - Primary auto-incrementing key
   name - the name of a person

now lets create a class that represents that table.

Class Person extends DatabaseModel{
    private $primaryKey = "id";
    private $fields = Array("id"=>DB_INT,"name"=>"DB_STRING");

    public $id = null;
    public $name = null;
}

now lets say we build a function in our database class that looks something basically like this

define("
DB_INT", 0);
define("DB_STRING", 1);
define("
DB_DATETIME", 2);

class database{
....
function save($obj){

    if($obj->getPrimaryKeyValue()<0){
          $sql_insert = "........."
          foreach($obj->getFields as $field=>$type){
          }
          return $this->dbObj->execute($sql);
    } else {
         //  do an update using the fields.
    }
}
....
}

With this type of coding style you will write small simpler code ( no it doesn't work with joins its for when you wan to extract record X edit it and save it)

$person = new Person();
$person->name = "Bill Gates";
$db->save($person);

done


Sunday, 13 January 2013

PHP Tutorial - the wonderful world of hello

Ok the second tutorial will be simple its hello world.  Ok so I'll write some code I'll use two minus signs to represent all the code in the file.  The first double minus sign will be followed by the file name  so here is the first version of hello world

--hello.php
hello world
--

as you can see there is not even a php processor tag involved.  So what would it look like if we used php to write the code well one of three ways


--hello1.php
<?php
print "hello world";
?>


--hello2.php

<?php
echo "hello world";
?>

--hello3.php

<?="hello world";?>



OK lets go a step further and get it to say our name with it defaulting to world if no name supplied

--hello4.php
<?php
$name = isset($_GET["name"])?$_GET["name"]:"world";
// the following will write out the same text in different ways
// concatenate the two strings together
print "hello " . $name;
// with double quotes we dont need to concatenate two string together.
print "hello $name";
?>

You can test this by running this file via a web server and through your browser

hello4.php
hello4.php?name=test

Ok still with me  then how about an image that writes hello world to the screen

--hello5.php

<?php
header('Content-Type: image/png');

// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 10, 5, 5,  "HELLO WORLD", $text_color);

// Output the image
imagepng($im);

// Free up memory
imagedestroy($im);
?>



--hello6.php

<?php
header('Content-Type: image/png');

// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);

$name = isset($_GET["name"])?$_GET["name"]:"world";

imagestring($im, 10, 5, 5,  "HELLO ".$name, $text_color);

// Output the image
imagepng($im);

// Free up memory
imagedestroy($im);
?>





Friday, 11 January 2013

PHP Tutorial - Your first program is not hello world

Ok so i'm going to assume that you have already got php installed  if not then for linux use a package manager to install each of the sections your will need PHP, Apache and Mysql server.  For windows install a complete package like XAMPP for Mac OSX install MAMP.

Php is a scripting language so the .php files are all text so to run the script you must compile the script so that the computer can run the steps that you have in your code.  Most programming languages compile once and give you bytecode files which are normally then linked into an executable.  for example the java language is compiled into .class files (bytecode) which you then server to a JVM Java virtual machine which takes the bytecode and links it together so that it can run on what ever operating system you have a JVM for.  C compiles to .o files then is linked into exe files which you then server and  run.  With php you just upload your code to a server and it gets compiled & linked each time the page is called.

Ok the first program that we are going to write is to check out what things in the php.ini have been loaded correctly.  Don't assume that because you have put the correct line in the PHP.ini that its installed.  This program will also allow you to find out why a program that works on your dev box doesn't work on your live environment.

Ok php is a scripting language now with most scripting languages you just write your code in the text file and run it

-- filename : hello.bat
echo "hello world"
-- /end file

With php it was written to be embedded in html pages so you need to  wrap your scripts in processor tags that tell the php interpreter php.exe

<?php

?>

It is possible to configure php to accept short processore tags <? & ?> you save 3 bytes of information doing it this way.  "DON'T EVER DO THIS" because you will find that you'll move your application to a different provider who hasn't and won't configure php to allow it.  For compatibility with most servers use the long version.

So your first program is not an hello world program we are going to write a program to tell us which extensions that are in php.ini have been enabled.

<?php
phpinfo();
?>

Thats it! yeah that simple,  the PHP guys have written this function to report what has been configured correctly.  Have a look at the results of the file you will see things like the version of PHP that you are running.

In the future tutorials I hope will we will cover image creation, database access using PDO,  Fetching content from another server via CURL & SOAP.

The next tutorial is going to be how to do different hello world programs in php and not the following hello world program.  So we are going to need the basic image library "GD", the "PDO" library and "CURL" so scroll down the configuration page to check if those modules are available.  If they are not available then configure php.ini and restart your webserver to test if they become available.

<?php
 echo "hello world";
?>

Sunday, 6 January 2013

Had to use an Android phone the other day at work.

All I had to do was redial a number that we had just used (we were just testing the office phone network) so i picked up the phone and navigated to the last call screen very simple.  The one that lists the last numbers that you rang.  I pressed the last number and stuck the phone to my ear.  after waiting 10 seconds for the ring tone I looked back at the screen.  The phone was still sitting on the list of numbers that you previously dialed.  So I thought doh I mustn't have actually pressed correctly. So I pressed the screen again noticed an interaction and as I was putting it to my ear realised that it screen didn't look like it was making a call.

Looking again I realised that the default action was to list the history of making the calls "What?????  No" I thought to my self the default should be make the bleeding call I wanted to not list the history then have to click on one of those previous 5 calls to actually make the call.

I mean I had to choose one of 5 options all of which was the same.  Now I don't know if this is still the way that Android phones work but honestly just make the dam call.  This could be simply fixed by putting ring number icon on the right hand side of the cell.  Which you can  then easily click on to make a call or click on the data cell.

Every phone I've ever used would dial the frigging number when you select it from the call history.

Found out today that it was running version 2.2 of Android

Saturday, 5 January 2013

Why develop n-Tier Applications

New or junior php developers are always asking what they should be doing to improve their code which has led me to write the following post about n-Tier development. So what is n-Tier development,  N-Tier development is splitting your application into different sections to allow ease of future development.

For example if you were storing data in an array for your application then you would state that the php application is encapsulated in a single Tier.  Once you move to storing your data in another location separate from the php language like a database or data files.  That you process either through a database connection or through an import function.  You have moved to a 2 Tier application.  All good so far as this is where most developers will get to quite quickly.  Lets talk about 3-Tiers of application development,

So you have 

1) Database
2) Application 
But what is the third Tier???

The third Tier is presentation and by splitting your application into two distinct pieces you can get your third tier.Most applications have a business logic and a presentation logic and most young developers have these mixed through out their code.  Meaning that future changes to the system will either require a rewrite of a large complex function so that you can present two views or what normally happens is that the next developer takes a copy of function A and calls it B and then makes B do what they want.  So whats the problem with that ?  Simple if there is a fundamental flaw or security hole found in function A then you have to also know that you must fix B as wellTake for example the following small bit of code

hello("world"); 

function hello($name){ 
   $name = strtoupper($name);
   print "&gt;&gt;&gt;Hello [$name] &lt;&lt;&lt;";
}

As you can see this function renders the name in capitals and puts  angle brackets around the statement.

now lets say that we want to do the same thing but changing the presentation to be square brackets  would you create a new function our would it have been better to write it a different way to start with.

print ">>>" . hello("world") ."<<<";
print "[[[" . hello("world") ."]]]";

function hello($name){ 
   return strtoupper($name);
}


As you can now see the presentation is separate from the business logic.  the code is simpler as you have removed the presentation logic to a different location.

I was asked for example code so here you go

https://github.com/IrishAdo/examples-php