Thursday, September 24, 2020

A Guide to PHP Web Concepts



Hello dear readers! welcome back to another section of my tutorial on PHP. In this section of our PHP tutorial, we will be studying about the basic PHP Web concepts.

This tutorial will be demonstrating how PHP can be used to create dynamic content according to web browser type, randomly generated numbers or User input. It also demonstrates how the client web browser can be redirected.

Identifying Browser & Platform

PHP creates some functional environment variables that can be seen in the phpinfo.php page that was used in setting up the PHP environment.

One of the environment variables set by PHP is HTTP_USER_AGENT which identifies the user's browser and operating system.

RECOMMENDED POST: PHP Arithmetic Operators

PHP provides a function called getenv() to access the value of all environment variables. The data held in the HTTP_USER_AGENT is used to create dynamic content that is appropriate to the browser.

Example

The following example shows how you can recognize a client's web browser and operating system.

<html>
   <body>
   
      <?php
         function getBrowser() { 
            $u_agent = $_SERVER['HTTP_USER_AGENT']; 
            $bname = 'Unknown';
            $platform = 'Unknown';
            $version = "";
            
            //First get the platform?
            if (preg_match('/linux/i', $u_agent)) {
               $platform = 'linux';
            }elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
               $platform = 'mac';
            }elseif (preg_match('/windows|win32/i', $u_agent)) {
               $platform = 'windows';
            }
            
            // Next get the name of the useragent yes seperately and for good reason
            if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) {
               $bname = 'Internet Explorer';
               $ub = "MSIE";
            } elseif(preg_match('/Firefox/i',$u_agent)) {
               $bname = 'Mozilla Firefox';
               $ub = "Firefox";
            } elseif(preg_match('/Chrome/i',$u_agent)) {
               $bname = 'Google Chrome';
               $ub = "Chrome";
            }elseif(preg_match('/Safari/i',$u_agent)) {
               $bname = 'Apple Safari';
               $ub = "Safari";
            }elseif(preg_match('/Opera/i',$u_agent)) {
               $bname = 'Opera';
               $ub = "Opera";
            }elseif(preg_match('/Netscape/i',$u_agent)) {
               $bname = 'Netscape';
               $ub = "Netscape";
            }
            
            // finally get the correct version number
            $known = array('Version', $ub, 'other');
            $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';
            
            if (!preg_match_all($pattern, $u_agent, $matches)) {
               // we have no matching number just continue
            }
            
            // see how many we have
            $i = count($matches['browser']);
            
            if ($i != 1) {
               //we will have two since we are not using 'other' argument yet
               
               //see if version is before or after the name
               if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
                  $version= $matches['version'][0];
               }else {
                  $version= $matches['version'][1];
               }
            }else {
               $version= $matches['version'][0];
            }
            
            // check if we have a number
            if ($version == null || $version == "") {$version = "?";}
            return array(
               'userAgent' => $u_agent,
               'name'      => $bname,
               'version'   => $version,
               'platform'  => $platform,
               'pattern'   => $pattern
            );
         }
         
         // now try it
         $ua = getBrowser();
         $yourbrowser = "Your browser: " . $ua['name'] . " " . $ua['version'] .
            " on " .$ua['platform'] . " reports: <br >" . $ua['userAgent'];
         
         print_r($yourbrowser);
      ?>
   
   </body>
</html>

Output

When the above code is executed, it will produce the following result on my machine. This result may be different on your various machines depending on what you are using -

Your browser: Google Chrome 54.0.2840.99 on windows reports: 
Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) 
   Chrome/54.0.2840.99 Safari/537.36

RECOMMENDED: PHP Logical Operators

Display Images Randomly

The PHP rand() function is used to generate random numbers. It can generate random numbers with-in a given range. The random number generator should be seeded in order to prevent a regular pattern of numbers being created. This is achieved by making use of the srand() function that specifies the seed number as its argument.

Example

Following example shows how you can display different image each time out of four images -

<html>
   <body>
   
      <?php
         srand( microtime() * 1000000 );
         $num = rand( 1, 4 );
         
         switch( $num ) {
            case 1: $image_file = "/php/images/logo.png";
               break;
            
            case 2: $image_file = "/php/images/php.jpg";
               break;
            
            case 3: $image_file = "/php/images/logo.png";
               break;
            
            case 4: $image_file = "/php/images/php.jpg";
               break;
         }
         echo "Random Image : <img src=$image_file />";
      ?>
      
   </body>
</html>

Output

When the above code is executed, it will produce the following result -


RECOMMENDED: PHP Decision Making

Using HTML Forms

The most important thing that is to be noticed when dealing with Html forms and PHP is that any form element in an Html page will automatically be available to your PHP scripts.

Example

Try the following example below by putting the source code in a test.php script -

<?php
   if( $_POST["name"] || $_POST["age"] ) {
      if (preg_match("/[^A-Za-z'-]/",$_POST['name'] )) {
         die ("invalid name and name should be alpha");
      }
      
      echo "Welcome ". $_POST['name']. "<br />";
      echo "You are ". $_POST['age']. " years old.";
      
      exit();
   }
?>
<html>
   <body>
   
      <form action = "<?php $_PHP_SELF ?>" method = "POST">
         Name: <input type = "text" name = "name" />
         Age: <input type = "text" name = "age" />
         <input type = "submit" />
      </form>
      
   </body>
</html>

Output

When the above code is executed, it will produce the following result -


  • The default variable of PHP $_PHP_SELF is used for the PHP script name and when you click on "submit" button then same PHP script will be called.
  • The method "POST" is used to post user information to the server script. There are two methods to post data to the server script which are discussed in my tutorial on PHP GET & POST Methods.

RECOMMENDED: A Guide to PHP Arrays

Browser Redirection

PHP header() function supplies raw HTTP headers to the Web browser and it can also be used to redirect it to another location. The redirection script should be at the very top of the page so as to prevent any other part of the page from loading.

The target is specified by the Location: header as argument to the header() function. After this function is been called the exit() function is used to halt parsing of the rest of the code.

Example

The following example shows how you can redirect a browser request to another web page.

<?php
   if( $_POST["location"] ) {
      $location = $_POST["location"];
      header( "Location:$location" );
      
      exit();
   }
?>
<html>
   <body>
   
      <p>Choose a site to visit :</p>
      
      <form action = "<?php $_SERVER['PHP_SELF'] ?>" method ="POST">
         <select name = "location">.
         
            <option value = "http://www.webdesigntutorialz.com">
               Webdesigntutorialz.com
            </option>
         
            <option value = "http://www.google.com">
               Google Search Page
            </option>
         
         </select>
         <input type = "submit" />
      </form>
      
   </body>
</html>

Output

When the above code is executed, it will produce the following result -


RECOMMENDED: Strings in PHP

Alright guys! This is where we are rounding up for this tutorial post. In my next tutorial post, we will be discussing about the PHP GET and POST Methods

Feel free to ask your questions where necessary and i will attend to them as soon as possible. If this tutorial was helpful to you, you can use the share button to share this tutorial.

Follow us on our various social media platforms to stay updated with our latest tutorials. You can also subscribe to our newsletter in order to get our tutorials delivered directly to your emails.

Thanks for reading and bye for now.
Share:

0 comments:

Post a Comment

Hello dear readers! Please kindly try your best to make sure your comments comply with our comment policy guidelines. You can visit our comment policy page to view these guidelines which are clearly stated. Thank you.