Category Archives: Programming With PHP

I Just Moved – A Friendly Reminder

moving-wordpress-blog

I am creating this post to let you know that I have started the process of migrating from this wordpress-hosted blog to a self-hosted one which is located at, well, Simple Developer. I am still fixing a few errors like syntax highlighting and things like that.

Besides that, everything should be fine now. I humbly request those who had subscribed to this blog to consider subscribing to my new blog which is still a wordpress platform.

Thank you for your loyalty as readers and I hope we can connect with each other as time as goes by.

Take care and see you at http://www.simpledeveloper.com !

Object-oriented Programming In PHP – Part II

Yesterday I created a post on OOP and had to split it in two to avoid making it too long. Today, I am going to finish up the remaining part before starting other stuff! So, let us get started here.

object-oriented-programming

Controlling Visibility Through Inheritance With private and protected

While writing code using OOP, you can use private and protected visibility modifiers to control what gets inherited. Attributes or methods declared as private will not be inherited. If an attribute or a method is marked as protected, it will not be visible outside the class (like private) but will be inherited. Example:

<?php
   class A
   {
     private function operation1(){
       echo 'operation1 was called';
     }
     protected function operation2(){
       echo 'operation2 was called';
     }
     public function operation3(){
       echo 'operation3 was called';
     }
   }

   class B extends A
   {
     function __construct(){
       $this->operation1();
       $this->operation2();
       $this->operation3();
     }
   }

   $b = new B();

   #----------------------------------------------------#
   |The above code creates a class A with three methods |
   |with private, protected and public accessibility    |
   |As I mentioned earlier, private attributes and      |
   |methods are not inherited - that means that operat- |
   |ion1() will result in an error when you call class B|
   |constructor                                         |

   |Fatal error: Call to private method A::operation1() |
   |from context 'B'                                    |
   #----------------------------------------------------#

   #The protected operation2() can only be used inside  #
   #the child class but not outside. That being said,   #

   $b->operation2();

   #will result in an error!
   #public operation3() however will not result in any  #
   #error
   $b->operation3();

?>

Overriding

We have shown that a subclass can declare new attributes and methods. It is also valid and sometimes useful to re-declare the same attributes and operations. You might do it to give an attribute in the subclass a different default value to the same attribute in its superclass or to give an operation in the subclass a different functionality to the same operation in its superclass. This is called overriding.

Consider:

<?php
   class A
   {
     public $attribute = "default value";
     function operation(){
       echo "Something <br />";
       echo "The value of \$attribute is ".$this->attribute."<br />";
     }
   }

   #Now if you want to alter the default value of $attribute
   #and provide new functionality to operation() you can create
   #the class B that inherits from A like this:

   class B extends A
   {
     public $attribute = "different value";
     function operation(){
       echo "Something else<br />";
       echo "The value of \$attribute is ".$this->attribute."<br />";
     }
   }

   #Declaring B does not affect the original declaration of A
   #Now see what happens here:

   $a = new A();
   $a->operation();
   #----------------------RESULT----------------------#
   #Something
   #The value of $attribute is default value
   #---------------------Now create one for B---------#

   $b = new B();
   $b->operation();
   #---------------------RESULT-----------------------#
   #Something else
   #The value of $attribute is different value

   #NOTE: overriding attributes and operations in a
   #subclass does not
   #affect the superclass

   #The parent keyword allows you to call the original version
   #of the operation in the parent class. To call A::operation()
   #in class B, you simply do this:
   parent::operation();
?>

Preventing Inheritance and Overriding with final

In PHP, using the keyword final in front of a function prevents it from being overridden in any subclasses. For instance, we could add it to our operation in our class A like this:

<?php
   class A
   {
     public $attribute = "default value";
     final function operation(){
       echo "Something <br />";
       echo "The value of \$attribute is ".$this->attribute."<br />";
     }
   }
   #-------------------------------------------------------#
   #using final prevents you from overriding operation in class
   #B and an attempt to do so will result in a fatal error!
   #Fatal error: Cannot override final method A::operation()

   #You can also use final to prevent a class from being
   #subclassed like so:

   final class A
   {
     //--------------
   }
   #Trying to inherit from A now will result in an error message:
   #Fatal error: Class B may not inherit from final class (A)
?>

Understanding Multiple Inheritance

PHP does not support multiple inheritance – that means each class can only inherit from one parent. There is however no restriction on how many children can share the same parent.

Implementing Interfaces

Since PHP does not support multiple inheritance, you use interfaces to solve problems that would otherwise require multiple inheritance. The idea of an interface is that it specifies a set of functions that must be implemented in classes that implement the particular interface.

Consider a situation where you have a set of classes that you want them to be able to display themselves. Instead of having a parent class with a display() method that they all inherit and override, you can simply implement an interface as follows:

<?php
   interface Displayable
   {
      function display();
   }

   class webPage implements Displayable
   {
     function display(){
       //do some display work here for web page
     }
   }

   #Failure to implement the display() function will result
   #in a fatal error. It is also worth mentioning that
   #a class can inherit from one class and implement more than
   #one interface!
?>

Designing Classes

When I was working on my simple shopping cart, I used some include() or require() to maintain consistency throughout the pages. Now that we know what classes and functions do, we should be able to generate our web pages dynamically!

That will be really fun and that is why I want to save it for tomorrow to avoid diluting it with what I have already done today! I hope you will join me for this fun adventure because it will be so much fun.

Thanks for stopping by and if you have any questions or have spotted any errors, let me know. Take care and see you!

Object-Oriented Programming In PHP – Part I

According to Wikipedia , Object-oriented programming(OOP) is a programming paradigm that represents concepts as objects that have data fields (attributes that describe the object) and associated procedures known as methods. An object  is an instance of a class – that is, you use a class to create an object. The easiest way to understand OOP is using a real-world example.

object-oriented-programming-cars

Looking at the above image makes our work really easier here. In real life, there is something called a car. But you can’t just walk to your friend’s house and say I own a car and assume that they will automatically know what type of car you have. So, in other words, our car is a class and from that car class, we can create different kinds of cars(objects) like Toyota, Ford, Chevy etc. Oh, don’t forget the VW Bug!

To make this a little understandable, we can break the car concept into data fields and methods. Every car has some color(attribute), and most importantly they move(method). What else can you think of? A car can either be on or off. The other fact is that different cars have different other properties. Think of them!

Another good example is a cookie-cutter. You can think of a cookie-cutter as a class and the cookies themselves as objects.  Using your cookie-cutter, you can create all shapes of cookies, using different recipes.

Encapsulation

One of the biggest advantage of OOP is its capability to support and encourage encapsulation – also known as data hiding. Essentially, access to the data within an object is available only via the object’s operations, known as the interface of the object.

Polymorphism

Polymorphism means different classes can have different behaviors for the same operation. Consider having a class Car and a class Bicycle. They can both have different move operations. Polymorphism is more a characteristics of behaviors than it is of objects. In PHP, only member functions of a class can be polymorphic.

Inheritance

Inheritance allows you to create a hierarchical relationship between classes using sub-classes.  If you are asking whether this works like a son inheriting a million dollars from his father or not, then you are thinking right! A subclass inherits attributes and operations from the superclass.  An example could work like this: we both know that a car and a bicycle have certain things in common. You could then use a class called vehicle that contain a color attribute and a move operation that all vehicles have. You can simply then have both car and bicycle classes inherit from vehicle class – how nice right?

