• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » PHP » PHP Tutorials

PHP Tutorials

How to Checking MySQL NULL values with PHP

By Dinesh Thakur

It is useful to verify that all fields are NULL in MYSQL to query data from a database so they can be treated differently from fields with numeric values ​​or text. NULL indicates an unknown value, which is different from a default value, such as 0 or ‘ ‘. You can use the PHP function “is_null” to tell if a returned MYSQL field is NULL or not.

1. Open your PHP source code in a text editor such as Notepad.

2. Use the “mysql_query (query)” function to send a query to the active MYSQL database. For example, “$result = mysql_query (“Select row from Tname”);”.

3. Use the “mysql_fetch_assoc ($result)” function within a “while” loop to fetch rows from the MYSQL result. For example, “while ($row ​​= mysql_fetch_assoc ($result)) “.

4. Use the “is_null (variable)” inside “while” loop to determine if a field of a returned row has a NULL value. For example, if (is_null ($row [“LName”])) {echo “is null”;}} “will print” is null “values ​​for any ” row ” which are NULL.

5. Save the PHP below file and run.

<!DOCTYPE html> 
<html>
<body>
  <?php
   $result = mysql_query ("Select row of Tname");
   while ($row ​​= mysql_fetch_assoc ($result))
     {
       if (is_null ($row ["LName"]))
         {echo "is null";}
     }
 ?>
</body>
</html>

Differences between PHP Code & Redirect 301

By Dinesh Thakur

The word “code” has two meanings in operation of computers. The first one is Number or Symbol that representing another meaning. An example of this type of code is “301”, which is a code specified in the HTTP to signify. The 301 redirect is the most effective way for you to change the content of a page or site to another without losing the PageRank of the page and the domain that migration. Discover all you need to know to migrate page or domain without losing position in Google. The other meaning of “code” in computing is “programming code” a “permanent redirection”. PHP is a programming language for web pages. You can use the PHP code to create a redirect. Redirection redirect or forwards visitors to a web address to another Web address, usually because the original page changed its address. The user is automatically forwarded to the new page location, and usually do not even notice that the address on the top of the browser has changed.

Hypertext Transfer Protocol

The HTTP specification contains a list of status codes. All web servers and Web browsers to know these codes. The code 301 means “Permanent Redirect” and the code 302 means “temporary redirect.” An HTTP message contains a section called “headers” and a message body. When a web server responds to a request for a redirected page, it sends a simple message with an empty body. One of the HTTP headers will contain the redirect code, or 301 or 302, and the new page address. The web browser knows that when it receives such a message, must reapply immediately to the page with the new address.

PHP

PHP is a programming language that generates web pages. The language contains a number of functions, one of which is “header ()”. The function header has two shapes. Receives an HTTP code phrase as a parameter, the other has a “Local” parameter, which is a function that creates a redirect. A PHP program file must exist at the site of the old page, and the request arrives will only activate this program, if the page was generated by a PHP program with the same name.

Coding for Code

The header function creates a 302 redirect by default if no HTTP code was created before being called to the “Local” parameter. The value for the location parameter is the new address for the page. A 301 redirect is required, the function must be written twice: once to create the 301 code for the function and then again to implement the redirection with the parameter location. This PHP code simply requests that the Web server to send an HTTP code, or 301 or 302.

Defining a class in php

By Dinesh Thakur

In this Tutorial, you will create your first object, which will be an instance of a physical address class. As you will be building your examples using this class, you will want to save it as you progress.

In your editor or IDE now, create a new file. The same PHP file-naming conventions apply to files that contain classes.

Many coding standards have file-naming and content conventions as well.

For readability, let’s name the file containing the example class something logical: class.Address.inc.

I am using the extension INC, short for include, to indicate that this file is intended to be included and not executed on its own.

In PHP, a class definition always begins with the keyword class, followed by the name of the class. There are three PHP rules regarding the naming convention used for classes.

In particular, the class name must start with a letter or underscore; the remaining characters must only consist of letters, numbers, or underscores; and there is no limit on the length of the class name.

There are best practices for naming a class to aid with code readability and portability across multiple developers. Those conventions differ between coding standards, but a common theme tends to be the use of upper camel naming and avoiding the word class in the name.

Upper camel naming means the first letter of each word is capitalized. This is a variation of CamelCase, which does not specify whether or not the first letter should be capitalized.

This helps visually differentiate between an instance and an object.

Following the class name is a pair of curly braces that enclose any attributes, known as properties, and functions, known as methods, that belong to the class.

PHP allows the contents of the class to be empty,

Here are some practical examples of class creation in PHP.

class Address.

This is valid as it starts with a letter, and the remaining characters are also

letters. class PhysicalAddress and class Physical_Address.

Each of these is valid and follows common best practices for capitalization. The use of underscores for word separation differs between coding standards.

class physical_address, but this time in lowercase.

This is valid but not a best practice, as each word does not start with a capital letter.

class 21_jump_street.

This class name is invalid.

It will trigger a parse error, expecting T_STRING because it starts with a number.

Why should you use object-oriented programming

By Dinesh Thakur

Object-oriented programming allows you to organize a large project into manageable pieces. In comparison, procedural programming is a set of instructions, step by step, that the computer must follow.

A procedural program can consist of a series of conditions and function calls for logic, but the end result is very linear. There is nothing intrinsically wrong with procedural programming, and for small projects it can be an appropriate practice.

The problem comes when you scale up.

You may find yourself defining arrays with long descriptive keys, or passing large numbers of global variables between scripts, or searching for a nonfatal bug across a dozen scripts with thousands of lines of code with little indication of which component is at fault.

With that in mind, object-oriented programming introduces structure and principles aimed at mitigating procedural scaling and maintainability issues.

A number of features of object- oriented programming include:

Abstraction, which defines data and program structures using a representation of the meaning while hiding the implementation itself–this allows for the use of human-readable terminology to be used as part of the software solution;

Encapsulation, which exposes functionality while restricting access to low-level components and data;

Hierarchy, where attributes and behavior from pre-existing classes are inherited, allowing for incremental development; modularity, where functionality is broken into modules that accomplish one task and contain everything necessary to complete said task–instead of trying to deal with one large problem, a number of smaller sub problems work in conjunction with each other; and polymorphism, which is the ability to interact with classes without having to know what class they are.

By implementing this technique, the compartmentalized components can be maintained and expanded without affecting the overall architecture, which in turn reduces overhead.

What is an Object and class in PHP?

By Dinesh Thakur

Object: In computer science a primitive data type is a basic type of data provided by programming language. Some examples of primitive data types in PHP include Booleans, which are a logical data type containing true or false; floating-point numbers, also known as floats, which are numeric data type that have fractional values–examples include 36.2 and -25; integers are a numeric data type that hold a whole number without any fractions–examples include -6 and 42; and strings, which contain a sequence of characters such as “ecomputernotes.com.” With that in mind, an object is a complex data structure along with attributes and behaviors.

In contrast with the basic data types, such as a primitive that consists of a single value, an object can have multiple data types, each with their own values.

For example, a string containing the words “Toronto” is a simple data type with a single value.

In comparison, an object representing a physical address may have multiple data types, each with their own values, such as a street number, city, and subdivision.

The value stored for the city could be a string containing the words Toronto. Each value in an object is known as a property, which will be explored in greater depth in a later segment.

Class: A class is a blueprint that defines the attributes and behaviors that makes up an object. Objects are instances of a class, meaning each occurrence of an object of a particular class has all the attributes and behaviors of that class.

The individual attributes will be the same, but the contents of those attributes may differ. Each class modularizes program functions by separating distinct features with as little overlap as possible. Using the example of a physical address again, you can define a class for an address.

The class address has several attributes, like the city and subdivision, and has a behavior of being able to look up a postal code given these attributes; therefore, any object of class address will have those attributes and behavior.

Conceptualize two objects that are instances of an address.

As each object is an address, I know that they should have it least the city and subdivision, so I can look up the postal code. I can’t anticipate the contents of the object attributes, but I do know that they will be in a particular format, and how to access them.

PHP: Why it is not advisable to use short tags …

By Dinesh Thakur

As you all know, any PHP script must be surrounded by specific tags. They allow the interpreter to know where in the file is PHP code to execute. On ecomputernotes.com, all presented scripts use the <? Php and ?>; and it is not by chance …

The various PHP code boundary markers

There are indeed several syntaxes PHP tags. Here they are detailed in the following list:

• <? php and ?> (formal language tags)
• <? and ?> (very short tags used by novice webmasters)
• <? = And ?> (Rarely used)
• <% And %> (tag from the ASP language – rarely used)
• <script language = “php”> and </ script?> (rarely used)

Why choose <? Php and ?> ?

Simply becaufe tags <? Php and ?> Ensure full portability on all servers and all versions of PHP. These are the tags default PHP.

However, “short-tags” could prevent the execution of your scripts for the following two reasons:

• The server that hosts your php pages disables the use of these markers by the php.ini directive short_open_tags placed to off.
• It there’s confusion with the opening tag of an XML file.

Indeed, an XML file begins with the following syntax:

Introduction to an XML file

<? xml version = “1.0” encoding = “utf-8” standalone = “yes”?>

Note the presence of the short tag <? at the beginning of the code and?> at the end. When reading the file, the interpreter PHP will attempt to execute this line (thinking it’s PHP) and return a parsing error similar to the one below:

Syntax error: conflict between the interpreter and the PHP XML file
Parse error: syntax error, unexpected T_STRING in /Applications/MAMP/htdocs/CodePHP/xml.php on line 1

The only way to solve this problem is to generate the XML code using an echo statement () for example.

Solution to avoid this conflict
<? php
echo '<? xml version = "1.0" encoding = "utf-8" standalone = "yes"?> "," \ n ";
?>

Secure your passwords with hashes in PHP

By Dinesh Thakur

A password is an extremely sensitive and given coveted by pirates, irrespective of the application that uses it. When the password becomes known to a third person, then the latter can for example take ownership of rights in an application and compromise its normal operation.

What is a password?

Metaphorically, a password can be seen as a key opening a / door (s) to the one who holds it. Thus, this user appropriates additional rights that others do not have. It then up to him not to disclose it to the privileges conferred upon him are not diverted by a third person with bad intentions.

When / passwords must be saved in an information system (database, configuration files, …), it gets more complicated. Indeed, security is hanging by a person but is now based on the security of the information system itself (physical access credentials to connect it) and how these are stored passwords in SI.

Security passwords in an information system

It is evident that increased protection of passwords in the information system must be established. Storing passwords in clear text in the information system becomes impossible. What for ? Take the typical case of a database that stores user IDs of an extranet a company. This implies that a security policy at several levels of rights.

A technician will not have the same privileges on the application that her supervisor. The latter will also have the same rights as the HR director or CEO. In this application, the password is the guarantor of the security of data. We must therefore protect it diligently. A use of encryption becomes indispensable.

