PHP Programming 101

May 1st, 2015

Random Numbers

Posted by Conrad in Basic Programming, PHP, Programming

int rand ( [int min, int max])
int mt_rand ( [int min, int max])
int getrandmax ( )
int mt_getrandmax ( )
void srand ( [int seed])
void mt_srand ( [int seed])

Sometimes you want to take random actions in your code – it might be to give your web site visitors a different greeting each time they visit, you might be programming a game, or you might be trying to secure data by hashing it. Either way, randomisation is simple and helpful thing to remember, and has just two functions: rand(), and mt_rand().

Both functions do the same thing, and both take the same parameters, so what is the difference between the two? Well, rand() is a basic randomisation function that is very quick but not very “random” – the numbers it generates are slightly more predictable. Mt_rand() on the other hand, is more complicated – the “mt” parts means Mersenne Twister, as that is the name of the randomisation algorithm it uses. Mt_rand() returns much more “random” numbers, but does so at the expense of some speed.

As mentioned, both functions have the same parameters – two optional numbers, for the minimum number to return and the maximum number to return. Either you supply no parameters, which will result in PHP returning a random number between one and a very high number, or you can supply the two parameters. Here is an example:

$random = rand();
$randrange = rand(1,10);
$mtrandrange = mt_rand(1,100);

Note that the two numbers passed in are inclusive. That is, our $randrange number could be anywhere between 1 and 10 including 1 and 10.

As mentioned, if you do not pass any parameters to your rand() and mt_rand() calls, PHP will generate a random number from 1 to a high number. If you want to find out the maximum number PHP can return from a rand() call, use getrandmax(). There is a similar function, mt_getrandmax() for mt_rand().

Now you know how randomisation works, here is a quick example to show you how you can make use of randomisation to greet web site visitors in various ways:

switch(rand(1,6)) {
case 1:
$greet = 'Hello!'; break;
case 2:
$greet = 'Welcome!'; break;
case 3:
$greet = 'Greetings!'; break;
case 4:
$greet = 'Salutations!'; break;
case 5:
$greet = 'Good day!'; break;
case 6:
$greet = 'Yo!'; break;

print $greet;

Here we have not bothered assigning the result of rand() to a variable before putting it into the switch statement, but you can do it whichever way is easier for you to read.

One important thing to note is that the speed of randomisation does not depend on the sizes you pass into it – rand() is just as fast in rand(1,3) as it is in rand(1, 10000000). Mt_rand() works just short of 50% slower than rand(), which means you should only be using it if you particularly need the extra randomisation it brings.

To give you an idea of how fast the two run and how using larger values for randomisation makes no difference, try this script:

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = rand(1,100);
$END = time() - $START;
print "Short rand() took $END seconds\n";

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = mt_rand(1,100);
$END = time() - $START;
print "Short mt_rand() took $END seconds\n";

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = rand(1,10000000);
$END = time() - $START;
print "Long rand() took $END seconds\n";

$START = time();
for ($i = 1; $i < 1000000; ++$i) {
$j = mt_rand(1,10000000);
$END = time() - $START;
print "Long mt_rand() took $END seconds\n";

Most random number generators require “seeding” – initialising with a starting value – because the numbers they generate are not truly random. Instead, they are known as pseudo-random, meaning that they appear to be random. The seed value is used to generate the first number, the first number is used to generate the second number, the second for the third, etc, meaning that if you always supply the same seed value you will always get the same string of “random” numbers. This is actually advantageous. Many years ago there was a popular game called Elite available on the BBC Micro, where the player was allowed to fly around a large universe of eight galaxies, each with thousands of star systems. Each star system had a very precise number of planets, a distinct economy situation, etc, and yet the entire universe fit into just 22K of memory. How was this possible? Simple: by providing the same seed to their random number generator, the exact same universe could be generated each time.

Of course, this is a fairly rare situation. More often than not you will want numbers that look random as opposed to numbers that are always the same, and this is where random seeding comes in. If you provide a random number to the random number generator as its seed, you will have a new and original string of random numbers coming out. Does this sound like a chicken and egg situation to you? That is, how do we get the random number to provide to the random number generator? Well, think of what randomness – usually called entropy – you can draw upon in your scripts.

  • The number of files in your temp directory?
  • The number of rows in your database?
  • The time your script was called?

Of all three of these, the latter is potentially the most random – you do not control when your script is called, and you are certainly never likely to have the same script called in the exact same microsecond, so you could use the return value from microtime() as your initial random seed.

The seed function for rand() is srand(), and it takes one parameter – an integer to use as the seed value. If you are using mt_rand(), you should use mt_srand() for seeding. If you recall from earlier, microtime() returns a floating-point number – this is no good for use as the parameter to srand() (or mt_srand() – it is exactly the same), so you need to make it into an integer before use.

Now, as we know that microtime() returns the time in millionths of a second, we can convert its return value to an integer by multiplying it by a million, like this:


The code above should seed the standard random number generator fairly well. You can do the same for the Mersenne Twister generator with this code:

mt_srand((double)microtime()*1000000 );

If you want your random number to always generate the same string of numbers, simply supply a seed that is a known value. For example, no matter how often you run it, this next script will always generate the same “random” numbers:

echo mt_rand(1, 100), "\n";
echo mt_rand(1, 100), "\n";
echo mt_rand(1, 100), "\n";

The last option is just to call srand()/mt_srand() without any parameters at all. In this situation, PHP will attempt to generate a random seed for you – not much good if you want reliably random numbers or if you have a particularly good source of entropy for your seed value, but generally good enough for most people.

As of PHP 4.2.0, there is no need to seed the random number generator with srand() or mt_srand() as this is done automatically.


April 24th, 2015

PHP Browser Checking Script

Posted by Conrad in Basic Programming, Information, PHP

Several factors are to be considered should one be involved with deploying projects over the internet. One of the things you could do would be to have a nifty script that checks for the particular browser your clients might be using. This can be done with a simple and short piece of code that can mean the difference between a successful deployment without problems allowing proper extensions and plugins to be included. A sample of the code can be seen below for your reference which makes it easier for your program/web page to know which set of scripts and what parameters to adhere with. (more…)

April 17th, 2015



V. Operators in PHP

*Arithmetic Operators*

+ addition
- subtraction
* multiplication
/ division
% modulus (division remainder)
++ increment
– decrement

*Comparison Operators*
== equal to
!= not equal
> greater than
= greater than or equal
<= less than or equal

*Logical Operators*
&& and
|| or
! not

I know its self explanatory…

VI. IF….Else Statements

If (condition)
//*Things to be executed if the answer to the condition is true*//
//*Things to be executed if the answer to the condition is false*//

If…else statement is use if the user wants to execute a set of code when the condition is true and another if the condition is not true.

VII. Switch Statement

switch (expression)
case 1:
//*code to be executed*//
case 2:
//*code to be executed*//
//*code to be executed*//

Switch statement is use if you want to select one of many blocks of code to be executed. this statement is used to avoid long blocks of if…elseif..else.

VIII. Looping Statement

code to be executed;

While statement is used to execute a block of code if and as long as a condition is true

code to be executed;
}while (condition)

Do—while statement is used to execute a block of code at least once and it will repeat the loop as long as the condition is true.

for each (array as value)
code to be executed;

For each statement is used to loop through arrays.

I think this is already enough and it has added new knowledge to those who are new in PHP… good luck and happy coding…


image source:

April 10th, 2015

The Client side and Server Side Validation (1/3)

Posted by Edi in PHP

In validating the input, there are two options:

1)validate on the client side using a scripting language, or
2) validate on the server side using PHP.

The Client side Validation
A scripting code can be written (most commonly JavaScript) that will verify if the form fields
contain good data before being submitted to the server, this method is the most oftenly used.
There are also two advantages in using client-side validation:
A) The users receive feedback faster (no need to go off to the server, process the information, then download another HTML page), and
B) This means that it also saves load on the server – more work is done on the client

To be continued…

April 2nd, 2015

Marketing Your Skills as a Freelance Programmer

The popularity of PHP as a solution for websites with dynamic contents has created a huge market for people skilled enough in writing complex applications in PHP, covering a wide range of solutions. If you think you’ve got enough experience under your belt, you’ve probably already considered the idea at least once. However, simply knowing how to write good PHP scripts won’t be enough to make it as a successful freelance programmer. This post is a bit more abstract as it doesn’t cover programming specifically, but more general ideas that can help you get a better exposure for your skillset.