Using inheritance might save you work if operations can be written once in a superclass rather than many times in separate subclasses. It might also allow you to more accurately model real-world relationships. If a sentence about two classes makes sense with “is a” between the classes, inheritance is probably appropriate.The sentence “a car is a vehicle” makes sense, but the sentence “a vehicle is a car” does not make sense because not all vehicles are cars.Therefore, car can inherit from vehicle.

Creating Classes, Attributes and Operations

Let us get our hands dirty here by …you guessed it, creating classes, attributes and operations in php. When creating a class, the keyword class must be used.


<?php
   #the structure of a class
   #opening and closing braces
   #---------------------------------------------------------#
   class classname
   {
     #do stuff here - attributes and operations
   }
   #---------------------------------------------------------#
   #Obviously, without attributes and operations, our class
   #is not that useful. So let us add some attributes
   #---------------------------------------------------------#
   class classname
   {
     public $attribute1;
     public $attribute2;
   }
   #---------------------------------------------------------#
   #the above code creates a class called classname and
   #two attributes $attribute1, $attribute2 with [public]
   #visibility. visibility options[public, private, protected]

   #We have added attributes but we have no way of operating
   #on them, so why not add some methods to our brand new class?
   #---------------------------------------------------------#
   class classname
   {
     public $attribute1;
     public $attribute2;

     #now add two methods here
     function operation1(){
        //do some cool math here
     }

     function operation2($param1, $param2){
        //do some other crazy rocket-propulsion.
     }
   }
   #--------------------------------------------------------#
   #As you can see, we created two functions inside our class
   #and we call such functions ... methods because they are in
   #the class!
?>

Constructors

Most classes have a special type of operation called a constructor. A constructor is called  when an object is created and also normally performs useful initialization tasks such as setting attributes to sensible starting values or creating other objects needed by the object.

A constructor is declared the same way as other operations inside a class but has the special name __construct() and although you can manually call a constructor, its purpose is to be called automatically when an object is created. Time for an example:

<?php
   #declaring a constructor for a class
   #----------------------------------------------#
   class classname
   {
     public __construct($param) #our constructor
     {
        //do some initialization or setup here
        echo "Constructor called with parameter: ".$param."<br />";
     }
   }

   #PHP supports function overloading - providing more than one
   #function with the same name with different numbers or types
   #of parameters!
?>

Destructors

Just like constructors, there exist destructors. They are special in the sense that they don’t take any parameters and declared as __destruct(). When all references to a class have been unset or fallen off a scope, it gets destroyed. If you then want to have some functionality executed before the class is destroyed, you use the destructor!

Instantiating A Class

After declaring your class, you need to create an object – a particular individual that is a member of the class. You can then do something with it. As I mentioned earlier, it is called instantiating or creating an instance of a class. You create an object by using the new keyword. When you do so, you need to specify which class your object will be an instance of and provide any parameters required by the constructor. Time for an example:

<?php
   #from our first class earlier;
   class classname
   {
     public __construct($param)
     {
        echo "Constructor called with parameter: ".$param."<br />";
     }
   }

   #--------------------NOW INSTANTIATE-------------------------#
   $a = new classname("first");  #param - first
   $b = new classname("second"); #param - second
   $c = new classname();         #param - none

   #Running the above code will result in: guessed it?
   #Constructor called with parameter: first
   #Constructor called with parameter: second
   #Constructor called with parameter:
?>

Using Class Attributes

Within a class, you have access to special pointer called $this. If an attribute of your current class is called  $attribute you refer to it as $this->attribute when either setting or accessing the variable from an operation within the class.

<?php
   #demonstrating how to use attributes inside a class
   class classname
   {
     public $attribute;

     function operation($param)
     {
       $this->attribute = $param;
       echo $this->attribute;
     }
   }
   #Access modifiers [public, private, protected] determine
   #whether you can access an attribute outside a class or not.

   #---------------------CONSIDER THIS--------------------#
   class classname{
     public $attribute;
   }
   $a = new classname();
   $a->attribute = "value";
   echo $a->attribute;
   #--------------------EXPLANATION-----------------------#
   #Since the $attribute variable is declared as [public],
   #we can access it outside and even change the value!
?>