Why encrypt sensitive data in an SI?

The answer is simple. This is to keep confidential the password that has been assigned to the user out of the application. It there’s also a part of ethics since even responsible for the application should not to know the personal login users. This does not concern him. Returning to our example.

Who says extranet also said access to the application from the Internet. It is then advisable to encrypt data over a secure HTTPS connection and protect the application against possible hacker access. Say this extranet has been poorly written and it includes a SQL injection flaw. An attacker could then retrieve the passwords stored in the database and enter the application without problems with the identifiers of the CEO. If passwords are encrypted, the hacker will have even more trouble finding their correspondence in the clear. In this example, the attack comes from outside but what is so weak system is right inside of it?

Indeed, suppose that we should maintain the database by connecting directly above. The company who published the application sends its data base administrator intervention. This technician intervenes on site but makes no part of society that uses the application. Yet she will manipulate the database. Ie it can probably see everything in it is inside … including logins. If the passwords were stored in clear, he could appropriate the access of any user on the extranet application … Still, nothing prevents to create a new user with all rights directly into the database. We will see later that a traditional encryption is not enough to strengthen the security of a password.

Encryption methods

There are many. This can range encryption algorithms (which can be decrypted with the algorithm and the proper key) to the hash algorithms. Rather, it is the latter that we tend to use today. Indeed, a hash algorithm to encrypt a string with no possibility of reverse operation. The result of the hash generally produces a single chain and of fixed length. This is the case for example with MD5 and SHA1 algorithms. Thus, during an authentication phase, no longer compares two passwords in clear but two password hashes.

Password Hasher MD5

Example of hash with md5 ()
   <?php
      $md5 = md5 ('m9tS3Q6ll9');
    ?>

The variable $ md5 then contains a unique string composed of hexadecimal characters and a length of 32 characters.

Hasher a word to pass with SHA1

Example of hash with SHA1 ()
<?php
$sha1 = sha1 ('m9tS3Q6ll9');
?>

The variable $ sha1 here contains a unique string composed of hexadecimal characters and a length of 40 characters.

Why simple hashes are not enough?

This method can effectively encrypt strings but remain “crackables”! ” Really ? Yet it was written earlier that we could not achieve the reverse !!! ” Effectively ! Nevertheless there are on the Internet “rainbow tables” (dictionaries) able to turn around the light chain md5 (), a sha1 () or other standard hash algorithm. No need to remind that conventional passwords root type superadmin, foo … exist in these dictionaries. As long as the original password is a dictionary word, it is likely that we can find it in a rainbow table from its hash.

Hasher passwords with ‘salts’

This technique consists of the concatenation of one or more keys (also called “salt”, “seed” or “seed”) the password and the hashed string created. Of course, the / keys must remain secret in an application configuration file. A simple example of password hashes from two seeds.

Password Hash with salts
<?php

// Declare the constants
define ('PREFIX_SALT', 'Ram');
define ('SUFFIX_SALT', 'Raj');

$hashSecure = md5 (PREFIX_SALT.'m9tS3Q6ll9'.SUFFIX_SALT);
?>

In this example, we will finally MD5 hasher with the following string: Ram9tS3Q6ll9Raj

So the MD5 of this string will be completely different from the one MD5 password.

What then is the advantage of this technique?

This technique can not easily recover the original password in plain text in a rainbow table from MD5. Security password so is the complexity and confidentiality selected key.

Returning to our example, starting by considering that the passwords are hashed this time with this method before being stored in a database. The malicious technician working on the database can try to crack the passwords from a rainbow table, it will not succeed because it does not know the seeds used and employed encryption method. Similarly, if it recognizes the format of MD5 passwords, and it saves the password in this format, it will not work at the time of identification. Indeed, the hash of the concatenation of the password entered and two seeds will not match the hash he recorded just before the database.

Can this technique be used outside the passwords?

The answer is yes! This technique is used to encrypt the information placed in a hidden form field or a cookie. The technique of seed serves in particular to verify the integrity of data recorded between each page. This means that if the hash does not match the expected hash is that the client has changed the information on her side to try to chip away your application. It will be possible to apply the appropriate treatment: error message, ban the user for a while …

PHP Iterator interface

By Dinesh Thakur

The conditional structure “foreach” when you allowed to browse the contents of a table. With version 5 of PHP, you can now browse an entire object to retrieve its properties.

Reminder of Interfaces

An interface is a way to contract with a class, to ensure that it will have much of certain methods / properties. Unlike inheritance, it is possible to implement multiple interfaces, allowing to overcome the inability to use multiple inheritance in PHP.

The Iterator interface

The native interface Iterator has existed for some time in Java and provides a significant advantage in terms of object oriented programming. Here’s what the code looks like the Iterator interface:

<?php
    Interface Iterator
   {
        public function rewind();
        public function key();
        public function current();
        public function next();
        public function valid();
    }
?>

Browse an object with foreach ()

<?php
    class MyClass {
        protected $arg1 = 'Good' ;
        protected $arg2 = 'Bye';
         //...
     }
      $c = new MyClass();
      foreach($c as $key=>$value) {
      echo $key, ' : ', $value, '<br/>';
   }
?>

This will print:

arg1 : Good
arg2 : Bye

This is where the Iterator interface. She will indeed help you customize the behavior of foreach. Implement this interface in your class requires you to overload (or redefine) the following 5 methods: rewind (), next (), key (), current () and valid ().

<?php
    class MyClass implements Iterator {
      protected $n;
      const MAX = 5;

      public function rewind() {
          $this->n = 0;
       }

      public function next() {
           $this->n++;
       }

       public function key() {
           return 'increment '.$this->n+1;
       }

      public function current() {
           return $this->n;
       }

       public function valid() {
            return $this->n<=self::MAX;
       }
}
      $c = new MyClass();
         foreach($c as $key => $val) {
           echo $key,' : ',$val, '<br/>';
        }
?>

This will print:

increment 1: 0
increment 2: 1
Increment 3: 2
increment 4: 3
increment 5: 4

These methods will be called by foreach, in this order:

1. rewind at the first iteration, which allows you to rewind your item (here it gives $ n 0)
2. valid which verifies that one does not arrive at the end of the iteration (where $ n is less than the maximum number of iterations set by the constant MAX). If valid returns TRUE, if it continues we stop, it’s the end of the iteration.
3. which returns the current value of the current iteration (here $ n)
4. key which returns the key of the current iteration (here key. $ n)
5. next that starts the next iteration (here, $ n is incremented by 1)
6. Is recalled after the valid () method that checks again that we did not come under Iteration.

Note [1]: A class can not implement two interfaces that share, however, function names.

PHP Exception Handling

By Dinesh Thakur

The exception mechanism was introduced in version PHP 5 in addition to its new object-oriented model. Just as in Java, C ++, ActionScript 3, or Visual Basic (to name only these programming languages), exceptions to simplify, personalize and organize the management “errors” in a computer program. Here the word “errors” does not mean “bug”, which is an abnormal behavior of the developed application, but “exceptional cases” to treat differently in the program sequence. Let us therefore how the exceptions. [Read more…] about PHP Exception Handling

PHP Abstract Classes and Methods

By Dinesh Thakur

PHP integrates another concept of object-oriented programming: abstract classes. This course defines and introduces the concept of abstract classes. We will present what abstract classes, what they are used for development and how to declare and use them. Finally, we will study the particular case of final classes and methods involved in the security of the code object oriented programming.

Presentation and reporting abstract classes

Defining abstract classes

Abstract classes enroll more in the safety of the object oriented programming. The first feature of an abstract class is that it can not be instantiated (and thus create an object). From this statement, we deduce logically that an abstract class is declared to be derived in concrete classes.

An abstract class acts like a typical concrete class. That is to say, it can declare attributes and traditional methods that will be accessible in derived classes. Depending on the chosen course visibility (public, private, and protected) for each of the attributes and methods.

Until then, there is no change from the concrete classes except the fact that we can not instantiate abstract classes. This is where the abstract methods. We will see later that a class declared abstract can also define abstract methods. The latter will have to be redefined in derived classes. It is a way of ensuring that the derived class will adopt the desired behavior.

Declaration of an abstract class

The declaration of an abstract class is realized using the keyword “abstract”. Take the example of an abstract class “HumanBeing” that will, for example, derived by two concrete classes “Male” and “Femal”.

Declaration of an abstract class
<?php
   abstract class HumanBeing
     {
         protected $sex;
         protected $name;
         public function setName ($name)
         {
             $this-> name = $name;
         }
         public function getName ()
         {
           return $this-> name;
         }
         public function getSex()
         {
           return $this-> sex;
         }
   }
?>
If we attempt to instantiate this class to create an object of type HumanBeing, we will get the error message below:
Fatal error: Can not instantiate abstract class in HumanBeing /Users/Tutorial/abstract.php on line 35
We now focus on the other subtlety of abstract classes: the abstract methods.

Declaration and redefinition of abstract methods

An abstract method is declared using the keyword “abstract”. It is a partially defined in the class method. Indeed, when an abstract method is declared, it only defines its prototype (signature). Derived classes must necessarily redefine completely (body + prototype) all abstract methods of the parent class.

Returning to our previous example and add some abstract methods to our abstract class “HumanBeing”.

Declaration abstract methods

<?php
   abstract class HumanBeing
   {
       protected $sex;
       protected $name;
       abstract function toSports();
       abstract function toEntertain ();      
       public function setName ($name)
         {
           $this-> name = $name;
         }
       public function getName ()
         {
         return $this-> name;
         }
       public function getSex()
         {
         return $this-> sex;
       }
   }
?>

Our class now has two new abstract methods to toSport () and toEntertain (). As we can see, the bodies of these two methods is not defined. We will have to define in derived classes.

Note: Any class that defines one or more abstract methods must be declared abstract as well.

That is why we will now define two classes “Man” and “Woman” who will inherit both the properties and methods of our abstract class. Simply start with reporting and attempt to instantiate.

Declaration of derived classes

Declaration of derived classes Man and Woman

<? php
    class Man extends HumanBeing
    {
        / **
        * Built Man object
        *
        *param String $ name Human Name
        *return Void
        * /
        public function __construct ($ name)
        {
            $ this-> name = $ name;
            $ this-> sex = 'M';
        }
   }     class Female extends HumanBeing
     {
          / **
          * Built Object Woman
          *
          *param String $ name the woman Name
          *return Void
          * /
          public function __construct ($ name)
          {
             $ this-> name = $ name;
             $ this-> sex = 'F';
           }
      }
?>

Now try to instantiate one of two classes.

<?php
   $oBob = new Man ('Bobby');
   echo $oBob-> getName ();
?>

 

Of course, we get the following error because we have not redefined the abstract methods of the superclass.