First, consider your weak points – this is crucial when aiming to be a successful freelancer. With a highly competitive market like the one we have, you simply can’t afford to lack in any qualification when it comes to writing PHP scripts. If your knowledge of database interaction is weak, you’d better grab a book on databases and dig in for the next few weeks – otherwise, that other guy who doesn’t write scripts quite as well as you, but knows MySQL by heart will keep getting the good jobs and you’ll keep treading in the same place.

Also, figure out what exactly you want to offer as a service – the applications of PHP are quite varied and this allows you to specialize in a particular type of design. Figure out what you do best and market yourself to that crowd – it’s always better to offer the type of service you’re best at (something which really shouldn’t even need mentioning, but somehow keeps getting ignored by many people).

March 26th, 2015

Arrays : Changing cases

Posted by Conrad in Basic Programming, Sample Code

This form of array declaration allows one to change the case from uppercase to lowercase and vice versa. The syntax goes as follows:


The array part, specifies which table or array to use and is a required field which is not the case with the key which is automatically assigned a value. An example of it’s use can be seen below:


The output of the said commands will be:
Array ( [A] => Mouse [B] => Rat [C] => Rodent [D] => Cat)

Another example of it’s use would be:


That returns the following values respectively:
Array ( [A] => Mouse [B] => Rat [C] => Rodent [D] => Cat)

In the next post, we would discuss an array function that divides a large array into several chunks of separate arrays.

March 19th, 2015

Dissecting/Understanding the first program

Posted by Conrad in Basic Programming

The first post had you making a program that was equivalent to the “Hello World” program used for teaching basics of a programming language and here’s how it worked. When the script was requested by opening the web page, Apache intercepted the request and passed it onto PHP which parsed the script looking for the code in between the terminators and then doing the requested operation which was to display the text contained within the echo command. This result was given back to the server then again to the client. The output contained a valid HTML so the browser was able to understand it and execute the requested operation.

March 12th, 2015

PHP Installation

Posted by Edi in PHP


You can download PHP and install in the windows system in, which is the official Web site for PHP. After downloading. Unzip the file into a directory and that’s done.

To check if installation is okay, there are 2 execution interfaces, CLI Command Line Interface and CGI Common Gateway Interface. However, if you installed PHP in the \php directory, you can 1st try to check there.

Run “\php\php -v” command to check the Command Line Interface (CLI).

Run “\php\php-cgi -v” command to check the Common Gateway Interface (CGI).

If you see the PHP version on the screen with both commands, then the installation is okay.

With these, tips you can now try to install you PHP program and know how to check if it is installed properly.

March 5th, 2015

5.2.7. is a security hazard–get rid of it!

Posted by editor in Information

PHP version 5.2.7. is dangerous and a security hazard; take it out and update to 5.2.8. immediately:

Due to a security bug found in the PHP 5.2.7 release, it has been removed from distribution. The bug affects configurations where magic_quotes_gpc is enabled, because it remains off even when set to on. In the meantime, use PHP 5.2.6 until PHP 5.2.8 is later released.

The PHP Development Team would like to announce the immediate availability of PHP 5.2.8. This release addresses a regression introduced by 5.2.7 in regard to the magic_quotes functionality, which was broken by an incorrect fix to the filter extension. All users who have upgraded to 5.2.7 are encouraged to upgrade to this release. Alternatively you can apply a work-around for the bug by changing “filter.default_flags=0″ in php.ini.

Take out 5.2.7. as soon as possible and use the newest one for security’s sake!


February 26th, 2015

Embedding Comments

Posted by Conrad in Basic Programming, Sample Code

Now, to make you a better programmer we all know the value of comments. This allows you to understand the code that you have written defining and given meaning to operations as you build them up. You start with the terminators used by PHP and end with them as well. Single line comments look like this �// comment� and Multi-line ones use the syntax /* comment comment*/. A better example would be the one below:

/* comment

In the next post we take on the best parts of PHP which would be variables which is essential in all programming languages.

Next Page »