Dynamic Content Handling in PHP

Last updated on May 31 2022
Aridam Das

Table of Contents

Dynamic Content Handling in PHP

This blog demonstrates how PHP can provide dynamic content according to browser type, randomly generated numbers or User Input. It also demonstrated how the client browser can be redirected.

Identifying Browser & Platform

PHP creates some useful environment variables that can be seen in the phpinfo.php page that was used to setup the PHP environment.

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

PHP provides a function getenv() to access the value of all the environment variables. The information contained in the HTTP_USER_AGENT environment variable can be used to create dynamic content appropriate to the browser.

Following example demonstrates how you can identify a client 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>

This is producing following result on my machine. This result may be different for your computer depending on what you are using.

It will produce the following result −

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

Display Images Randomly

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

Following example demonstrates 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>

 

Using HTML Forms

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

Try out following example by putting the source code in 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>

It will produce the following result −

  • The PHP default variable $_PHP_SELF is used for the PHP script name and when you click “submit” button then same PHP script will be called and will produce following result −
  • The method = “POST” is used to post user data to the server script. There are two methods of posting data to the server script which are discussed in PHP GET & POST section.

Browser Redirection

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

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

Following example demonstrates how you can redirect a browser request to another web page. Try out this example by putting the source code in test.php script.

<?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.tecklearn.com">

               Tecklearn.com

            </option>

        

            <option value = "http://www.google.com">

               Google Search Page

            </option>

        

         </select>

         <input type = "submit" />

      </form>

     

   </body>

</html>


So, this brings us to the end of blog. This Tecklearn ‘Dynamic Content Handling in PHP’ blog helps you with commonly asked questions if you are looking out for a job in PHP Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

 

0 responses on "Dynamic Content Handling in PHP"

Leave a Message

Your email address will not be published. Required fields are marked *