Fatal error: Class Man contains two abstract methods and must be Declared Therefore abstract gold Implement the remaining methods (HumanBeing::toSport, 
HumanBeing::toEntertain themselves) in /Users/Tutorial/abstract.php on line 74

This indicates that we must explicitly redefine the abstract methods of the superclass or make our abstract male class. Since we want to instantiate the derived class, it remains that the first solution. Thus redefining these two abstract classes in each of the derived classes.

Redefinition of abstract methods in derived classes

<?php
   class Man extends HumanBeing
     {
           public function __construct ($name)
           {
                 $this-> name = $ name;
                 $this-> sex = 'M';
             }
           public function toSport ()
             {
                 echo $this-> name. ' made boxing ';
             }
             public function toEntertain ()
             {
                 echo 'Evening football and beer';
             }
     }
     class Female extends HumanBeing
     {
           public function__construct ($name)
             {
                 $this-> name = $name;
                 $this-> sex = 'F';
             }
           public function toSport()
           {
              echo $ this-> name. ' makes fitness';
             }
           public function toEntertain ()
           {
                 echo 'Shopping girls';
           }
     }
?>

 

Now instantiate each of the two classes.

Instances of classes Man and Woman

<? php
    $ oAlice = new Woman ('Alice');
    $ oAlice-> toSport ();
    echo '<br/>';
    $ oAlice-> toEntertain ();
    echo '<br/>';
    echo 'Sex', $ oAlice-> getSex ();
    echo '<br/>';
    $ oBob = new Man ('Bobby');
    $ oBob-> toSport ();
    echo '<br/>';
    $ oBob-> toEntertain ();
    echo '<br/>';
    echo 'Sex', $ oBob-> getSex ();

?>
The result is the one expected:
   Alice makes fitness
   Shopping girls
   Sex: F

   Bobby makes boxing
   Evening football and beer
   Gender: M

For instances of Women class, we find good value for F attribute $sex and redefined the abstract methods that correctly displays the fitness and shopping. As for instance the Man class, the result is as expected. The attribute $sex takes good value M and the two abstract methods show well the Boxing Sport and Football Evening entertainment.

Special cases of final classes and methods

Presentation of final classes and methods

So far we have presented the abstract classes and methods. PHP introduces an additional mechanism to ensure the programming of safety. This is the keyword “final” that may be applied either to a class or a method.

When a class is defined as “final”, it means that it can be derived by a subclass. This also implies that its attributes and methods may not be redefined. However, if we apply the keyword “final” a method of a class, then it is only this method can not be overridden in derived classes.

By prohibiting the derivation of a class or redefine (overload) methods of a class, this allows you to ensure that the developer does not directly bypass the logic you have implemented.

Declaration of final classes

Let our 3 previous classes. Now we decide that classes “Man” and “Woman” can not be derived. We therefore declare as final. This gives us:

Declaration of final classes

<? php
     final class Man extends HumanBeing
     {
        // Following the class code
     }

     final class Female extends HumanBeing
     {
         // Following the class code
     }
?>

Now trying to derive one of the two classes and instantiated. For this, we need only write a class “YoungBoy” which inherits the properties and methods of the class “Man”.

<? php
    class YoungBoy extends Man
    {
        / **
        * Built the object Youngboy
        *
        *param String $ name name of the young boy
        *return Void
        * /
       public function __construct ($ name)
       {
           parent :: __ construct ($ name);
       }
    }

?>

Obviously an error is generated because the Man class is no longer differentiable because of his statement “final”.

Fatal error: Class Youngboy May not inherit from final class (Men) in /UsersTutorial/abstract.php on line 153

Note: An abstract class may not be declared “final”. A syntax error will be generated. In addition, declare an abstract and final class is synonymous with a lack of logic since the purpose of an abstract class is to be derived by subclasses.

Final Declaration methods

Let us now study the case of final methods. Let the abstract class “HumanBeing” and declare methods “getName ()” and “getSex ()” final.

Final Declaration methods

<?php
   abstract class HumanBeing
   {
         public final function getName ()
           {
               return $this-> name;
           }
           public final function getSex ()
           {
               return $this-> sex;
           }
    }
?>

Now derived classes “Man” and “Woman” can not redefine these methods. Try to override one of these methods in the “Man” class.

Redefining abstract methods

<?php 
   final class Man extends HumanBeing
   {
     public function getSex ()
       {
           return 'Male';
       }
   }
?>

Here, the method “getSex ()” no longer returns the value of $ sex protected attribute, but attempts to return the string “male”. Not surprisingly, redefining the method generates a fatal error by the PHP interpreter.

Fatal error: Can not override final method humanbeing :: getSex () in /Users/Tutorial/abstract.php on line 115

PHP Magic Methods: __sleep () and __wakeup ()

By Dinesh Thakur

We studied in previous articles the magiques__clone () methods, __set (), __get () and __call (). PHP adds to recent two additional magic methods __sleep () and __wakeup () that allow overloading the native process of serialization and de-serialization of PHP data. That’s what we’ll explain in tutorial with some concrete examples and easy to understand.

What is data serialization?

To summarize very simply, action to serialize a variable is to convert it into a string for example, store it in a text file. Conversely, the action of deserializing a string is to apply the inverse process to recover the original variable. This process is not limited to PHP, you will find it in many languages ​​like Java, ActionScript, C, C # … to name a few.

The words serialization and de-serialization are probably the most common words, but you will hear / maybe read somewhere the words linearization / delinearization or even marshalling / unmarshalling. Serialize, linearized, marshaller (deserialize, respectively, and delinearize unmarshaller) define the concepts of serialization and de-serialization.

Syntactically speaking, data serialization is reflected by using the serialize () function, the inverse action results unserialize (). Let’s see some examples.

Serialization / deserialization of an integer variable

<? php
   $ iVar = 1;
   $ sSerialized = serialize ($ iVar);
   $ iUnserialized = unserialize ($ sSerialized);
   echo '<pre>';
   var_dump ($ sSerialized, $ iUnserialized);
   echo '</ pre>';
?>

The first var_dump () displays the following string to standard output:

string (4) “i: 1;”

And the second displays the following:

int (1)

You deduce course it is not interesting to serializer an integer since you can store it directly. However, this example is still useful to a simple principle illustration: a variable serialization preserves type it. So we will have a good return integer, just as we retain an Array or an object.

Serialization / de-serialization of an array (Array)

Consider now a table as an example. Serialization and deserialization here become much more interesting since they will allow us to transform (and recover) an entire table.

<? php
    $ atable = array ('Moga', 'Agra', 'Abohar', 'Punjab', 'Jaipur');
    $ sSerialized = serialize ($ atable);
    $ aUnserialized = unserialize ($ sSerialized);
    echo '<pre>';
    var_dump ($ sSerialized, $ aUnserialized);
    echo '</ pre>';
?>
The first var_dump displayed:
string (87) "a: 5: {i: 0; s: 4:" Moga"; i: 1; s: 4:"Agra"; i: 2; s: 6:"Abohar"; i: 3; s: 6: "Punjab"; i: 4; s: 6: "Jaipur";} "

Serialization of the table eventually built a character string with a length of 87 characters. Let us quickly the structure of this chain.

• The first character of the string indicates the type of the serialized variable. Here, the letter “a” thus indicates that we have to serialize an array (array).
• Then we read the number 5 indicates the number of elements in the array. In between parentheses, we find all the elements of the array.
• The first letter of an element group indicates the type of the index in the table followed by its value. Here we have an array indexed numerically serialized, so
each index is an integer (“i”) whose value is between 0 and 4 inclusive. If we had used an associative array, the indexes would have become strings (“s”).
• We then read each stored value, type (“s”), its length (4) and the value stored in the table (“City”).

With all this information, the unserialize () function is able to completely rebuild the array by analyzing the formatted string.

This is why the second var_dump () displays the result in which we find all the information in the serialized string:

array(5) {
[0]=>
string(4) "Moga"
[1]=>
string(4) "Agra"
[2]=>
string(6) "Abohar"
[3]=>
string(6) "Punjab"
[4]=>
string(6) "Jaipur"
}

Now try to serialize / deserialize an object.

Serialization and de-serialization of an object

Now comes the most interesting example, serialization of an object. Let’s take a basic class with different properties. We deliberately use public property, private and protected in order to visualize how does serialization of an object with different properties.

<? php
    class Sleeper {
       protected $ _age;
       protected $ _HeadCap;
       private $ _FavoriteColor;
       public $ _tastes ;
       public function __construct () {
            $ this -> _age = 19;
            $ this -> _HeadCap = true;
            $ this -> _FavoriteColor = 'red';
            $ this -> _tastes = array ('Music', 'cinema', 'curling');
          }
   }
?>

We then get the following results respectively:

string (181) "O: 7:" Sleeper ": 4: {s: 7:" * _age "; i: 19; s: 14:" * _HeadCap"; b: 1; s: 25:"FavoriteColor";s:6:"_tastes";a:3: 
{i:0;s:7:"Music";i:1;s:7:"cinema";i:2;s:7:"curling";}}
object (Sleeper) # 2 (4) {
["_age: protected"] =>
int (19)
["_HeadCap: protected"] =>
bool (true)
["_FavoriteColor: private"] =>
string (5) "Red"
["_tastes"] =>
array (3) {
[0] =>
string (7) "music"
[1] =>
string (7) "cinema"
[2] =>
string (7) "curling"
}
}

You already know that the type variable was preserved, it is the same for visiblity (private, protected and public), it does not change in any way the class structure. We Instance Storage talking, we must be careful that your class is declared before serialization, otherwise you’ll get an error:

Fatal error: Class ‘Sleeper’ not found in /home/path/to/your/script.php on line xx

You will notice the “o” as the first character of the serialized chain to say we have much to serialize an object.

Magic Methods __sleep () and __wakeup ()

Now that we have understood the principle of serialization, we can enter the heart of the matter and talk about the magic methods __sleep () and __wakeup ().

These methods will be respectively called by the script when using serialize () and unserialize (). Here is a demonstration, we will add __sleep () and _wakeup () to our Sleeper.

The magic __sleep () method, however, must take an action that serialization is going well. It is here that one can see the first benefit of the serialization of a class instance: you select which properties of your body you want to store. To do this, the __sleep () method must return an array containing the names of the properties to keep:

<? php
     class Sleeper {
       / **
          * Magic Method __sleep () Called during a serialize ()
          *
          *return Array the list of parameters to be held
          * /
          public function __sleep() {
             echo 'Bon ben I'm going to sleep.';
             return array ('_age', '_HeadCap', '_FavoriteColor');
       }

        / **
        * Magic Method __wakeup () Called during a unserialize ()
        *
        *return Void
        * /
         public function __wakeup() {
            echo 'ben good I'm going to get a coffee.';
         }
     }
?>

Here one chooses to keep that age Sleeper, her favorite color and whether or not he has his cap on his head.

