Store Page View Count In Session Variable: PHP

PHP program to store page views count in SESSION, to increment the count on each refresh, and to show the count on web page.

Session: A session is specific to the user and for each user a new session is created to track all the request from that user. Every user has a separate session and separate session variable which is associated with that session.

The concept of session is more visible and practical when we explain building log in form using MySQL database. Until then, memorize the above definition!

In this PHP program, as the above question suggests: we are storing the page view count in a session variable and incrementing it on each page view.

Mechanism used:
On the first visit, the session variable is set to 1 and as this is the first visit, a message “Session does not exist” is displayed on the web page.
As the session variable is set to 1 on first visit, on consecutive visits the code inside the if block is executed and the value of the session variable is echo’ed or printed on to the browser and then incremented by one.

Video Tutorial: Store Page View Count In Session Variable: PHP


[youtube https://www.youtube.com/watch?v=VmB6ZrhLAp0]

YouTube Link: https://www.youtube.com/watch?v=VmB6ZrhLAp0 [Watch the Video In Full Screen.]


Source Code: Store Page View Count In Session Variable: PHP

(session.php)

<?php 
session_start();
 
if(isset($_SESSION['count']))
{
echo "Your session count: ".$_SESSION['count']."<br />";
$_SESSION['count']++;
}
else
{
$_SESSION['count'] = 1;
echo "Session does not exist";
}
 
?>

Code Explanation: Logic

session_start() is a standard call and is mandatory step to start the session. On each page, wherever you use the session variable, you must write session_start() before using the session variable. It is a usual practice to write session_start(); as the first line of code in a php program whenever necessary.

$_SESSION[‘sessionName’] is a session variable. sessionName is the session name and it should be enclosed within single quote.

isset() is a standard php function which returns true or false depending upon whether the passed parameter is set or not.

In all major programming languages(including PHP) we use shorthand notations like $_SESSION[‘count’]++; which means $_SESSION[‘count’] = $_SESSION[‘count’] + 1; Here ++ is called increment operator.
And in $_SESSION[‘count’]- -; which is equal to writing $_SESSION[‘count’] = $_SESSION[‘count’] – 1; Here – – is called decrement operator.

Randomly Display Some Images From A Set of Images: PHP

Use of this script:
1. If you have a photo blog with 100 or more images, using this small php script you can show some random images on your homepage, to keep it more dynamic.. This makes up for a good user experience due to constant fresh content(images) each time.
2. If you have 10 products and you want to show atleast 3 products image on your homepage, using this php script you can randomly display the images and yet not bore your audience!

Video Tutorial: Randomly Display Some Images From A Set of Images: PHP


[youtube https://www.youtube.com/watch?v=ajAj6oAkz60]

YouTube Link: https://www.youtube.com/watch?v=ajAj6oAkz60 [Watch the Video In Full Screen.]


Source Code: Randomly Display Some Images From A Set of Images: PHP

(image.php)

<?php
$pic = array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg');
shuffle($pic);
?>
<html>
 <head>
  <title>Random Images</title>
 </head>
 <body>
  <ul>
<?php
   for( $i = 0; $i < 3; $i++)
      echo "<li style=\"display: inline;\">
                         <img src=\"$pic[$i]\" width=\"250\" height=\"250\">
                       </li>";
 
?>
 </ul>
 
 </body>
</html>

Copy and paste above code into a plain text editor. Save the file with .php file extension. Make sure to have 5 image files(with .jpg extensions) in the same folder as image.php

random-image


PHP Code Explanation:

Arrays are very important concept in all programming language.

 $pic = array('1.jpg','2.jpg','3.jpg','4.jpg','5.jpg');

here $pic is an array variable and is used to store the file names of all the images.

shuffle($pic);

shuffle() is a standard PHP function, which shuffles the content of the array variable. i.e., it re-orders or changes the position of the elements of an array.

<?php
for( $i = 0; $i < 3; $i++)
echo "<li style=\"display: inline;\">
                           <img src=\"$pic[$i]\" width=\"250\" height=\"250\">
                        </li>";
?>

Usually unordered listing tags of HTML displays elements vertically.

<li style="display: inline;"> </li>

But using some css style property, we are showing the images horizontally.
i.e., display: inline;

for loop, loops through 0 to 3(in above example). After the execution of the above line of code(for one instance), we get the following HTML output in the browser.

<ul>
 <li style="display: inline;">
            <img src="4.jpg" width="250" height="250">
 </li>
 <li style="display: inline;">
           <img src="5.jpg" width="250" height="250">
 </li>
 <li style="display: inline;">
            <img src="1.jpg" width="250" height="250">
 </li>
</ul>

\ (back slash) is used as an escape character, to escape the effect of (double quote).

Dynamic Page Creation: PHP

In this PHP program we will not be generating pages, but creating the illusion of dynamic page creation!
i.e., we will have a bunch of files inside a directory. We will fetch the contents of these files and display on a single file(index.php).

Advantages:
1. Eliminating duplicate coding: Since, we will display the contents on single page, all the common content will be written in that single page.
2. Common user will not be able to track the exact location of the individual files.
3. We can track, if the user is trying to access a file that does not exist, and then we can show appropriate messages: This will be user friendly and also helps in Search Engine Optimization(SEO), as we can specially design our 404 pages.

Note: Even though this dynamic page creation may not be something you are looking for right now, I am sure, you will encounter a situation in your project development where this technique will come handy. So nevertheless, have it in your tool box!


[youtube https://www.youtube.com/watch?v=RrSRO248NOQ]

YouTube Link: https://www.youtube.com/watch?v=RrSRO248NOQ [Watch the Video In Full Screen.]


PHP Program with CSS implemented:

(index.php)

<html>
 <head><title> Dynamic Pages </title>
 
<style type="text/css">
 
* {
font-family: Verdana;
font-size: 24pt;
 
}
#menu {
position: absolute;
top: 50px;
left: 200px;
 
padding: 10px;
margin:  10px;
 
background-color: pink;
 
}
 
#content {
position: absolute;
top: 50px;
left: 450px;
 
padding: 10px;
margin:  10px;
 
background-color: yellow;
color: red;
 
}
 
 
</style>
 </head>
 <body>
 
  <div id="menu">
 
<a href="index.php">Home</a><br />
<a href="index.php?page=js">Javascript</a><br />
<a href="index.php?page=cSharp">C Sharp</a><br />
<a href="index.php?page=css">CSS</a><br />
 
  </div>
 
 <div id="content">
 
<?php
 $p = $_GET['page'];
 
$page = "sub/".$p.".php";
 
if(file_exists($page))
include($page);
elseif($p=="")
echo "This is Home Page";
else
echo "what are you looking for! ?";
 
?>
  </div>
 
 
 </body>
</html>

In the menu div, we are having some anchor tags, using which we are passing the file names to the variable page. Which we receive in the php code(same page) and add the exact file location and check whether the file exists in the specified location or not.

Based on the file name passed, we will include the corresponding file content in the content div section. If nothing is passed, then its home page. If some irrelevant file names are passed, then we will show some messages: Here we can design a 404 error message page and show it – each time someone tries to access a page that does not exists.

File Structure:

file-structure
Save all these below files ( js.php, cSharp.php, css.php and index.php ) as shown in above image.

js.php Content:

This is Javascript File...

cSharp.php Content:

This is C Sharp....

css.php Content:

This is Cascading StyleSheet...

[ Above files are kept simple in-order to save time and to keep the program explanation simple. You can use your web designing skills to make the pages as you like. ]

PHP Code Explanation:

$p = $_GET['page'];

This line of code accepts the parameter sent by the anchor tags and stores it in a variable by name p.

       $page = "sub/".$p.".php";

sub is the folder name, inside which we have our js.php, cSharp.php and css.php files.

Ex:
If the link corresponding to cSharp is clicked. Then variable p will have the string cSharp in it.
So, variable page will have sub/cSharp.php in it.

if-elseif-else Statement:

       if(file_exists($page))
            include($page);
        elseif($p=="")
            echo "This is Home Page";
        else
            echo "what are you looking for! ?";

file_exists is a built-in php function, which checks if the specified page/file exists or not.
If it exists, then we will include that page. i.e., the content of the page will be displayed.
If variable p has nothing in it, then the clicked link is home page.
If some non-existing page is passed, then we display the message “What are you looking for! ?”.

Return Multiple Values From Function Using Arrays In PHP

If you are a C/C++ programmer, then you know that functions can not return more than one value. To over come this, they use Call by Reference – where address of the variables is passed, hence whenever the value in the passed address changes, the value of the actual variable changes without anything being returned.

In PHP we can accomplish this with the help of arrays.

Video Tutorial: Return Multiple Values From Function Using Arrays In PHP


[youtube https://www.youtube.com/watch?v=HsX2ay702R8]

YouTube Link: https://www.youtube.com/watch?v=HsX2ay702R8 [Watch the Video In Full Screen.]


Work Flow: Logic

Step 1: Here we pass the values to the function.

Step 2: Calculation or operation takes place inside the function.

Step 3: In case there are multiple things to return, we store it inside a array variable. Ex: $result = array($add, $sub, $mul, $div);

Step 4: We return the array variable.

Step 5: Now using array index we display the individual result using echo or print statement.

Source Code: Return Multiple Values From Function Using Arrays In PHP

<html>
 <head><title>Return Multiple Values From Functions, 
                                           using Arrays: In PHP</title></head>
 <body>
 
<?php
$get_result = calc(20, 10);
 
echo "Addition: ".$get_result[0]."<br />Subtration :".$get_result[1].
"<br />Multiplication: ".$get_result[2]."
                         <br />Division: ".$get_result[3];
echo "<br /><br />";
 
print_r ($get_result);
 
?>
 
<?php
function calc($one, $two)
{
$add = $one + $two;
$sub  =  $one  -  $two;
$mul = $one * $two;
$div  =  $one  / $two;
 
$result = array($add, $sub, $mul, $div);
 
return $result;
}
?>
 
 </body>
</html>

Output:
Addition: 30
Subtration :10
Multiplication: 200
Division: 2

Array ( [0] => 30 [1] => 10 [2] => 200 [3] => 2 )

Things To Remember:

1. All PHP files must have .php file extension.

2. Concatination operator in PHP is . [DOT]

3. print_r is a function which takes array variable as its argument and displays the input array structure. Ex: print_r ($get_result);

4. Function is defined in php using the keyword function, followed by function name.

5. $ is used to declare variables in PHP.

Array Syntax In PHP:
$variable = array(arrayElements);

For Numbers: Ex: $num = array(20, 40, 50, 60, 100);
For Strings: Ex: $str = array(“Microsoft”,”Apple”,”Oracle”,”Google”);
For Character: Ex: $chr = array(‘A’,’E’,’I’,’O’,’U’);

array is a keyword for declaring/initializing arrays in PHP.

PHP Comments, String Concatenation, Addition of Numbers & Hello World

Today lets see these 4 basic things:
1. The classic “Hello World” program.
2. Comment system in PHP.
3. Concatenation of Strings.
4. Addition of Numbers.



Classic “Hello World” program
Program to output simple string

1
2
3
<?php
          echo "Hello World";
?>

Comments:

1
// This is single line comment
1
# This is also a single line comment
1
2
3
/* This is how multi-line comments
    are written.
*/

Anything following a double forward slash or a hash( # ) symbol will be ignored by your parser. Comments are very important and are often ignored by programmers. Comments come handy when we come back to the codes and want to make some changes to the coding. So its always a good practice to write comments wherever appropriate.

Concatenation of Strings
Concatination is joining of two or more strings end to end. Ex: if we concatenate Micro and soft, it will become Microsoft.
In PHP, we use .[DOT] operator for concatenation. Below is an example:

1
2
3
4
<?php 
         echo "Micro" . "soft";
         echo "<br />Oracle, " . "Sun Microsystems";
?>

The output for the above php code is:

1
2
Microsoft
Oracle, Sun Microsystems

Addition of Numbers
We can use variables for addition of numbers or we can simply make use of echo or print for addition of numbers.

1
2
3
<?php
         echo 10+20;
?>

This gives 30 as the output.

1
2
3
<?php
         echo "5"+10;
?>

This gives 15 as output. The string “5” will be implicitly converted into number and will be added to the actual number 10.