Google search

Basic and advanced computer skills like Excel with macros, How to speed up your PC, C, CPP, Java programming, HTML, JavaScript, PHP, Wordpress, all web tools, Android tutorials, MySQL Tutorials, WAMP server installation. etc.

PHP Function, Cookies, Session examples

1. PHP Program to use of user-defined function.
<?php
function msg()
{
echo "Hello from msg function!";
}

function test()
{
echo "Hello from test function!";
}

test();
echo "<hr>";
msg();
?>

Output of above code is...
function without parameter







2. PHP Program to use of function with parameters.
<?php
function add($a, $b)
{
$c=$a+$b;
echo "sum=", $c;
}
add(2,5);
?>

3. PHP Program to create cookies.
<html>
   <head>
    <title>Set Cookies</title>
   </head>

<?php
setcookie("username", "Raj", time()+120, "/","", 0);
setcookie("age", "50", time()+120, "/", "",  0);
setcookie("country", "India", time()+120, "/", "",  0);
?>
   
  <body>
    <?php echo "Setting Cookies..." ?>
   </body>
   
</html>


setting cookies




4. PHP Program to retrieve cookies values [from above program]
  <?php
echo "<h1>Fetching Cookies Value </h1>";
         echo $_COOKIE["username"]. "<br>";
         echo $_COOKIE["age"] . "<br>";
         echo $_COOKIE["country"] . "<br>";
      ?> 


fetching cookies values







5. PHP Program to retrieve server information using super global variables. 
<?php 
echo "<h1> PHP Superglobal variables </h1>"; 
echo "Location:",$_SERVER['SERVER_NAME'];
echo "<br>";
echo "Port number:",$_SERVER['HTTP_HOST'];
echo "<br>";
echo "Browser info:", $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo "File name:", $_SERVER['SCRIPT_NAME'];
?>

Output of the program is...
superglobal-variables










6. PHP Program to use of SESSIONS.
<?php
   session_start();
   if( isset( $_SESSION['c'] ) ) 
{
 $_SESSION['c'] += 1;
}

else
{
$_SESSION['c'] = 1;
}
    
 $msg = "You are visitor number : ". $_SESSION['c'];
?>
<?php  echo ( $msg ); ?>

Above program produces following output.
session-examples





7. PHP example to demonstrate destroy the sessions.
<?php
session_start();
session_destroy();
echo "<h1> Session destroyed!</h1>";
?>

And the output is...
session destroyed





No comments:

Post a Comment