By executing the above code again, you’ll see both echo appear after (“Bon ben I’ll sleep.” Then “ben good I’m going to get a coffee.”) Confirming that the methods __sleep () and __wakeup () have been successively called.

The result of the serialization is:

string (108) “O:7:”Dormeur”:3:{ s: 7 : “*_age” ;i :19 ;s: 14: “* _HeadCap “;b:1;s:25 : ” FavoriteColor “;s:5:”tastes”;}”

We see that we do not keep the likes of Sleeper. And here is what you show the second var_dump:

object (Sleeper) # 2 (4) {
["_age: protected"] =>
int (19)
["_HeadCap: protected"] =>
bool (true)
["_FavoriteColor: private"] =>
string (5) "Red"
["_tastes"] =>
NULL
}

Note that only the properties specified in the __sleep () have been stored, the “_tastes” property, meanwhile, is equal to NULL, its contents has not been preserved. Of course, the interest does not stop there, you will be able to perform the actions you want from these methods: synchronization with a database, close a connection to a database when serializing, reopen at deserialization, etc.

For lovers of DIY, it is also possible to implement the concept of “cast” of object, PHP totally absent at present.

PHP Magic Methods: __clone ()

By Dinesh Thakur

PHP since version 5 implements magic methods you can implement in your classes, which will be automatically called by your script. Magic method __clone () is one of these methods. The following tutorial introduces the operation of the magic method __clone () based on simple and concrete examples.

Reminders on object-oriented programming

To understand the principle of this method and its scope, this is how running (in outline), object-oriented programming.

Take an object “Point” that has protected properties “_x” and “_y”, which here correspond to the coordinates of the point. It adds a setcoords () method that lets you specify these values:

<? php
    class Point
      {
           / **
           * X-coordinate of the point
           *
           *var Integer
           * /
                 protected $ _x = 0;

          / **
          * Intercept point
          *
          *var Integer
          * /
             protected $ _y = 0;
         / **
            * Fixed the point coordinates
            *
            *param Integer $ x coordinate of the point
            *param Integer $ y coordinate of the point
            *return Void
            * /
               public function setcoords ($ x, $ y) {
               $ this -> _ x = (int) $ x;
               $ this -> _ y = (int) $ y;
               }
         }

When you want to use this object, we call its constructor (here it is declared implicitly) and we store it in a variable the result of this appeal. This is what we call the class instantiation phase. The variable is an instance of this object.

<? php
   // Instantiating the object Point
   // And storage in the instance variable "ODOT"
   $ ODOT = new Point ();
?>

PHP 5 and the passing objects by reference

That’s the outline. Now speak (sorry) PHP 4. With version 4 of PHP, objects were passed by “value” (or by “copy”), which means that when variable “$ a” containing the instance of a Point object was copied into a variable $ b, then the two variables $ a and $ b each contained an instance (object) unique. PHP 5, objects are moved and copied by reference. This implies that if a copy of a $ a to $ b, it will contain the reference refers to the object in $ a. Let’s take a simple example to illustrate the theory in practice.

<? php
    $ ODOT = new Point;
    $ oDot-> setcoords (10,10);
        var_dump ($ ODOT);
    $oNewDot = $ ODOT;
    $ oNewDot-> setcoords (20,20);
        var_dump ($ ODOT);
?>

Here we instantiate our Point object and we store the instance in $ ODOT. Then we copy the contents of the variable $ ODOT in $ oNewDot. We modify the instance properties of the object stored in $ oNewDot Point and finally we display the information of the instance of our object.

The first var_dump () appears:
object (Point) # 1 (2) {["_x: protected"] => int (10) ["_y: protected"] => int (10)}
The second returns:
object (Point) # 1 (2) {["_x: protected"] => int (20) ["_y: protected"] => int (20)}

We note here that we are dealing with a single instance although we have tried to copy the variable.

But then, in some cases it may be useful to duplicate a class instance, which is not possible through the ‘PHP 4 “method, as we have just seen. The solution is to use the keyword “clone”.

The clone keyword

Operation is simple, instead of:
<? php
    $ oNewDot = $ ODOT;
?>
We will do :
<? php
    $ oNewDot = clone $ ODOT;
?>
By modifying and running the previous code:
<? php
     $ ODOT = new Point;
     $ oDot-> setcoords (10,10);
     var_dump ($ ODOT);
     $ oNewDot = clone $ ODOT;
     $ oNewDot-> setcoords (20,20);
     var_dump ($ oNewDot);
     var_dump ($ ODOT);
?>
Here the display of the first var_dump ():
object (Point) # 1 (2) {["_x: protected"] => int (10) ["_y: protected"] => int (10)}
And here is the display of the second, we can see that the _x and _y properties are modified:
object (Point) # 1 (2) {["_x: protected"] => int (20) ["_y: protected"] => int (20)}
Here the display of the third and final var_dump:
object (Point) # 1 (2) {["_x: protected"] => int (10) ["_y: protected"] => int (10)}

You can see for yourself, we have indeed two separate instances of the Point class.

Implementation of the magic method __clone

Now that we have understood the concept of cloning objects in PHP, we will finally be able to talk about the magic method “__clone ()”. The principle of this method is simple, it will be automatically called when the clone keyword will be used on an object. Let’s take an example.

Here is a class Sheep (sheep, for anglophobes):

<? php
     class Sheep
      {
          / **
          * Sheep Name
          *
          *var String
          * /
          protected $ _name;
           / **
             * Building & the Sheep class
             *
             *param String $ name name of sheep
             * /
               public function __construct ($ name) {
                  $ this -> _ name = (string) $ name;
                }

             / **
             * Magic clone Method
             *
             *return Void
             * /
              public function __clone() {
                    $ this -> _ name = 'Copy' $ this -> _ name.
               }
       }
Instantiate our class, and our duplicat object:
<? php
      $ oSheep = new Sheep (Dolly);
      $ oNewSheep = clone $ oSheep;
       var_dump ($ oSheep);
      var_dump ($ oNewSheep);
?>
Here is the first displayed by var_dump ():
object (Sheep) # 3 (1) {["_name: protected"] => string (5) "Dolly"}
And here is the second displayed by var_dump ():
object (Sheep) # 4 (1) {["_name: protected"] => string (14) "Copy Dolly"}

By duplicating the instance ‘$ oSheep, my method was __clone automatically called and changed the name by adding “Copy of” prefix in the name of the sheep.
You will notice that we have used the reference to the object itself $ this to change the information of the new instance.

Implementation in the case of a Singleton

The Singleton design pattern is to ensure that only have one instance of an object in a script. For more information, please visit this post.

But even if your constructor is declared protected or private access, it will still be possible to clone your object. You will lose the principle of singleton. To overcome this problem, just throw an exception when the developer using the Singleton decides to clone:

<? php
     class Singleton {
     / **
      * Instance of the Singleton class
      *
      *var Singleton
      * /
       protected static $ _instance = null;

      / **
      * Class Constructor
      *
      * @ Access protected
      * /
         protected function __construct () {}

     / **
     * GetInstance (): recovery of the class instance
     *
     *return Singleton
     * /
          public static function getInstance () {
             if (null === self :: $ _ instance) self :: $ _ instance = new Singleton ();
             return self :: $ _ instance;
          }

        / **
        * Magic clone Method
        *
        *return Void
        * /
        public function __clone () {
           throw new Exception ('Are you Trying to clone me I \?' Singleton my dude! ');
        }
     }

    try {
       $ oSingleton = Singleton :: getInstance ();
        clone $ oSingleton ;
      } catch (Exception $ e) {
        echo 'Oops, except:', $ e-> getMessage ();
   }
?>

And this is what will appear in the execution of the code:

Oops, exception: Are you Trying to clone me? I’m a Singleton dude!

The exception has been raised and has prevented the attempted cloning of the object. The singleton and retain its uniqueness in the developed application.

PHP Magic Methods: call ()

By Dinesh Thakur

PHP has made a big step forward in object-oriented programming with version 5. Since this version, it allows to implement methods in predefined behavior by PHP. These methods are called “magic methods” __call () is one of them.

Call a method that does not exist

Take the example of a class that models a Penguin, which instantiates then called his method “fly”.

<?php
   class Penguin
    { }
    $web = new Penguin ();
    $web -> fly ('Africa');
?>

This piece of code will throw you an error. You do not know but maybe penguins can not fly:

Fatal error: Call to undefined method web::fly () in /path/to/Code-php/magic_methods.php on line 4. 

This small reminder morphological allows you to see especially the following: you can not call a method that does not exist. PHP However, thanks to the magic method __call () allows you to violate a basic law of nature, namely to fly a penguin or generally call a method that has not been declared in your class.

Implement the __call () method

The __call () method takes two parameters. The first contains the name of the method that you tried to call, the second contains the arguments you passed him. The following listing shows the overall structure of this method.

<? php
    class MyObject
    {
         / **
         * Method magic __call ()
         *
         *param String $ method name of the method to call
         *param Array $ arguments Table settings
         *return Void
         * /
         public function __call ($method, $arguments)
          {
               // Code to execute custom
          }
    }

?>
Now take the example of Penguin.
<?php
     class Penguin
     {
         / **
         * Method magic __call ()
         *
         *param String $method name of the method to call
         *param Array $arguments Table settings
         *return Void
         * Private access
         * /
         private function __call ($method, $arguments)
         {
         echo 'You called the method', $ method, 'with arguments' implode (',', $ arguments);
         }
    }

      $web = new Penguin ();
      $web -> fly ('Africa');
?>

A few notes:

If you have made your __call () method public, you’ll also be able to call directly by doing: $ web -> __ call (‘fly’, ‘Africa’); but there will be a small difference.
By calling the fly () method, the variable $ arguments is an array storing different arguments. Conversely, if you go through the __call () method, the second argument is the type you want.

Case in point: creating a search engine

We will try to recreate a search engine. Notice that we use the PROOF class presented in a previous tutorial, which provides access to the database via the native PDO extension.

<? php
    class SearchEngine
    {
        / **
        * Performs a search in the database
        * Based on criteria supplied argument
        *
        *param Array $ terms Table search criteria
        *return Array $ return results Table
        *see SPDO
        * /
        public function search ($terms = array ())
        {
           $query = "SELECT id FROM table ';

           if (sizeof ($conditions)> 0) {
              $query .= 'WHERE' .implode ('AND', $conditions);
               }

             // Run the SQL statement with PDO Class
             $result = SPDO :: getInstance () -> query ($query);
             $return = $result-> fetchAll (PDO :: FETCH_ASSOC);
             return $return;
        }
   }
?>

As you can see, this search engine has a search () method that takes an array argument to apply different conditions to the application performing the search. These conditions are of the form: fieldname = “value”.

You will agree like me (I hope!) That this syntax is more practical, I do not see myself use the query like this:

<?php
     $mySearchEngine = new SearchEngine();
     $mySearchEngine -> search (array (
     'field1' => 'Code-php'
     'field2' => 'Study'
));

It would be really nice to make $ mySearchEngine-> searchByName (‘Study’); for example, or $ mySearchEngine-> searchByNameAndDate (‘Study’, ’11/05/1988′); not true ?

And this is where we will be able to implement the __call () method.
<?php
    class SearchEngine
    {
        / **
        * Performs a search in the database
        * Based on criteria supplied argument
        *
        *param Array $ terms Table search criteria
        *return Array $ return results Table
        *see SPDO
        * /
        public function search ($ terms = array ())
          {
             $ query = "SELECT id FROM table ';
               if (sizeof ($ conditions)> 0) {
                  $ query = 'WHERE' implode ('AND', $ conditions);
          }
         // Run the SQL statement with PDO Class
         $ result = SPDO :: getInstance () -> query ($ query);
         $ return = $ result-> fetchAll (PDO :: FETCH_ASSOC);
            return $ return;
     }

      / **
      * Magic method __call () allows to call a virtual method
      * kind of SearchByName (), searchByAge () or searchByNameAndAge () ...
      *
      *param String $ method name of the virtual method called
      *param Array $ args Table search criteria
      *return Array | null $ return results table or NULL
      *see SearchEngine :: search ()
      * /
      public function __call ($ method, $ args)
       {
           if (preg_match ('#^searchBy#i', $method))
              {
                  $ searchConditions = str_replace ('searchBy', '', $method);
                  $ searchCriterias = explode ('and' $ searchConditions);
                  $ terms = array ();
                  $ nbCriterias = sizeof ($ searchCriterias);
                  for ($ i = 0; $ i <$nbCriterias; $ i ++)
                       {
                            $ Conditions [] = strtolower ($ searchCriterias [$ i]) ="'$ args [$ i]'" ';
                       }
                       return $ this-> search ($ conditions);
             }
                       return null;
      }
}
?>

This is a fairly substantial piece of code to digest, so let’s dissect it step by step:

• To begin, it is verified that the method we tried to call is a method whose name begins with “searchBy”. This step is not necessary, we will call it a care: we make so intuitive code.
• Recovering what is after searchBy in this example: name
• In case we would have several conditions, such searchByNameAndDate are recovered each field test, NameAndDate here.
•For each parameter, the condition is created, in the case of: $ Google-> searchByNameAndDate (‘Study”,”11/05/1988″); we obtain a table with name = “Study” and date = “11/05/1988” that we will be able to pass a parameter to the search () method, as we spoke above.

Disadvantages of the use of the magic __call () method

Just as magic methods __get () and __set (), the magic __call () method has two significant drawbacks when developing professional environnemet. Indeed, using __call () initially prevents the automatic generation of code documentation using the APIs (PHP Documentor for example) using the introspection objects (Reflection). Moreover, it also prevents IDE like Eclipse to introspect the code of the class and thus offer auto-completion of code. A so use sparingly!

PHP Magic Methods: set () and get ()

By Dinesh Thakur

PHP has made a big step forward in object-oriented programming with version 5. Since this version, it allows to implement methods in predefined behavior by PHP. These methods are called “magic methods”, the __set () and __get () are included.

Reminders visibility of the properties and methods

Public access properties

Object-oriented programming lets you specify the visibility of a class methods and properties. In the case of properties, it is very advisable to give them a public visibility because that way it becomes possible to change them without that no monitoring is carried out on values.

<?php

class Kid {
     public $age;
     public function showAge() {
         return 'His age is :'. $this-> age;
      }
  }

$billy = new Kid ();
$billy-> age = 'red';
echo $billy-> showAge ();
?>

This portion of code so you will return “His age is red” which, you will agree, means absolutely nothing.

Private and protected access for properties

So it is better to give them a limited visibility: private or protected.

<?php
      class Kid {
      private $age;
   }
   $billy = new Kid();
   $billy-> age = "even red than before";
?>
This piece of code will return a fatal error:
Fatal error: Can not access private property Kid::$age in /path/to/Code-php/magicmethods.php on line 6.

One solution would be to create a public accessor setAge () that would specify the age by ensuring that you have passed it a number, and getAge () in order to display it.

This method is entirely feasible, provided that not having a large number of properties, the number of accessor becoming too important: you can implicitly use the magic methods __set () and __get ().

In addition, the following syntax is perfectly valid PHP:

<?php
      class Kid {
     }
    $billy = new Kid();
    $billy-> age =14;
    $billy-> hair = 'black';
    echo 'Billy is aged ', $billy-> age, ' years and her hair color ', $billy-> hair;
?>

And yes, you can learn and then retrieve properties in a php object without these have been declared in your class, not dirtier? It is therefore possible to “butcher” this little blunder, still implicitly using magic methods __set () and __get () to be called respectively when the property information and when trying to read the value.

Magic method __set ()

Magic method __set () to do what we call the overload of properties of a class. Indeed, when trying to fix the value of a nonexistent property of the class, PHP automatically calls this method implicitly. Here is its general structure.

<?php
    class MyObject
     {
         / **
         * Magic Method __set ()
         *
         *param String $property Property name
         *param Mixed $value The value to assign to the property
         *return Void
         * /
         public function __set ($property, $value)
         {
            // Code to execute custom
         }
     }

?>

By overriding this method explicitly in the body of the class, this allows the developer to carry out access controls and ensure that only a few properties can be updated. This is what we introduce in our case of further application in this course.

Magic method __get ()

The magic __get () method, in turn, read the value of a nonexistent property of the class. Just like magic method __set (), the magic __get () method must be redefined in the class to run custom code when PHP implicitly calls this method. Again, this allows for an access control on the properties that are trying to read the values. The prototype of this method is presented below and will be further developed in the case of practical application of this tutorial.

<? php
    class MyObject
    {
        / **
        * Method magic __get ()
        *
        *param String $property name of the property to achieve
        *return Mixed | null
        * /
        public function __get ($property)
        {
             // Code to execute custom
        }
}

?>

Practical application case

We will resume our previous example of our Kid class and we will integrate him two magic methods _get () and __set (). The objective is thus to achieve access control when trying to set or get the value of private property $age.

<?php
     class Kid {
         private $age;
         public function __get ($property) {
             if ('age' === $property) {
                 return $this->age;
              } else {
                    throw new Exception ('Invalid property!');
                 }
}
      public function __set ($property, $value) {
          if ('age' === $property && ctype_digit($value)) {
             $this-> age = (int) $value;
          } else {
             throw new Exception ('Invalid property or value!');
         }
       }
   }
?>

In this way, it is ensured of being unable to specify the age of Billy, and nothing more. You will notice that one makes “hard” tests i.e. that we do not simply checks that $ age property exists, only that the user has attempted to specify “$age”. In addition, it controls the type of value using the ctype_digit () function that ensures that the format of the value corresponds to an integer.

It is quite possible to retrieve the properties of an object, but to do this properly, it is best to use reflection classes.

PHP visibility of the Methods and Properties

By Dinesh Thakur

The visibility of the properties and methods of an object is one of the basic features of object-oriented programming. This tutorial aims to introduce different levels of visibility offered by the object model PHP 5. We will review them one by one through practical examples and we will bring some good practices to adopt when used.

What is the visibility of the properties and methods of an object?

The visibility defines how an attribute or method of an object will be accessible in the program. Such as Java, C ++, or ActionScript 3, PHP introduced 3 different levels of visibility apply to properties or methods of the object.

These visibilities public, private, or protected, which are respectively defined in the class using the keywords public, private, and protected.

The following example illustrates the syntax of data reporting members (attributes) and methods with different visibilities. We will explain just after each particularity visibility levels.

Use keywords public, private, and protected

<?php
     class Vehicle
     {
          // Attributes
               public $mark;
               private $FuelVolume ;
               protected $isRepare;

          // Methods
               public function construct ()
                 {
                     $this -> FuelVolume = 40;
                     $this -> isRepare = false;
                 }

         // Start the car if the tank
        // Is not empty
             public function Start ()
               {
                   if ($this -> FuelVolumeControler ())
                       {
                           echo 'The vehicle starts';
                                     return true;
                       }

                           echo 'The tank is empty ...';
                                     return false;
               }

                  // Check if there's fuel in the tank
                       private function FuelVolumeControler ()
                           {
                                return ($this -> FuelVolume> 0); // Returns true or false
                           }

                // Set the vehicle maintenance
                       protected function repair ()
                           {
                                 $this -> isRepare = true;
                                     echo 'The vehicle is in repair';
                           }
     }

We note here that we were already using attributes and public methods in the examples of the first tutorial on object oriented programming. Now present each of visibility levels.

Public access

This is the PHP default access if one says no visibility. All attributes and methods that are declared without any of these three keywords will automatically be considered by the public as interpreter.

The public keyword indicates that the properties and methods of an object will be accessible from anywhere in the main program or in the inherited or derived subclasses parent classes. Remember these words in a corner of your memory as we present the concepts of inheritance to the next tutorial.

Concretely, this is what we did in the previous tutorial. What gives with our example:

Using public visibility

<?php
    // Instantiation of the object: implicit call to the construct () method
     $MyVehicle = new Vehicle();

    // Update the vehicle brand
     $MyVehicle-> mark = 'Honda';

    // Display the vehicle brand
         echo $MyVehicle -> mark;
?>

In this example, we see that we can directly read and change the value of the brand in the public attribute directly calling this way: $ MyVehicle-> mark (without dollars).

We will see just after the same usage will be impossible with private and protected attributes.

Note: when you instantiate the class to create a new object, the keyword “new” charge to call the class constructor method. The latter must necessarily be declared public because it is called from outside the class.

The private access

The private keyword is used to declare attributes and methods that will be visible and accessible directly from within that same class. That is, it becomes impossible to read or write the value of an attribute directly by private $MyVehicle -> FuelVolume. Also to use FuelVolumeControler () method via $MyVehicle -> FuelVolumeControler (). You will notice testing, a fatal error is generated at runtime.

The value of the private attribute $ FuelVolume is initialized in the class constructor. That is, when constructing the object.

For example, when our vehicle is finally assembled and ready for use, it will be sold to the customer with the fuel tank filled or 40L.

A method is declared private when it is not intended to be used outside of the classroom. Private methods are used in particular to validate data in an object or to perform various internal treatments. This is for example the task that fills the private method FuelVolumeControler () when called by the public method Start (). This private method verifies that there’s much of the fuel in the vehicle by testing the value of the private attribute $ FuelVolume. If this is the case, the method returns true and so the car starts. Otherwise, the return value is FALSE and the car will not start.

Call the START () method on the subject $MyVehicle
<?php

     // Displays: "The vehicle starts"
      $MyVehicle-> Start ();

?>

Access protected

The protected access (protected) is an intermediary between public access and private access. It allows the use of common attributes and methods in a parent class and derived classes.

However, we have to anticipate it to understand how the protected access. For this, we will add a Car class that will inherit our current class Vehicle. As a car is a kind of vehicle it is possible we derive the class Vehicle with a Car class.

The Vehicle class will contain the attributes and methods common to any type of vehicle while the car class will encapsulate the properties and methods specific to cars. For example, the brand or boolean isRepare may well be shared attributes. Against by the volume of fuel in the tank is not common to all vehicles.

Indeed, a bike, a scooter or even a rowing can be considered non-motorized vehicles. They therefore have no tank and do not work with fuel.

Using protected access
<?php

      class Vehicle
         {
                // Attributes
                     protected $Trademark;
                     protected $istRepare;

                // Methods
                     public function construct ($name)
                        {
                            $this -> brand = $trademark;
                            $this -> isRepare = false;
                        }

                // Set the vehicle maintenance
                     public function repair ()
                        {
                            $this -> isRepare = true;
                            echo 'The vehicle is in repair';
                        }
          }
     Car class extends Vehicle
         {
               // Attributes
                    private $FuelVolume ;

              // Constructor
                   public function construct ($name)
                      {
                          // Call the constructor of the parent class
                               parent ::construct ($name);
                           $this -> FuelVolume = 40;
                      }

            // Start the car if the tank
            // Is not empty
                 public function Start ()
                     {
                          if ($this -> FuelVolumeControler ())
                              {
                                  echo 'The vehicle starts';
                                  return true;
                              }

                                  echo 'The tank is empty ...';
                                  return false;
                      }

                   // Check that there's fuel in the tank
                        private function FuelVolumeControler ()
                            {
                                 return ($this -> FuelVolume> 0);
                            }
            }

We just declare protected two attributes in the parent class Vehicle and we descended the FuelVolume attribute in the car class. Similarly we back down methods Start() and FuelVolumeControler () in the car class. Thus, we can now instantiate a new object of type Car and enjoy the attributes and methods of the Vehicle class and more. Finally, note that the repair () method is passed from the public protected mode in order to call from outside the class. Which give :

Use of protected attributes and methods
<?php

      $MyVehicle = new Car ('Honda');
      $MyVehicle-> Start ();
      $MyVehicle-> repair ();

?>

Updating a private or protected attribute: role of mutator

We mentioned earlier that it was impossible to access the value of an attribute or private protected using the following syntax: $object-> attribute. A fatal error is generated. How to update the value of the attribute in this case? This is where the mutator.

The mutator is neither more nor months that a public method to which the new value to assign to the attribute we pass as a parameter. By convention, these methods are called with the set prefix. For example: setBrand (), setFuelVolume () … This is why you will hear most often mention setter that mutator.

Add a mutator to our Car class that changes the value of the fuel volume. This gives:

Added mutator (setter) setFuelVolume to Class Car
<?php

     Car class extends Vehicle
         {

                 // ...

                 public function setFuelVolume ($dVolume)
                     {
                        $this -> FuelVolume = $dVolume;
                     }
         }

To meet the IT development conventions we use in our example writing using the set prefix. But this name is completely arbitrary and our method might well have to call doFull() or FillTank (). It takes that to you to give meaningful names to your methods.

As for the use of this method, it is simply a traditional method call.

Update the value of the private attribute $ FuelVolume
<?php

     // I fill my 50 L fuel tank
      $MyVehicle-> setFuelVolume (50);
?>

Get the value of a private or protected attribute: role of accessor

We have just studied how to update (write) the value of an attribute private or protected. It only remains for us that to address the case of reading that value. How this value is restored in a program knowing that direct access to the attribute is forbidden? In the same way as the mutator, we should declare a method that will be responsible to return the value of the attribute. It is neither more nor less than a function with a return statement.

We call such a method accessor or more commonly a getter. Indeed, by convention, these methods are prefixed the word get. Just as the mutators, it is possible to apply any name a accessor.

Returning to our previous example. The getter below explains the principle of returning the value of a private attribute. We refer here the value of the variable $ FuelVolume.

Declaring an accessor for private attribute $ FuelVolume Class Car
<?php

     Car class extends Vehicle
       {
           // ...

           public function getFuelVolume ()
               {
                   return $this -> FuelVolume;
               }
        }

Here’s an example of using the method getFuelVolume :

Using the get accessor FuelVolume() on the object $MyVehicle
<? php

     echo sprintf ("% u It remains The essence of" $MyVehicle-> getFuelVolume ());

?>

That’s all there is to know about the visibility of essential methods and attributes as well as the access to the values ​​of the latter. Before concluding this tutorial, do a short reminder of good object-oriented development practices history that you can immediately start with a solid foundation.

Object Oriented Programming in PHP

By Dinesh Thakur

Object-oriented programming (OOP) was integrated into the PHP version 3 in 1998, including basic class and object support. In 2000, PHP4 added some functionality, but suffered from its non-intuitive handling of references with objects handled like value types. [Read more…] about Object Oriented Programming in PHP

PHP Imagefilter (): special effects

By Dinesh Thakur

PHP can manipulate the images for many years and for applying special effects to it, we were often forced to write many lines of code. Since PHP version 5, a new feature has appeared: “imagefilter” to achieve effects with the same quality as designs software.
This function allows you to customize the look of your site and also to achieve a different picture gallery of others.
So we’ll see:
• The basics
• The ImageFilter () function
• How to play with some filters?

The basics

Before using these new effects, it is important to have the GD library enabled. If it is not active, know that it is in the php.ini file. To verify that the GD library works correctly, we will attempt to load an image and display it:

Load and display a JPG image
<?php
Header("Content-type: image/jpeg");
     $image =imagecreatefromjpeg ('guest.jpg'); // Load the image JPG
         imagejpeg ($image); // Displays the image
         imagedestroy ($image); // Frees the image
?>

Here is the result:

                                                        

The function ImageFilter

This function allows you to apply a filter on an image. It looks like this:

Imagefilter prototype of the function ()
imagefilter (resource $image, int $filtertype [, int $arg1 [, int $arg2 [, int $arg3]]])

Imagefilter () is divided into three criteria:

• Image: Image name
• filtertype: the type of filter of choice
• arg: the criteria, if necessary, in relation to the type of filter selected. The shade allows slice of -255 to 255

To illustrate our different examples, we will leave on the landscape we posted above.

The filter IMG_FILTER_BRIGHTNESS

This filter allows you to change the brightness of the image. We will only use the argument 1 (arg1). The possible value will be between -255 and 255 that represents:

• 255: Lighten the image with up to white (gloss effect)
• 0: Default. color unchanged
• -255: Darken the image up to the black (dark effect)

Example filter usage IMG_FILTER_BRIGHTNESS
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $value = 0;
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_BRIGHTNESS, $value);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_COLORIZE