Doing what we did above(accessing attributes and changing their values outside a class is obviously not a good idea.To avoid such a problem, we take advantage of OOP’s encapsulation. We enforce it by using __get and __set functions. These functions are commonly known as setters and getters or accessor functions. Example:

<?php
   class classname
   {
      public $attribute;

      function __get($name){
        return $this->$name;
      }
      function __set($name, $value){
        $this->$name = $value;
      }
   }
?>

Now our above code provides minimal functions to access our attributes. Basically, our __get function returns the value of the attribute with the same name as the one passed in ($name). __set() on the other hand takes a name of an attribute and a value, then sets the value of the attribute to the value passed in!

One thing to remember is that you do not call __get and __set functions directly. You may be asking, so how do we then call them? Here is the thing: when you instantiate an object like this:


<?php
   $a = new classname();
?>

You can then use __get() and __set() functions to check and set the value of any attributes: If you type:

<?php
   $a->$attribute = 5;
?>

The above statement implicitly calls __set() with the value of $name set to “attribute”  and the value of $value set to 5. You need to write __set() to do error handling.

The __get() function works in a similar way. If, in your code, you reference

<?php
   $a->attribute
?>

this expression implicitly calls the __get() function with the parameter $name set to “attribute”. It is up to you to write the __get() function to return the value.

Let us improve our __set() function to do some error checking!

<?php
   function __set($name, $value){
      if(($name == "attribute") && ($value >=0) && ($value <=100)){
         $this->attribute = $value;
      }
   }
?>

Access Modifiers Debunked

There are three main access modifiers and they are described below:

  1. public – this is the default option. That means that failure to declare an access modifier on an item makes it public. The particular item will be accessible both in and outside the class.
  2. private – this means that the marked item is only accessible within the class. You may also declare some methods as private – for example if they are utility functions used only inside the class. Items that are private will not be inherited.
  3. protected – this means the marked item can only be accessed within the class. It also exists in subclasses! Think of this as halfway between private and public.

Calling Class Operations

Let us quickly look at an example of calling operations(methods)!

<?php
   class classname
   {
      function operation1(){
         //---do something
      }

      function operation2($param1, $param2){
         //---do other stuff
      }
   }
   #create an instance now
   $a = new classname();

   #You then call the operations as you would call any
   #other function:
   $a->operation1();
   $a->operation2(12, 'test');

   #if our operation returns something, you can store it as:
   $x = $a->operation1();
   $y = $a->operation2(10, "sample");
?>

Implementing Inheritance In PHP

If a class is to subclass another class, you can use the extends keyword. Example here: Consider a class B that extends another class previously created by a friend A.

<?php
   class B extends A
   {
      public $attribute2;
      function operation2(){
         //do something here
      }
   }

   class A
   {
      public $attribute1;
      function operation1(){
         //do something here
      }
   }

   #Now you can do these:
   $b = new B();
   $b->operation1();
   $b->attribute1 = 10;
   $b->operation2();
   $b->attribute2 = 5;

   #Since class B extends class A, you can access both
   #operation1() and $attribute1
   #NOTE: inheritance works only in one direction - that is:
   #a subclass can only inherit from the superclass and not
   #the other way round.
   #-----------CONSIDER THIS NOW--------------------#
   $a = new A();
   $a->operation1();  #valid
   $a->attribute1 = 21; #valid
   $a->operation2(); #invalid
   $a->attribute2 =100; #invalid
?>

I am going to stop here then continue tomorrow. I hope you found this helpful. If you have any questions or errors you might have spotted, let me know. There are just a few more concepts that should fit into a single post bringing this OOP topic to an end. Stay safe and hope to see you soon! Please drop me a line in the comment section.

Writing Your Own Functions – PHP

Functions exist in most programming languages and they separate code that performs a single well-defined task. This makes it easier to read and reuse the code. A function is a self-contained module of code that prescribes a calling interface, performs some task and optionally returns a result.

There are several reasons to write your own functions in PHP; for instance if you want to perform a task that other built-in functions cannot help you do. Let us quickly look at an example of a function call before we do function definition.

<?php
  #call a function in php
  function_name();

  #this line calls a function named function_name that does not
  #require parameters. This line also ignores any possible values
  #that might be returned by the function.

  #You might have come across phpinfo() function used to test
  #php version, information about php, the web server setup etc
  #it takes no parameters:
  phpinfo();
?>

Most functions however do require a parameter or more – which are the inputs to the functions. If a function expects a parameter to be passed, you can either pass in the exact value or a variable containing the value. Let us see an example

<?php
   #this function expects 1 parameter (string):
   function_name('parameter');

   #this function expects a number:
   function_name(2);

   #we use a variable as a parameter here
   function_name($age);

   #Consider fopen() function's prototype here:
   resource fopen(string filename, string mode
                    [, bool use_include_path [, resource context]]);

   #The above prototype tells you several things: resource word tells
   #you that the function fopen() returns a resource(an open file
   #handle). The function parameters are inside the parentheses:
   #filename & mode are both strings and then bool use_include_path
   # and lastly
   #context which is of type resource!

?>

The square brackets around use_include_path and context indicate that these parameters are optional.That means you can choose to provide values for optional parameters or you can ignore them in which case the default values will be used. Note that for functions with more than one optional parameter, you can only leave out parameters from the right. In our example, you can leave out context or both use_include_path and context but you cannot leave out use_include_path and provide context.

Knowing the above prototype therefore makes it easier to understand the code below as valid:

<?php
   $name = 'myfile.txt';
   $openmode = 'r';
   $fp = fopen($name, $openmode);

  #the above line calls fopen() passing in $name and $openmode
  #whatever is returned is stored in $fp variable
?>

One common mistake among new php users is calling a function that is not defined. If you do that, you will get an error message! Always check to see if your functions are spelled correctly during definition and check to see if the function exists in the version of PHP you are using.

You might not always remember how the function names are spelled. For instance, some two-word functions have an underscore between the words and some don’t. The function stripslashes() runs the two words together while strip_tags() separates the two words with an underscore.

You will also get an error message if you try to call a function that is part of a PHP extension that is not loaded. It is a good thing to name your functions with lowercase for consistency.

The cool thing about programming languages is the ability to write your own functions. You are not limited to using built-in php functions!

Basic Function Structure in PHP

A function definition starts with the keyword function and then followed by a name, then the parameters required and contains the code to be executed each time this function is called:

<?php
   #define a function
   function my_function(){
      echo 'Hello, my function was called';
   }

   #we can now call our function as follows:
   my_function();   #you can guess the output!

   #built-in functions are available to all php scripts but
   #your declared functions are only available to the scripts
   #in which they were declared. It is a good idea to have a file
   #or set of files containing your commonly used functions. You
   #can then use require() to make them available to your scripts.
?>

Naming Functions In PHP

The main point to consider while naming your functions is; short but descriptive. Consider a page header function – pageheader() or page_header() sound pretty good! There are restrictions to follow:

  • Your function cannot have the same name as an existing function.
  • Your function name can only contain letters, digits and underscores.
  • Your function name cannot begin with a digit.

As opposed to other languages, function overloading – the feature that allows you to reuse function names, in PHP is not supported.

<?php
   //examples of valid function names
   name()
   name2()
   name_three()
   _namefour()

   //examples of invalid function names
   5name()
   name-six()
   fopen()   #this could be valid if it didn't already exist!

?>

Using Parameters In Functions

<?php
   function create_table($data) {
      echo "<table border=\"1\">";
      reset($data); // Remember this is used to point to the beginning
      $value = current($data);
      while ($value) {
         echo "<tr><td>".$value."</td></tr>\n";
         $value = next($data);
      }
      echo "</table>";
   }

   #You can call create_table($data) by passing in values like this:
   $my_array = array('This is Line one', 'This is Line two',
                     'This is Line three', 'This is Line four');
   create_table($my_array);

?>

If you run that simple code, you will get:
functions-testing

Just like built-in functions, your functions can have no parameters, one parameter or more than one parameter. Let us improve our above function to include some optional parameters:

<?php
   #allow the caller to set the border width, cellspacing and
   #cellpadding:
   function create_table2($data, $border=1,
                         $cellpadding=4, $cellspacing=4 ) {
      echo "<table border=\"".$border."\"
                        cellpadding=\"".$cellpadding."\"
                        cellspacing=\"".$cellspacing."\">";
      reset($data);
      $value = current($data);
      while ($value) {
         echo "<tr><td>".$value."</td></tr>\n";
         $value = next($data);
      }
   echo "</table>";
   }

   #Now let us call our function passing in the parameters
   $my_array = array('This is Line one.','This is Line two.',
                     'This is Line three', 'This is Line four.');
   create_table2($my_array, 3, 8, 8);
?>

If we run the above code, we get a much better table because we can adjust the parameter values as we wish. If we don’t supply them, the default values are used! This is what we get on the browser.
better-function

Understanding Scope

A variable scope controls where that variable is visible and usable. Below are the simple rules in PHP to follow:

  1. Variables declared inside a function are in scope from the statement in which they are declared to the closing brace at the end of the function. This is called function scope. These are called local variables.
  2. Variables declared outside functions are in scope from the statement in which they are declared to the end of the file but not inside functions. This is called global scope. These variables are called global variables.
  3. The special superglobal variables are visible both inside and outside functions.
  4. Using require() and include() statements does not affect scope. If the statement is used inside a function, the function scope applies. If it is not inside a function, the global scope applies.
  5. The keyword global can be used to manually specify that a variable defined or used inside a function will have a global scope.
  6. Variables can be manually deleted by calling unset($variable_name) .A variable is no longer in scope if it has been unset.

Example of scoping:

<?php
   #declare a function and a variable inside it
   function fn(){
      $var = "contents";
   }

   #the $var variable declared inside our fn() function has function
   #scope.
   fn();
   #Trying to refer to $var outside our fn() function will create a
   #new $var variable with global scope.It will be visible till the
   #end of the file. Using $var with just echo will return nothing
   #because it has no value at the moment.
   echo $var;

   #The inverse of the above example:
   function fn(){
      echo "inside the function, \$var = ".$var. "<br />";
      $var = 'contents 2';
      echo "inside the function, \$var = ".$var. "<br />";
   }
   $var = 'contents 1';
   fn();
   echo "outside the function, \$var = ".$var. "<br />";

   #-----------------OUTPUT-------------------------------#
   #inside the function, $var =
   #inside the function, $var = contents 2
   #outside the function, $var = contents 1

   #If you want to create a global variable inside a function,
   #you simply use the global keyword (global $my_variable)

?>

Pass By Reference vs. Pass by Value
Let us consider a simple function increment()

<?php
   function increment($value, $amount = 1) {
      $value = $value +$amount;
   }

   $value = 10;
   increment($value);
   echo $value    # 10 - no change

  #-----------------------------Solution-------------------------#

  function increment(&$value, $amount = 1) {
     $value = $value +$amount;
  }

  $a = 10;
  echo $a;   #10
  increment($a);
  echo $a;  #11

  #Explanation:
  #-------------by value -----------------------#
  #If you pass by value, a new variable is created containing the
  #value passed in. It is a copy of the original. Modifying this new
  #variable does not change the original value.

  #----by reference-----------------------------#
  #Instead of creating a new variable, the function receives a
  #reference to the original variable.This reference has a variable
  #name starting with a $ sign and can be used like any other
  #variable. Modifying this reference variable affects the original
  #variable.
  #You specify a pass by reference parameter by using an ampersand(&)
  #before the parameter name in the function definition.
?>

Using The return keyword:

The keyword return ends the execution of a function. Execution of a function ends either after all statements have been executed or the return keyword is used. Consider this example:

<?php
    function test_return() {
       echo "This statement will be executed";
       return;
       echo "This statement will never be executed";
    }
    #Calling the above function will cause the first echo
    #statement to be executed and not the second one!
?>

The above example is obviously not the best way to use return keyword. Normally, you want to use it while checking for some conditions being met or not. Let us see a simple example here:

<?php
    function larger( $x, $y ) {
       if ((!isset($x)) || (!isset($y))) {
            echo "This function requires two numbers.";
            return;
       }
       if ($x>=$y) {
           echo $x."<br/">;
       } else {
           echo $y."<br/">;
       }
   }
   #testing the function
   $a = 1;
   $b = 2.5;
   $c = 1.9;
   larger($a, $b);
   larger($c, $a);
   larger($d, $a);
   #The output is as follows:
   2.5
   1.9
   This function requires two numbers

?>

Returning values from functions
You can simply return values directly from functions as follows:

<?php
   #modified version of larger that use return
   #instead of echo to return the value
   function larger ($x, $y) {
      if ((!isset($x)) || {!isset($y))) {
         return false;
      } else if ($x>=$y) {
         return $x;
      } else {
         return $y;
      }
   }
   #--------------sample test code--------------#
   $a = 1; $b = 2.5; $c = 1.9;
   echo larger($a, $b).’<br />’;
   echo larger($c, $a).’<br />’;
   echo larger($d, $a).’<br />’;

   2.5
   1.9
   #--------------------------------------------#
?>

Implementing Recursion in PHP
Recursion is supported in PHP. A recursive function is a function that calls itself. They are more useful when navigating dynamic data structures such as linked lists and trees. Example:

<?php
   #----------recursive approach-------------#
   function reverse_r($str) {
      if (strlen($str)>0) {
         reverse_r(substr($str, 1));
      }
      echo substr($str, 0, 1);
      return;
   }

   #------------iterative approach-----------#
   function reverse_i($str) {
       for ($i=1; $i<=strlen($str); $i++) {
           echo substr($str, -$i, 1);
       }
       return;
   }

    reverse_r('Hello');
    reverse_i('Hello');

    #calling reverse_r('Hello') will call itself a number of times,
    #with the following parameters:

    reverse_r(‘ello’);
    reverse_r(‘llo’);
    reverse_r(‘lo’);
    reverse_r(‘o’);
    reverse_r(‘’);

?>

The above functions  do the same thing but using recursive and iterative approaches respectively.
With each iterative call in the first function, the length of the string is tested. When you reach the end where strlen($string) == 0, the test fails. One issue with recursion is the memory use. It is up to you to decide which approach fits your taste.

As I end this post, I would like to direct you to PHP documentations where you can find out more. Thanks for stopping by and I hope you found some useful information here. If you have any questions, please let me know through the comments section. If you spot any errors, please let me know as well.

Reusing Code and Writing Functions – PHP

Hello! One thing you will hear everywhere you go as a coder is code reuse – the idea that if someone has already wrote some code that you need, you might want to consider using it instead of spending so much time writing from scratch. You could choose to repeat the process but your boss might not like it very much!

So today, am going to start on code reuse. There are several advantages to code reuse and they include: reduces the cost (you will spend more time maintaining your code than writing it, therefore you want to make sure that you limit the number of lines in use.). In simple terms, less code means lower cost. Secondly, there is reliability – existing mature code is always more reliable than a fresh ‘green’ code. Thirdly, consistency – If you are reusing code that runs in another part of the system, your functionality should automatically be consistent.

Using require() and include()

PHP provides two very simple, yet very useful, statements to allow you to reuse any type of code. Using require() or include() enables you to load a file into your PHP file. The imported file can contain anything you would type in a script including php statements, text, HTML tags, PHP functions, or PHP classes. So what is the difference between the two statements?

Good question there. They are almost identical except for one thing: when they fail, require() construct gives a fatal error, while include() construct gives only a warning.

One more thing to mention here is that there are two variations to require()  and include()require_once() and include_once() and you might have guessed what they mean? They mean that the respective files can only be included or required once! Consider a situation where you have included a file twice without knowing, you will get an error. So, if you are cautious, you might want to try require() or include() because they are faster to execute.

Consider a file named: reusablefile.php

<?php
   echo 'Hello there, this is a reusable code <br />';
?>

And now consider another file named: main.php

 <?php
    echo 'This is the main file for testing stuff <br />';
    require('reusablefile.php');
    echo 'This is where the script ends at this moment <br />';
 ?>

Now the outcome: Running the main.php file will return the page shown:

CodeReuse

How easy was that? So, it is as simple as using an echo statement in between the two lines.

Using require() for website templates

You can use require() while creating a website that has a consistent look and feel. If you want the visitors to see the same header and footer throughout the pages, you simply require those templates in every page. If you want to add new pages, you do the same thing as before, require the header and footer. The only thing that could be different is the content!

So, simply create a header and store it in a file like ‘header.php’ and create another file ‘footer.php’ and then create another file ‘home.php’ and require these two files inside that file! Consider a file home.php

<?php
   require('header.php');
?>
  <p>Welcome to our crazy website where real problems
  get solved, and tough questions answered!</p>
<?php
  require('footer.php');
?>

It is a convention to name your files that you plan to include in other files with a .inc extension (includes). This is not recommended because .inc extensions are not interpreted as php unless the server is configured to do that.

Another alternative is to use auto_prepend_file and auto_append_file. By setting these two properties to point to the header.php and footer.php, you ensure that they will be loaded before and after the page loads! If you use this directives, you will no longer need to use include() on your pages but the headers and footer files will not be optional.

That is good enough for today! I figured I should get those out of the way before moving on to defining and using functions in PHP! Stay tuned and see you tomorrow. Thanks for stopping by and I hope this post helped you learn something. If you see any errors, please notify me so I can fix them.

Regular Expressions – Data Validation In PHP

Hi! I am back from a serious headache and today am going to talk about regular expressions. The idea is to validate data submitted by the users of our online store. This will help us stop taking in invalid emails, or stuff like that. Also, using a new page created for feedback submission, we would like to send the message to respective departments depending on which  words our customers mention in their messages. Let us get started.

Here is my feedback page:

feedbackone

Basically, we don’t want crazy people submitting fake data just to annoy us and to avoid that, we use regular expression. This is a huge subject and I will not exhaust it, instead, I will touch on the basics so that you can go out there for more details.

postfeedback.php file:

<?php
 #Here I define some variables and then check to make sure
 #that they are set in the _POST array.
 $name = '';
 $email = '';
 $feedback = '';

 if(isset($_POST['name'])){
   $name = trim($_POST['name']); //use addslashes
 }
 if(isset($_POST['email'])){
   $email = trim($_POST['email']); //use addslashes
 }
 if(isset($_POST['feedback'])){
   $feedback = trim($_POST['feedback']); //use addslashes
 }

 #This will return an array of two items (an email is separated
 #by an '@' symbol and so the two sides are stored in our array
 $email_array = explode('@', $email);
?>

From the above code, you might have noticed certain new things: trim, addslashes and explode. When trying to store data in a database, you want to do some clean-up to remove any dangerous characters which might be interpreted by the database as commands. To eliminate such uncertainties, you use trim() and addslashes(). explode breaks the string given using the delimiter (‘@’) given and stores the results in an array.

<?php
  #my intention here was to put together some feedback and then email
  #them to the respective departments. So, let us get some variables
  #ready here:
  $toaddress = 'feedback@crazystore.com'; //default
  if(strstr($feedback, 'shop')){    //if 'shop' is in $feedback
      $toaddress = 'retails@crazystore.com';
  }else if(strstr($feedback, 'delivery')){ //if 'delivery' is in..
      $toaddress = 'fulfilment@crazystore.com';
  }else if(strstr($feedback, 'bill')){
      $toaddress = 'accounts@crazystore.com';
  }
  #
  #Even more variables here.
  if(strlen($email) < 6){    //strlen() returns length of string
     echo 'That email address is invalid';
     exit;
  }

  $subject = 'feedback from website';

  $mailcontent = 'Customer name: '.$name .'\n'.
                 'Customer email: '.$email. '\n'.
                 'Customer comments:\n '.$feedback.'\n';

  $fromaddress = 'From: webserver@crazystore.com';

  //invoke mail() function to send the email
   mail($toaddress, $subject, $mailcontent, $fromaddress); //use mail()

?>

As shown above, you might have thought to yourself that there might be better ways to doing the validation! You are right and it is always good to try out different approaches before settling on one.

Other String Manipulation functions:

<?php
   #-------------------------------------------------#
   strstr(haystack, needle); #case sensitive
   strchr();                 #find character match
   strrchr(haystack, needle);#from the end
   stristr(haystack, needle); #not case sensitive

   strpos(haystack, needle)  #returns position (numerical)
   strrpos(haystack, needle) #returns position of
                             #the last occurrence of the needle

   $sample = 'Hello world';
   strpos($sample, 'o');    #returns 4
   strpos($sample, 'o', 5); #returns 7 (3rd param is the starting point)

   #Alternatively:
   $result = strpos($sample, 'H');
   if($result === false){
     echo 'Not found';
   }else{
     echo 'Found at position: '.$result;
   }
?>

Let us assume your customers were really outraged by your service and they just unleashed really mean feedback. To protect your employees, you want to replace every cuss word with some other word. Let us do that!

 <?php
  #--------------------string replacing ---------------------------#
  $offcolor = array('fr***', 'nkdhs', 'k*-^', 'cuss');

  #Now we have our array of cuss words to replace; ($offcolor)
  #So, let us use str_replace() function to achieve this goal
  $feedback = str_replace($offcolor, '%!&@', $feedback);

  #What about substrings? Here is how to replace substrings
  #we have a $test string, we then replace whatever is at position
  # indicated by the 3rd parameter (-1) with 'X'
  substr_replace(string, replacement, start) #replaces a substring
  $test = substr_replace($test, 'X', -1);

  #More string manipulation functions and examples:
  $test = 'Your customers are the best in the world';
  substr($test, 1); //our customers are the best in the world
  substr($test, -10); // the world
  substr($test, 0, 4); // Your
  substr($test, -13); //returns between 4th
                      // character and 13th character-to-last

  #----------------------------------------------------#
  strcmp(str1, str2);     #compare strings
  strcasecmp(str1, str2); #not case sensitive
  strnatcmp(str1, str2);  #case-sensitive
  strncasecmp(str1, str2, len); #not case-sensitive

  #------------------------------------------------------#
 ?>

So far, we have not really used any regular expression functions yet!
I am going to make this as simple as possible to avoid confusion because Regular Expressions are not very easy to understand yet they are so useful!

<?php
   #Regular Expressions - Smart Form
   [a-zA-Z] #both lower and uppercase letters of alphabets
   [a-z]    #only lower-case alphabetical letters
   [aeiou]  #only vowels
   [^a-z]   #cannot be a member of a set

   [[:alnum:]] #------ Alphanumeric characters
   [[:alpha:]] #------ Alphabetic characters
   [[:lower:]] #------ Lowercase letters
   [[:upper:]] #------ Uppercase letters
   [[:digit:]] #------ Decimal digits
   [[:xdigit:]]#------ Hexadecimal digits
   [[:punct:]] #------ Punctuation
   [[:blank:]] #------ Tabs and spaces
   [[:space:]] #------ Whitespace characters
   [[:cntrl:]] #------ Control characters
   [[:print:]] #------ All printable characters
   [[:graph:]] #------ All printable characters except for space

   #repetitions
   [[:alnum:]]+ #------ means --> at least one alphanumeric character

   #subexpressions
   (very)*large ------ matches: 'large', 'very large',son on

   #counted subexpressions
   (very){1, 3} ------ matches -> 'very', 'very very', 'very very very';

   ^crazy #----- matches 'crazy' at the start of a string
   com$   #----- matches 'com' at the end of a string
   ^[a-b]$ #---- matches a single character from a and z

    com|edu|net #----- matches com, edu and net
?>

Let us take a quick look at what characters mean when used outside and inside the brackets:

<?php
#-----------------Outside brackets------------------------|
 # Character | Meaning                      |
 #     \     | Escape character             |
 #     ^     | Match at start of string     |
 #     $     | Match at the end of string   |
 #     .     | Match any character except \n|
 #     |     | Start of branching (OR)      |
 #     (     | Start subpattern             |
 #     )     | End of subpattern            |
 #     *     | Repeat 0 or more times       |
 #     +     | Repeat 1 or more times       |
 #     {     | Start min/max quantifier     |
 #     }     | End min/max quantifier       |
 #     ?     | Mark a subpatter as optional |
 #----------------Inside brackets -------------------------|
 #     \     | Escape character             |
 #     ^     | NOT - if used in initial pos |
 #     -     | Specify character ranging    |
 #---------------------------------------------------------|

?>

We are almost done here. Now that we know some regular expressions, we should be able to use them to validate our data: particularly the email and the message- searching for keywords then determining where to send the message!

<?php
#we check if the $email passes the test here.This will probably
#not work for all kinds of emails.
if(preg_match('~^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}$~i', $email)){
   echo '<p>That is not a valid email address!</p>'.
        '<p>Please try again by visiting the previous page.</p>';
   exit;
 }

 $toaddress = 'feedback@crazystore.com'; //default value
 #we are using the $feedback variable from the start of our post above

 if (preg_match(“shop|service|retail”, $feedback)){ #use | (OR)
    $toaddress = 'retail@crazystore.com';
 }else if(preg_match("deliver|fulfil", $feedback)){ #use | (OR)
    $toaddress = 'fulfilment@crazystore.com';
 }
 else if(preg_match(“bill|account”, $feedback)){    #use | (OR)
    $toaddress = 'accounts@crazystore.com';
 }

 #Always use string functions instead of regex here. This is
 #just an example to demonstrate that you can also use regex
 if(preg_match('bigcustomer\.com', $feedback)){
    $toaddress = 'owner@crazystore.com';
 }
  ?>

Finally, we will look at splitting strings using Regular Exp.

  <?php

    #Splitting strings using Regular expressions
    $address = “username@crazystore.com”;
    $arr = split (“\.|@”, $address);
    while (list($key, $value) = each ($arr)) {
       echo “<br />”.$value;
    }
    #Results ---------------------------------------
    #username
    #@
    #crazystore
    #.
    #com
    #-----------------------------------------------
  ?>

That is it for today. I hope you found this helpful in a way. If you have any questions, please let me know so that I can answer them. Next time we will tackle functions and code reuse. If you  have spotted any errors, please let me know through the comments section and I will really appreciate.

Putting Arrays To Work – Shopping Cart (php)

PART ONE:

Hello! Today, I want to use arrays to improve our shopping cart and find out more about them as we go a long! This post is going to be split into two: Part 1 and 2. You want read them in parts or in full. There are basically two types of arrays in PHP: numerically indexed arrays – where indices start at zero by default and non-numerically indexed arrays – where the keys can be set to whatever you deem meaningful. Let us start with numerically indexed arrays:

#Using the items from our store (oil, tires & spark plugs)
#We can create an array like this:
<?php
    $products = array('Tires', 'Oil', 'Spark Plugs');
    #this creates a $products array containing 3 items
    #just like echo, array() is a language construct rather
    #than a function.

    #You can use range() to create an array of ascending numbers.
    $numbers = range(1, 10);    # 1....10
    #Add a 3rd param to set the step size between numbers:
    $odds = range(1, 10, 2);    #array of odd numbers from 1 to 10

    #You can also use letters with range like so:
    $letters = range('a', 'z');
?>

Accessing Array Contents

To access the content of an array, you need the variable name and an index or key. The index is placed inside square brackets: Let us take a quick look here:

#Using our $products array, we can easily:
<?php
    $products[0]    #Tires
    $products[1]    #Oil
    $products[2]    #Spark Plugs

    #As you can see, element zero is the first element in the array
    #To change elements in our array, we do this:
    $products[0] = 'Fuses';   #replaces Tires with Fuses
    $products[3] = 'Fuses';   #adds Fuses to the array

    #Now we can print out everything in our array like so:
    echo "$products[0] $products[1] $products[2] $products[3]";

    #You can also create the $products array on the fly:
    $products[0] = 'Car';
    $products[1] = 'Cow';
    $products[2] = 'Tablet';    #love a tablet!

    #If $products array does not exist, the first line creates it!
    #As you add elements, the array is dynamically re-sized!
?>

Using Loops To Access Array Data:
Because arrays of this kind are indexed using a sequence of numbers, you can easily use a for loop to display contents


#Consider this example:
<?php
    #We can easily print out the content of the array by:
    for($i = 0; $i < 3; $i++){
       echo $products[$i]." ";
    }
    #I just added a space there to clean things up a bit!
    #Now using a foreach to print out everything!
    foreach($products as $product){    #foreach($array as $variable)
       echo $product." ";
    }
    #Now you have a choice to make - which loop to use and that
    #totally depends on your taste! Freedom is yours!
?>

Arrays With Different Indices:
Instead of letting PHP assign a value of 0, 1 or 2 to our array, we can create our own indices! Let us take a look at how to do this below:

#Using Non-numerical indices:
<?php
    $prices = array('Tires' =>50, 'Oil' => 100, 'Spark Plugs' => 40);
    #The product names are keys and prices are values.
    #In between them are an equal sign (=) and a greater than (>) sign

    #Let us access the contents of our $prices array
    #Like before, we need the variable and a key

    $prices['Tires'], $prices['Oil'], $prices['Spark Plugs']

    #Alternatively, we can create the above array like this:
    $prices = array('Tires' =>100);
    $prices['Oil'] = 15;
    $prices['Spark Plugs'] = 200;

    #Yes, another way to do the same thing is by doing this:
    $prices['Tires'] = 100;
    $prices['Oil'] = 50;
    $prices['Spark Plugs'] = 14;
?>

Using Loops With Non-Numerically indexed arrays:
I figured you might have asked yourself whether you could do the same thing as you did earlier using for loops to print out content! Let us take a quick look here!

#You cannot use a simple counter here because the indices are not
#numbers, and that means we have to use a foreach loop! Cool!
<?php
    #let us print out key : value pairs from our array
    foreach($prices as $key => $value){
       echo $key." - ".$value. "<br />";
    }

    #You can also use a while loop and an each() construct like so:
    while($element = each($prices){
        echo $element['key'];
        echo " - ";
        echo $element['value'];
        echo "<br />";
    }
    #The above while loop will result in something like this:
    #----------|Tires - 100      |----------------------#
    #----------|Oil - 10         |----------------------#
    #----------|Spark Plugs - 14 |----------------------#

    #Let us go rogue here and make this while loop look cooler:
    reset($prices);
    while(list($product, $price) = each($prices)){
       echo "$product - $price<br />";
    }
    #Using list() construct helps to split an array into a number
    #of values. So, we separate 2 values given to us by the each()
    #construct like above.
    #Since the each() construct keeps track of the current element,
    #we simply use reset($prices) to set the current element back
    #to the start of the array!
?>

Array Operators
I am going to list Array operators and briefly describe what they do:

<?php
    #--| Operator | Name      | Example | Result                   |
    #--|    +     | Union     | $a + $b | Array $b appended to $a  |
    #---------------------------------  | Any key clashes not added|
    #--------------------------------------------------------------|
    #--|    ==    | Equality  | $a == $b| True if $a & $b contain  |
    #---------------------------------  | the same elements        |
    #--------------------------------------------------------------|
    #--|   ===    | Identity  | $a ===$b| True if $a & $b contain  |
    #---------------------------------  | same elements same types |
    #--------------------------------------------------------------|
    #--|   !=     | Inequality| $a != $b| True if $a and $b do not |
    #-----------------------------------| contain the same elements|
    #--------------------------------------------------------------|
    #--|   <>     | Inequality| $a<>$b  | The same as !=           |
    #--------------------------------------------------------------|
    #--|   !==    | Non-Identi| $a !==$b| True if $a and $b do not |
    #-----------------------------------| contain the same elements|
    #-----------------------------------| with same types and order|
    #--------------------------------------------------------------|
?>

PART TWO : Multidimensional Arrays

So far, we have been using one dimensional arrays. What happens when you want to store more than one piece of data about each of our products, then we could use a two-dimensional array! Let us take a look:

#Using Multidimensional arrays to store more data
<?php
    #Arrays inside an array showcase:
    $products = array(array('TIR', 'Tires', 100),
                      array('OIL', 'Oil', 10),
                      array('SPK', 'Spark Plugs', 25));
    #Think of a multidimensional array as columns and rows.
    #The top row is row 0 and far-left column is column 0
    #let us access the contents of our multidimensional array

    echo '|'.$products[0][0].'|'.$products[0][1].'|'.$products[0][2];
    echo '|'.$products[1][0].'|'.$products[1][1].'|'.$products[1][2];
    echo '|'.$products[2][0].'|'.$products[2][1].'|'.$products[2][2];

    #Alternatively, using a for loop, we can do the same thing:
    for($row = 0; $row < 3; $row++){
       for($column = 0; $column < 3; $column++){
          echo '|'.$products[$row][$column];
       }
       echo '<br />';
    }

    #Using nested for loops seems cleaner and shorter than trying
    #to access data using the first means.
    #What if you wanted to use column names instead of numbers,
    #You could do the following instead.

    $products = array(array('Code' => 'TIR',
                            'Description' => 'Tires',
                            'Price' => 100),
                      array('Code' => 'OIL',
                            'Description' => 'Oil',
                            'Price' => 10),
                      array('Code' => 'SPK',
                            'Description' => 'Spark Plugs',
                            'Price' => 15)
                );
    #Now let us use a for loop to display some data
    for($row = 0; $row < 3; $row++){
       echo '|'.$products[$row]['Code'].'|'
             .$products[$row]['Description'].'|'
             .$products[$row]['Price'].'|<br />';
    }

    #Also, you can use a list construct like so:
    for($row=0; $row < 3; $row++){
       while(list($key, $value) = each($products[$row])){
          echo "|$value";
       }
       echo "|<br />";
    }
   #You don't have to stop at two dimensional arrays! Think of 3?
   #Assuming we want to put our products in categories, then using a
   #3-dimensional array, we would do this:

   $categories = array(array(array('CAR_TIR', 'Tires', 100),
                             array('CAR_OIL', 'Oil', 10),
                             array('CAR_SPK', 'Spark Plugs', 20)
                             ),
                       array(array('VAN_TIR', 'Tires', 150),
                             array('VAN_OIL', 'Oil', 15),
                             array('VAN_SPK', 'Spark Plugs', 40)
                            ),
                       array(array('TRK_TIR', 'Tires', 300),
                             array('TRK_OIL', 'Oil', 50),
                             array('TRK_SPK', 'Spark Plugs', 60)
                            )
                 );

    #Let us use nested for loops to print the data out!
    for ($layer = 0; $layer < 3; $layer++) {
        echo "Layer $layer<br />";
        for ($row = 0; $row < 3; $row++) {
            for ($column = 0; $column < 3; $column++) {
                echo '|'.$categories[$layer][$row][$column];
            }
            echo '|<br />';
        }
    }

?>

Sorting Arrays
Let us take a look at what sorting means as far as arrays are concerned:

<?php
    #Using sort()
    $products = array('Tires', 'Oil', 'Spark Plugs');
    sort($products)   #alphabetically ascending order
    $prices = array(100, 45, 300);
    sort($prices)     #numerical ascending order

    #Other Sorting functions
    $prices = array( ‘Tires’=>100, ‘Oil’=>10, ‘Spark Plugs’=>4 );
    asort($prices);    #asort() sorts values rather than keys
    ksort($prices)     #ksort() sorts keys rather than values

    #All the above sorting methods sort in ascending order.
    #To do the sorting in reverse, they have corresponding functions
    rsort($prices);
    arsort($prices);
    krsort($prices);

?>

Sorting Multidimensional Arrays
Sorting multidimensional arrays is more complicated than one-dimensional arrays! Let us do something here really quick:

<?php
    #Using our previous array example:
    $products = array( array( ‘TIR’, ‘Tires’, 100 ),
                       array( ‘OIL’, ‘Oil’, 10 ),
                       array( ‘SPK’, ‘Spark Plugs’, 4 ) );

    #Now we need to write our own comparison function
    #then we will pass it to usort()
    function compare($x, $y){
       if($x[2] == $y[2]){
          return 0;
       }else if($x[2] < $y[2]){
          return -1; #keep an eye on this value
       }else{
          return 1;  #look carefully at this
       }

    }
   #Now we can sort!
   usort($products, 'compare');
   #after this sorting, our products will be sorted in ascending
   #order by price!
   #To sort by a different order, you can write another function
   #To do a reverse sort, use (rsort(), arsort(), krsort()

function reverse_compare($x, $y){
       if($x[2] == $y[2]){
          return 0;
       }else if($x[2] > $y[2]){
          return 1;  #Now keep an eye on this. See something?
       }else{
          return -1; #Now look at this. See anything?
       }

    }
    usort($products, 'reverse_compare'); #descending order by price
?>

Reordering Arrays
For some reasons, you might want to manipulate the order of your arrays. You can do this using shuffle() and array_reverse().
Consider our simple shopping cart: assuming we wanted to display random photos of our products for customers to see. All we would have to do is create an array of images and then pass them to shuffle function! Simple!
array_reverseve() function takes an array, creates a new one with the same content in reverse order.

That is good enough for today! Phew! I know, longer than I had thought.
I should mention that although this post has so much details on Arrays, there are a lot more concepts that are available to you through the documentations. There are other functions, like count(), sizeof() and more. I highly recommend trying them out yourself and seeing what exactly is going on! I promise to shorten my next posts! Thank you for stopping by and I hope this was helpful to you. Got questions? Please ask and we can answer them together! See you soon!

Storing Data Using Files in PHP – Shopping Cart

Hi! After adding some functionality to our shopping cart, I am going to do something different today: storage. Assuming we want to collect all the orders from customers and store them in a file somewhere for later use, we can easily create a file and write and read to and from it. I have altered the original look of our simple cart by adding a new input area for shipping address: Let us look at it now.

snapshot1

Adding that single input area is obviously not a big deal but if you have done any online shopping before, there is a good chance you were prompted to enter your shipping address! Now let us take a quick look at the results of submitting your order!

snapshot2

Simple enough, the Address information is now included in the summary! Everything looks great. Now, we both know that just displaying the summary of orders might not be the best way to get the job done – assuming you have a million orders or something. So, to solve this problem, we need to save the orders in a file. We can then retrieve the orders and process them before fulfilling them. So, using a new file, vieworders.php here is what I have done already:

snapshot3

Now we are not worried about anything getting lost because we can look into our file and fetch the orders. That is good. I know you might be asking, but is that the best way to do this kind of job? The answer is NO. Using plain text files is not the most efficient way and the reason why am using it here is to demonstrate why we will need to use a database management system for anything important! Let us look at how to write data into a file.


#from within store.php we add some new lines of code here
#writing data into files stored in my machine

<? php
  $fp = '';
  //create a folder in your directory (orders)
  $fp = fopen("C:\\orders\orders.txt", 'ab');
  flock($fp, LOCK_EX)       #lock the file - file cannot be shared
  if(!$fp){
    echo "<p><strong>Your order could not be completed at this time."
          ."Please try again later</strong></p></body></html>";
    exit;
  }
  else{
    //that means there is no error and we therefore
    //can write to a file

    $outputstring = $date." \t". $tiresqty." tires \t". $oilqty." oil\t"
                  .$sparksqty." spark plugs\t\$".$totalamount
                  ."\t". $address."<br />";

    fwrite($fp, $outputstring);  //write data to file
    flock($fp, LOCK_UN);         //release existing lock
    fclose($fp);                 //close the file!
  }
?>

That is all you need to write to a file. So what did we do here? A few things: first, create a variable $fp (file pointer) and then use PHP’s file open function (fopen()) which takes several parameters. First, the file path and then others. As you can see, I added ‘ab’ as the second param (a – (writing only) for appending to the end of existing content if any. If the file doesn’t exist, try to create it. b – (binary) differentiates between binary and text files – recommended for portability.

I then applied a lock to the file to disable sharing it. I then check to see if the file pointer exists, if not, then inform the customers politely that their order was not processed. Otherwise, go ahead and write their order to our file using fwrite() function. Then remove the lock and finally close the file.

Let us finally take a look at our vieworders.php file which we use to read data from our file as we process them in our parents’ garage!

<?php
    $fp = fopen("C:\\orders\\orders.txt", 'rb');
?>

<html>
   <head>
   <title>Crazy Auto Orders</title>
   <link rel="stylesheet" type="text/css" href="index.css" />
   </head>
   <body>
      <div class="container">
         <h1>Crazy Auto Store Inc </h1>
         <h2>Customer Orders: </h2>
         <?php
            if(!$fp){
              echo '<p><strong>No orders pending.'
              .'Please try again later</strong></p>';
             exit;
            }
            flock($fp, LOCK_SH);
            while (!feof($fp)){
               $order = fgets($fp, 999);
               echo $order. "<br />";
            }
           flock($fp, LOCK_UN);
           fclose($fp);
         ?>
       <p>Copyright 2013 &copy; Crazy Auto Store Inc </P>
     </div>
   </body>
</html>

Description:

Once again, on top of our file we create a file pointer variable $fp and use file open function fopen() passing in the path and a second param (‘rb’ – r (opens the file for reading from the beginning) and b – for binary differentiation – recommended by PHP developers!).

Just like before, we check to see if the pointer exists and if not, give the user a friendly message to try again later. If it exists, we use LOCK_SH to enable reading lock. The file can be shared with other readers. Using a while loop, we check to make sure that we have not reached the end of the file (feof – file end of file) and output the data one line at a time using fgets() function.

Last but not least, we release the lock and lastly close the file. That is all.

There are so many reasons why this is not the best approach and that is why database management systems were created. I will briefly mention a few:  The speed is affected if our files grow and so reading the data becomes a big challenge. Secondly, searching for a particular group of records is difficult. Another one could be a situation where more than one user is trying to access our file at once – concurrent access. This can become problematic even while using locking. It is hard to enforce different levels of access to data. Those are just a few and if you are interested in finding out more, I would recommend checking out the php documentations .

NOTE: This example does not include everything that file writing and reading entails. With that being said, there are a lot of information online on how to read and write files (functions and such) – this is just a small piece of it. I just touched on the tip of the iceberg here.

If you have any questions, spotted any errors or comments, please leave them below this post using the comments section. Thank you for stopping by and I hope you enjoyed building this shopping cart with me. See you soon!

Building A Shopping Cart – Part 2

Please Visit The Post’s New Location Simple Developer

Hi! I had promised to improve our simple shopping cart by adding some functionality to it. Today therefore, I have added a drop-down list to our web store so that customers can select an option describing where they found our store. It could be through television ads, phone directory, word of mouth or other sources. So, without much ado, am going to show you how our page will look like then share the php and html code.

crazy-php-html-code

As you can see above, you get a list of different sources. Now, in the next snapshot, I am going to show you another feature that I added to dynamically display a table which you can use to determine your shipping cost. I used a for loop to generate it. Cool!

store-image-php

You might have noticed something new in the above snapshot: the total costs and taxes inclusion. There is also the table shown by the arrow. Now, if you select an option from the drop-down, it will be displayed just below the total amount! Now let us take a look at the code.

php-code-image

Simply click on the above image for a closer view of the entire code. This code contains some pieces from the first Shopping Cart Part I and then the calculations and constants definition and usage.

Now let us take a quick look at how selections are used in html markup. It is easier than you might think:

referral-code-selection

What I did here was to simply add a <div> tag just below what I had in my first post. I added to the same file! Again, please click on the image to see the code clearly. Now let us take a look at the switch statement that utilizes the values returned by the above selection:

switch-statement-code

As you can see, using a switch statement is much better than using a lot of if else statements. I went a head and added the code to dynamically generate the table that shows the distance ::: shipping information. I used a for loop! Please click on the image to see a clear version of the image. I apologize for that!

That should do it for today! I know it is not that complicated but I thought it was good for me to start small and then move on to intermediate levels. I really liked reading through the PHP documentations and I think everyone trying to learn how to do scripting using PHP should give it a substantial amount of time. Thanks for visiting and if you have any questions or see any errors, please don’t hesitate to drop me a line using the comments! I will really like to connect with you!

Take care and see you soon!

Building A Simple Shopping Cart Using PHP

Please Visit The New Post Location Simple Developer

Hello there! When I started learning PHP, I began like most other people; the basics. I then promised to show you how to create a simple shopping cart. I have to warn you beforehand, this is not really a complex version. I figured it is smart to start with a simpler version then add more functionality to it as we proceed. So, let us get to it. I am going to do this in reverse, that is, show you snapshots of the cart then dissect the code. So, here we go!

shoppingcart

Assuming you were looking for oil, spark plugs and tires for your good old truck, you would visit Crazy Auto Store and add them to the cart. As shown above, you enter the quantities into the input area. Simple right? Assuming you have done that, and hit ‘Submit Your Order’ button: Here is what you will see:

confirmationpage

Yeah, when I said it was going to be simple, I meant it. Now let us take a look at both the [HTML] and [PHP] that made the above possible!

HTML FILE (store.html)


<!DOCTYPE html>
<html>
    <meta charset="utf-8">
    <head>
        <title>Crazy Auto Store</title>
        <link rel="stylesheet" href="index.css" />
    </head>
    <body>
        <div class="container">
          <form action="store.php" method="post">
             <h1>Welcome To Crazy Auto Store!</h1>
             <hr />
             <label for="oil">Oil Quantity: </label><input type="text"
             name="oil" max="3" maxlength="3" /><br />
             <label for="sparks">Sparks Quantity: </label><input
             type="text"
             name="sparks" max="3" maxlength="3" /><br />
             <label for="tires">Tires Quantity: </label><input
             type="text" name="tires" max="3" maxlength="3" /><br />
             <br />
             <button type="submit">Submit Your Order</button>
             <br />
             <hr />
             <div id="footer">
               <p>Copyright 2013 &copy; Crazy Auto Store Inc</p>
             </div>
         </form>
        </div>
    </body>
</html>

That is the html file (store.html). As you can see, I linked an external css file for presentation. Now that we have got that out of the way, we can look back at the first snapshot and see where it came from. Let us get the PHP file started.

PHP FILE (store.php)

<!DOCTYPE html>
<html>
    <meta charset="utf-8">
    <head>
        <title>Crazy Auto Store</title>
    </head>
    <body>
        <div class="summary">
           <h1>Below is your order summary:</h1>
           <hr />
           <?php
               //declare the variables here
               $oilqty = 0;
               $sparksqty = 0;
               $tiresqty = 0;
               $total = 0;

               //Now let us get the values from the form
               if(isset($_POST['oil'])){
                  $oilqty = &$_POST['oil'];
               }
               if(isset($_POST['sparks'])){
                  $sparksqty = &$_POST['sparks'];
               }
               if(isset($_POST['tires'])){
                  $tiresqty = &$_POST['tires'];
               }
               $total = $oilqty + $sparksqty + $tiresqty;
               echo '<b>You ordered on </b>'. date('H:i, jS F Y'). ':';
               echo '<br />';
               echo '<b> '.$oilqty. '</b> Oil Containers <br />';
               echo '<b> '.$sparksqty. '</b> Spark Plugs </br />';
               echo '<b> '.$tiresqty. '</b> New Tires <br />';
               echo '<b> '.$total. ' Total Items </b>';
           ?>
           <hr />
           <p>Copyright 2013 &copy; Crazy Auto Store Inc </p>
        </div>
    </body>
</html>

Again, I used my own css here. This should do it. That is all you need to accomplish what I showed you in the snapshots. Easy right? Just a brief explanation for the php file:
You might have noticed a couple of things: isset() and $_POST[]. I used the isset() method to check whether the values of (oil,sparks, tires) are set in the $_POST[] array. So I have already answered the ‘what is the $_POST[]’ thingy. When you click submit after filling up the form, the data you entered is stored in that $_POST array, that way, you can access them later and do some calculations or magic!

Next time, I will be building on top of what I did today, to add more functionality to our shopping cart! Think about shipping, discounts and more stuff! I hope to see you around and if you have any questions, please let me know and I will be glad to talk to you. Take care!

NOTE: Please Visit my brand new blog at

Simple Developer

Thank you!