This filter allows you to change the color trends, ie subtract one color over another. We will use the three arguments, which represent the shades of Red, Green, Blue. Each of the values of its shades they are finding a range of -255 to 255.

Example filter usage IMG_FILTER_COLORIZE
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $r = 100;
     $v = 0;
     $b = -50;
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_COLORIZE, $r, $v, $b);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_CONTRAST

This filter changes the contrast of the image. To determine this contrast, we use the argument 1 (arg1). Its value is in the range -255 to 255 where:

• 255: Lighten the image with up to white (gloss effect)
• 0: Default. color unchanged
• -255: Darken the image up to the black (dark effect)

Example filter usage IMG_FILTER_CONTRAST
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $value = -50;
     $image =imagecreatefromjpeg ($filename);
        imagefilter ($image, IMG_FILTER_CONTRAST, $value);
        imagejpeg ($image);
        imagedestroy ($image);
?>

The filter IMG_FILTER_EDGEDETECT

This filter uses edge detection to highlight in the image. No argument is used as this filter is applied to the entire image.

Example filter usage IMG_FILTER_EDGEDETECT
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_EDGEDETECT);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_EMBOSS

This filter can burn the image in relief. No argument is used as the filter is applied on the entire imag.

Example filter usage IMG_FILTER_EMBOSS
<?php
Header("Content-type: image/jpeg");
      $filename = 'guest.jpg';
      $image =imagecreatefromjpeg ($filename); 
         imagefilter ($image, IMG_FILTER_EMBOSS);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_GAUSSIAN_BLUR

This filter allows you to blur the image using the Gaussian method. No argument is used as this filter is applied to the entire image. It may be associated with IMG_FILTER_SELECTIVE_BLUR filter.

Example filter usage IMG_FILTER_GAUSSIAN_BLUR
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_GAUSSIAN_BLUR);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_SELECTIVE_BLUR

This filter can blur an image. No argument is used as this filter is applied to the entire image. It may be associated with IMG_FILTER_GAUSSIAN_BLUR filter .

Example filter usage IMG_FILTER_SELECTIVE_BLUR
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_SELECTIVE_BLUR);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_SMOOTH

This filter smoothes the image. We will use the argument 1 (arg1) to determine the degree of smoothing. The possible value will be between -255 and 255 that represents:

• 255: Lighten the image with up to white (gloss effect)
• 0: Default. color unchanged
• -255: Darken the image up to the black (dark effect)

Example filter usage IMG_FILTER_SMOOTH
<?php
Header("Content-type: image/jpeg");
      $filename = 'guest.jpg';
      $value = 50;
      $image =imagecreatefromjpeg ($filename);
          imagefilter ($image, IMG_FILTER_SMOOTH, 10);
          imagejpeg ($image);
          imagedestroy ($image);
?>

The filter IMG_FILTER_GRAYSCALE

This filter converts the image to black and white, that is, that we find the same opportunities as the IMG_FILTER_COLORIZE filter, except that here, we can not
choose the color.

Example filter usage IMG_FILTER_GRAYSCALE
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_GRAYSCALE);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_NEGATE

This filter allows to reverse all the colors of the image to make it negative.

Example filter usage IMG_FILTER_NEGATE
<? php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_NEGATE);
         imagejpeg ($image);
         imagedestroy ($image);
?>

The filter IMG_FILTER_MEAN_REMOVAL

This filter lets you apply a noise effect to the image.

Example filter usage IMG_FILTER_MEAN_REMOVAL
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_MEAN_REMOVAL);
         imagejpeg ($image);
         imagedestroy ($image);
?>

Now that we have seen all the possible filters for this function, we can apply multiple filters to a single image.

Let’s play with some types of filters

We will, for each presented effect from a different original image. The first effect consist in the separation of RGB colors of the image. The second script we discover flattening our image. Our third test will aim to apply a blur, and then we will close this tutorial by creating a monochrome effect. Let’s study the first effect:

Effect 1: Separating colors

To achieve this effect very common in software designs, we will apply two operations to the image. First, convert the black and white image with the IMG_FILTER_GRAYSCALE filter and recoloriser hue of choice with IMG_FILTER_COLORIZE filter.

RGB color separation of an image script
<?php
Header("Content-type: image/jpeg");
    // Red
    $r = 255; $v = 0; $b = 0;

   // Green
    $r = 0; $v = 255; $b = 0;

   // Blue
    $r = 0; $v = 0; $b = 255;


    $filename = 'guest.jpg';
    $image =imagecreatefromjpeg ($filename);
       imagefilter ($image, IMG_FILTER_GRAYSCALE);
       imagefilter ($image, IMG_FILTER_COLORIZE, $r, $v, $b);
       imagejpeg ($image);
       imagedestroy ($image);
?>

As you can see, you need to run the script three recovery commantant whenever two of the three lines of code number 4, 7 and 10.

Effect 2 Effect Flatten

To achieve this flattening effect that can approach an engraving effect, we must break the algorithm into two elementary operations.

• Detecting differences in the image with the filter IMG_FILTER_EDGEDETECT
• Transforming the relief image with the filter IMG_FILTER_EMBOSS

Flattening script example of an image
<?php
Header("Content-type: image/jpeg");
    $filename = 'afup.jpg';
    $image =imagecreatefromjpeg ($filename);
        imagefilter ($image, IMG_FILTER_EDGEDETECT);
        imagefilter ($image, IMG_FILTER_EMBOSS);
        imagejpeg ($image);
        imagedestroy ($image);
?>

Effect 3: Soft Snap

This effect shows how to create a blur effect. We will use two filters to achieve our goals:

• Blur the image with the filter IMG_FILTER_GAUSSIAN_BLUR
• Scrambling a little with the filter IMG_FILTER_SELECTIVE_BLUR

Script embodiment of a blur on an image
<?php
Header("Content-type: image/jpeg");
     $filename = 'phplogo.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_GAUSSIAN_BLUR);
         imagefilter ($image, IMG_FILTER_SELECTIVE_BLUR);
         imagejpeg ($image);
         imagedestroy ($image);
?>

Effect 4: monochrome effect

We will perform the operation in 2 phases:

• Transform a gray image with the filter IMG_FILTER_GRAYSCALE
• Highlight color levels with the filter IMG_FILTER_NEGATE

Blur creation script on an image
<?php
Header("Content-type: image/jpeg");
     $filename = 'guest.jpg';
     $image =imagecreatefromjpeg ($filename);
         imagefilter ($image, IMG_FILTER_GRAYSCALE);
         imagefilter ($image, IMG_FILTER_NEGATE);
         imagejpeg ($image);
         imagedestroy ($image);
?>

PHP Imports files with include () and require () functions

By Dinesh Thakur

The vast majority of dynamic websites or applications need to reuse parts of identical code in several places of the same page, or in several different pages. This is the case for example libraries of user functions or configuration files. Rather than rewrite each time the code, there are functions (actually language constructs) that can import and execute the code reuse in the page. These are the include () and require ().

The include () and require ()

Firstly why there are two different functions that perform the same function? Their operation is exactly the same but the difference between them lies in the error handling.

Include () will return an error of type WARNING if it does not open the file in question. Thereby running the code in the following page will be executed. However, the require () function will display an error FATAL type that stops the execution of the script.

Which prefer then? Everything depends on context. If the file must be present for the rest of the program, then require () is preferred if an include () will do.

How to use include () and require ()

These two functions take a single parameter type string. This is the path to the file to import. The path is relative default relative to the directory that contains the script. Illustrate this with examples:

<? php
      // Imports with require ()
           require ('../ folder/file.php');
           require 'file2.php';

      // Imports with include ()
           include ('../folder /file.php');
           include 'file2.php';
?>

We note here two possible syntaxes for each. Parentheses are optional (as echo () for example).

Explanation: In the first import of each function, we ask to include the file “file.php” found in the “Folder” at the same level as the script “../”. ../ We go through the levels file tree (return to the parent folder). In the second import, we want to import the file “file2.php” found the same level as this script.

When a file is imported, the code found inside runs. The variables, constants, objects, paintings … the imported file can be reused later in the program. Let’s take a simple example. We have a “config.php” file containing the following code:

File Listing "config.php"
<?php
// Define the variables
$a = 15;
$b = 5;
// Display a text
echo 'A little math ...<br />';
?>

Then a main program named “program.php” contained the same level as the first, which contains the following lines:

File Listing "program.php"
<?php
   // Import and execution file
        require ('config.php');
   // Calculate the sum
        $sum = $a + $b;
   // Display the sum
        echo 'Sum of $a + $b = ', $sum;
?>

The result of the execution of the code is as follows:

Result of the execution of the file "programme.php"
A little math ...

Sum of $a + $b = 20

The sum of $a and $b are displayed on the standard output. We conclude that the variables have been created to import the file and then used in the main program.

Note: these functions are used only for pages with PHP code to execute. To import pure static pages (html or text, for example), use file_get_contents () preceded by an echo () statement.

Require_once () and include_once (), what is it?

The functions require_once () and require_once () allow you to import only once a file if there’s several attempts to import the file into the page.

However the use of these two functions is impaired for optimization purposes. They are indeed slower than their respective little sister because they must also check that the file has been imported once.

Include () and require (), susceptible to hacking !!!

There is a very dangerous security flaw when these functions are not used correctly. This is a flaw related to neglect and ignorance of novice programmers.

In our previous examples, there was no risk of piracy because we had entered file paths hard. But what happens if we write a horror like this?

Dynamic import of example of unsecured page
<?php
      include ($_GET ['page']);
?>

Remember the tutorial on forms processing. $_GET Array contains all values ? passed in the url. In this example, we put a variable named page in the url that contains a value. Three scenarios of behavior include () available to us:

• The value of $_GET [‘page’] is empty or bad therefore include () can not be imported and an error.
• The value of $_GET [‘page’] is filled and is an existing file server. The import will be no problem.
• The value of $_GET [‘page’] is filled but contains the address leading to a dangerous present on a different server pirate file. For example $_GET [‘page’] is http://www.domain.com/hack.php. The file will be imported hack.php and hacked site !!!

We will have understood, it MUST NOT use the code above to dynamically import files.

What solutions can we put in place in this case? The first is first prefix and suffix of the variable to make false links to pirated files and prevent their importation. This example gives:

<? php

require ('/ path/to/something /' $_GET ['page'] '/ php'...);

This code protects us from malicious imports but does not put us in the shelter of an unsightly error on the screen if the file does not exist and may not be imported. An interesting solution is to use an associative array whose key matches the value passed in the variable $ url of the page, and the value the file name to import.

If the code is written in the index.php file, then the pages will be Called well:

• http://www.domain.com/index.php?page=tutorials
• http://www.domain.com/index.php?page=downloads
• http://www.domain.com/index.php?page=contacts

Note: the pages are located in a directory called “pages” on the same level as “index.php”

Dynamic import of such secure pages
<?php
     // Array of files to import
          $arrayPages = array (
          'home' => 'homepage.php',
          'tutorials' => 'tutorials.php',
          'downloads' => 'downloads.php',
          'contacts' => 'contacts.php'
          );

          // Variable $page-it exists in the url?
               if (!empty ($_GET ['page']))
                    {
                        // Check the value passed in the url: is it a key of the table?
                        if (array_key_exists (strtolower ($_GET ['page']), $arrayPages))
                            {
                               // Yes, so it is important
                               include ('pages/' . $arrayPages [strtolower ($_GET ['page'])]);
                            }
                        else
                           {
                               // No, so we import a default file
                                    include ('pages/error 404.php');
                           }
                   }
              else
                  {
                       // No, it displays the default home page
                            include ('pages/' . $arrayPages ['home']);
                  }
?>

In this example, we check that the page in the URL corresponds to an array key (see: array_key_exists() function). If so, then it is important, if not a 404 page are included (file not found). Note the presence of the strtolower () function that forces the value of $_GET [‘page’] in lowercase.

PHP Sessions

By Dinesh Thakur

Since PHP4, we hear a lot about sessions. Many people using PHP still unaware what they are and what they are for. Others, however, do not know how to use it wisely. This tutorial is an approach to theoretical and practical sessions. They will be presented by means of a simple example throughout this course. This is a space site secured by authentication.

What is a session?

A session is a technical mechanism to temporarily save the server information related to a user. This system has been especially invented to overcome the fact that the HTTP protocol is connectionless. Each time you open a new session, the user is given a session identifier. This identifier can be transmitted either GET (PHPSESSID added to the end of the URL) or POST Cookie (cookie on client) as the server configuration. The information will be transferred for their page by page by the server and not by the client. Thus, the security and integrity of the data is improved thereby see their availability throughout the session. A session can contain any type of data: number, string and even a table.

Unlike a database or a file system, the session stores information for a few minutes. This duration depends on the server configuration but is generally set at 24 minutes by default. The server creates files in a particular directory.

The sessions are particularly used for such applications:

• Members spaces and access with secure authentication.
• Managing a basket on an online sales site.
• Forms split on several pages.
• Storing information relating to user navigation (Preferred theme, languages ​​…).

The theory is fine but in practice how it goes? The next section explains the initialization and restoration of an open session.

Initialization (and restoration) of a session

PHP natively introduced a unique feature to start or continue a session. This is session_start (). This function takes no parameters and always returns true. It checks the status of the current session. If it does not exist, then the server creates it if he continues.

Initialization and restoration of session
<?php
    session_start();
?>

In the case of use of sessions with cookies, session_start () must be called before sending to the browser or risk seeing the famous display errors:

“Can not modify header information – headers already sent by …” or “Can not send session cookie – headers already sent by …”. This is due to the fact that PHP can not send any cookie to the user because there’s already had an output to the browser (echo (), print (), white space, html tag …).

Note: you must call session_start () on each page using the login system.

Reading and writing a session

$_SESSION Array

When a session is created, it is empty by default. It therefore has no interest. We must therefore assign values ​​to save temporarily. For this, the PHP language sets up the $_SESSION superglobal. The term means that the superglobal Tabeau maximum visibility in scripts. This means that we can do globally as a local reference to a user function without having to pass a parameter. Table $ _SESSION can be indexed numerically but also associatively. Generally, it is preferred the second in order to give names clear session variables and meaningful.

The session writing

To register a new session variable, it’s simple. You just need to add a key / value pair to the $_SESSION array as illustrated by the following example.

Declare and initialize a variable session
<?php
    // Start or restoration of the session
         session_start ();
   // Writing a new value in the table session
         $_SESSION ['login'] = 'Karan';
?>

$_SESSION Array, which was empty so far, has expanded dynamically and now contains a value (Karan) to the login associative key. A session variable is created.

Note Recall: in place of the string “Karan”, we could have put a number, a boolean or a table for example.

Playing a session variable

After writing, it is the turn of reading. There is nothing simpler. To read the value of a session variable, you must simply call the session table with the appropriate key. The example below illustrates all that.

Playing a session variable
<?php
      // Start or restoration of the session
           session_start ();
      // Read a value of session table
           echo $_SESSION ['login'];
?>

This instruction will cause the screen to display the character string Karan.

Destroying a session

As mentioned above, the server destroys the session itself after a certain time if the session has not been renewed. However, it is possible to force its destruction by the session_destroy () function. This allows eg webmasters to provide a logout page logged members in their personal space. However, the use of session_destroy () alone is not very “clean”. The following code shows a more correct way to end a session.

Clean and complete destruction of a session
<?php
      // Start or restoration of the session
           session_start ();
      // Reset the session table
     // We fully empty
           $_SESSION = Array ();
    // Destruction of the session
           session_destroy ();
    // Destruction of the session table
           unset ($_SESSION);
?>

To be convinced of the destruction of the session, you just have to try to view the contents of the session table using the print_r () function.

Configuring sessions on the server

A session remains open during a certain time. At most it will be that indicated by the php.ini directive session.gc_maxlifetime between two consecutive client clicks. It is recommended not to increase the value entered by default. But why? Simply becaufe if the session to a larger lifespan, it is exposed to piracy risks including session hijacking.

For the same security reasons, it is advisable to configure the server as follows:

PHP configuration recommended for sessions
session.use_cookies 1
session.use_only_cookies 1
session.use_trans_sid 0

This configuration however implies a total restriction for people not accepting cookies. Below, the meaning in the order of 3 previous configuration lines.

• The session ID is transmitted by a cookie.
• Only the cookie can transmit the session identifier.
• The transmitted PHPSESSID in the url is strictly refused.

Practical approach: develop a restricted access

Presentation of the practical case

This introduces a concrete case of use of sessions. This is a basic restricted access. Only a user is allowed to be logged but this example is the basis of creating a member zone. This is exactly the same. To achieve all this, we need two files: the form with the login script and the protected page. Start with the login form. The code is commented, there will be no more explanation.

Form authentication: authentification.php

Case study: identification form to a member's area
<?php
      // Definition of constants and variables
           define ('LOGIN', 'foo');
           define ('PASSWORD', 'tata');
           $errorMessage = '';

      // Test sending the form
           if (!empty ($_POST))
              {
                 // The IDs are transmitted?
                 if (!empty ( $_POST ['login']) && !empty ($_POST ['password']))
                    {
                       // Are they the same as the constants?
                       if ($_POST ['login'] !== LOGIN)
                           {
                               $errorMessage = 'Wrong login!';
                           }
                       elseif ($_POST ['password'] !== PASSWORD)
                          {
                              $errorMessage = 'Wrong password';
                          }
                       else
                         {
                              // Open the session
                              session_start ();
                             // It stores the login session
                             $_SESSION ['login'] = LOGIN;
                            // We redirected to the admin.php file
                            header ('Location: http://ecomputernotes.com');
                            exit ();
                          }
                  }
                      else
                       {
                           $errorMessage = 'Please enter your login please!';
                        }
            }
?>
<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "en">
       <Head>
           <title> Authentication Form </title>
       </Head>
             <body>
                <form action = "<?php echo htmlspecialchars ($_SERVER ['PHP_SELF']);?>" method = "post">
                     <fieldset>
                             <legend> sign in </legend>
                             <?php
                                   // Meeting are we a mistake?
                                   if (!empty ($errorMessage))
                                       {
                                            echo '<p>', htmlspecialchars ($errorMessage), '</ p> ';
                                       }
                             ?>
                            <p>
                                       <label for = "login"> login : </label>
                                       <input type = "text" name = "login" id = "login" value = "" />
                            </p>
                            <p>
                                 <label for = "password"> Password : </ label>
                               <input type = "password" name = "password" id = "password" value = "" />
                                 <input type = "submit" name = "submit" value = "Login" />
                          </p>
                     </fieldset>
                </form>
        </body>
</html>

Example protected page: admin.php

Example of a secure page with sessions
<?php
       // We extend the session
       session_start ();
      // It checks if the session variable exists and contains a value
      if (empty ($_SESSION ['login']))
         {
             // If no or zero, it redirects to the login form
             header ('Location: http://ecomputernotes.com');
             exit ();
         }
?>
<! DOCTYPE html PUBLIC "- // W3C // DTD XHTML 1.1 // EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml" xml: lang = "en">
     <Head>
           <title> Administration </title>
     </Head>
     <body>
     <?php
             // Here it is logged, it displays a message
            echo 'Welcome ', $_SESSION ['login'];
       ?>
    </body>
</html>

Little explanation: to protect each page of the administration, it is essential to add the first file header script entirely. It instantly redirects the user if he is not properly logged. Otherwise it displays the web page.

PHP Cookies

By Dinesh Thakur

Cookies are small files that can be written by a PHP script or other languages, such as JavaScript, on the visitor’s computer. The cookie mechanism was invented by Netscape in the bearing purposes to some HTTP protocol weaknesses but also to extend the possibilities of relationship between the client and the website. Their function is storage, for a given period, of information relating to the user (his nickname, his last login date, age, preferences …). [Read more…] about PHP Cookies

PHP Forms Processing with $ _GET and $ _POST Methods

By Dinesh Thakur

That says “dynamic website” generally called “forms” and therefore treatment of these. PHP was invented especially for this type of task and that is what we will discuss in this new tutorial. We will learn to use the forms via the superglobal arrays $ _GET and $ _POST. We will also determine the difference in the use of each of them. [Read more…] about PHP Forms Processing with $ _GET and $ _POST Methods

PHP Functions:User-defined functions

By Dinesh Thakur

As in most programming languages, it is possible to create your own PHP functions that complement the native functions. This allows performing particular operations that are redundant in the application, and solve a problem by breaking it into several small problems and solutions. [Read more…] about PHP Functions:User-defined functions

PHP Control structures: Loops

By Dinesh Thakur

This tutorial follows the one on conditional statements. The loops are a trivial principle of computing that any developer must master. They are, too, some of the control structures. PHP 4 into account, each with its specific characteristics: for (), while (), do-while () and foreach (). [Read more…] about PHP Control structures: Loops

PHP Control structures: conditions

By Dinesh Thakur

This chapter presents two important principles to assimilate: the condititions and loops. This first concept is especially important since it allows to perform a series of actions depending on the conditions being tested. As for the second, it allows to repeat N times a series of actions, and in very short time (at human scale). The advantage of the arrival of the computer is to make life easier for users performing tasks that they can not fulfill. If you ask a person to count from 0 up to 1000, it will take several minutes while a computer will process this transaction in milliseconds (or even a few nanoseconds as its computing power). Then immediately understand the benefits of computing. [Read more…] about PHP Control structures: conditions

PHP Operator Types

By Dinesh Thakur

There are 12 types of operators in PHP. We will review them using summary tables. Let’s start by arithmetic operators. [Read more…] about PHP Operator Types

PHP Arrays Numeric, Associative and Multi-Dimensional

By Dinesh Thakur

PHP provides structured data types that are more commonly called “tables”. What do they do exactly? How do we handle? [Read more…] about PHP Arrays Numeric, Associative and Multi-Dimensional

PHP Variable Types

By Dinesh Thakur

Among the most important concepts of the programming is the concept of variable. Like any language, PHP handles data. For a dynamic site, these data are variables. In addition, they may be of different types, such as text string, as you have used the echo statement in the form of whole or decimal numbers or as true or false boolean values (TRUE or FALSE). These basic types are the most used, but there are others who may be compounds types, such as arrays and objects, or specific types, as resource or NULL. . We will see that the variable part of the mechanisms which make a dynamic application. Let’s get into the thick of it. [Read more…] about PHP Variable Types

PHP Constants Types

By Dinesh Thakur

In programming, PHP allows you to define constants, it is often necessary to define data structures whose value must not change during program execution. These data structures are typically what is known constants. The most famous mathematical constants is for instance the PI number whose value is approximately 3.1415926535898. Note that PHP natively integrates the M_PI constant. This can then be used for any calculation of circumference. [Read more…] about PHP Constants Types

How many Types of Comments are there in PHP

By Dinesh Thakur

Comments are only intended for the programmer. They will not be displayed or executed. They identify as part of the program without interfering in the program. Comments are among the trivial elements in the success of a program; and this is why it is important to use them with intelligence.

A comment, what is it?

A comment in a programming language, is a line written in natural language (mother tongue of the developer for example) will not be executed by the interpreter (or compiler according to the language used). Its function is to describe or explain some of the code that will reveal is difficult to decipher for maintenance or collaborative work (multiple developers working on the same program).

The comments are therefore particularly useful for a developer, but they are more so when it is a complete team working on the same project. They allow to impose among other nomenclatures and organization in writing the code of a collaborative project. In addition, the comments provide easier maintenance program by its author or a third party.

Another highlight of comments is the generation of technical documentation. Indeed, there are applications such as PHP Documentor that relies on a particular syntax comments to generate documentation for an application. This ensures a significant time saving for a development team.

Comment code is also part of good programming practices to adopt. But it still not be entered to the other extreme where each instruction code become commented. The clarity and readability of the program would then be affected.

The Linear Comment

There are two kinds of comments. The comment on a single line and multi-line comment. Let us look at both methods to review a text on one line.

Comments on a single line

<?php
          // This is a first line comment
               echo 'Hello World!';
  echo'<br />';
         # This is a second line comment
               echo 'Hello World' ;
?>

PHP offers two ways to comment on a text placed on a line. The most widely used method is the first example with the double slash (//) unlike the second using a pound sign (#).

The multiline comment

It allows to comment a written text on multiple lines. It is very frequently used by developers. These comments are defined using symbols /* and */. The example below illustrates their jobs.

Multiline comments

<?php
      /*
         This program was written by Emacs
          It displays the string 'Hello Word!' on the screen
      */
          echo 'Hello World!';
?>
Next Page »

Primary Sidebar

PHP Tutorials

PHP Tutorials

  • PHP - Home
  • PHP - Features
  • PHP - Magic Methods
  • PHP - Imagefilter
  • PHP - Arrays Numeric
  • PHP - Sessions
  • PHP - Forms Processing
  • PHP - clone()
  • PHP - Cookies
  • PHP - Variable Types
  • PHP - First program
  • PHP - call()
  • PHP - Iterator interface
  • PHP - Imports files
  • PHP - Exception Handling
  • PHP - set() and get()
  • PHP - Install MAMP
  • PHP - Functions
  • PHP - Constants Types
  • PHP - Comments Types
  • PHP - OOP's
  • PHP - OOps Use
  • PHP - PHP Code & Redirect 301
  • PHP - Control structures
  • PHP - Abstract Classes
  • PHP - Control structures
  • PHP - Classes
  • PHP - MySQL NULL values
  • PHP - Methods Visibility
  • PHP - Operator Types
  • PHP - Short tags Not use
  • PHP - Object and class
  • PHP - Secure Passwords

Other Links

  • PHP - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW