Php Tutorial 1-10/46

Php Tutorial


  1. PHP is a script language and interpreter that is freely available and used primarily on Linux Web servers. PHP, originally derived from Personal Home Page Tools, now stands for PHP: Hypertext Preprocessor, which the PHP FAQ describes as a "recursive acronym."

  • A class to put get and post variables in hidden form
  • Add Slashes Recursively
  • Age from DATE
  • Array Insertion
  • Binary to Text
  • Cookie
  • Cookie Examples
  • Create a database
  • Authenticate user: Database based
  • Get data from database query 



Name Code

A class to put get and post variables in hidden form


  < ? php
     class c_HiddenVars
     {
       function display($a)
       {
         $c = Count($a);
         for ($i = 0, Reset($a); $i < $c; $i++, Next($a))
         {
           $k = Key($a); $v = $a[$k];
           if (is_array($v))
           {
             $vc = Count($v);
             for (Reset($v), $vi = 0; $vi < $vc; $vi++, Next($v))
             {
               $vk = Key($v);
               echo "< input type=hidden name=\"$k\[$vk\]\" value=\"".htmlspecialchars($v [$vk]). "\">\n";
             }
           }
           else
           {
             echo "< input type=hidden name=\"$k\" value=\"".htmlspecialchars($v). "\">\n";
           }
         }
       }
  
       function get()
       {
         global $HTTP_GET_VARS;
         if (is_array($HTTP_GET_VARS))
         {
           $this->display
           ($HTTP_GET_VARS);
         }
       }
       function post()
       {
         global $HTTP_POST_VARS;
         if (is_array($HTTP_POST_VARS))
         {
           $this->display
           ($HTTP_POST_VARS);
         }
       }
       function all()
       {
         $this->get();
         $this->post();
       }
     };
   ?> 

Add Slashes Recursively


  < ?
     function aslashes($array)
     {
       if(is_array($array))
       {
         foreach($array as $key => $val)
         {
           if(is_array($key)
           {
             return aslashes($key);
           }
           else
           {
             $return[$key] = stripslashes($val); // recurse
           }
         }
       return($return);
       }
       else
       {
         return(addslashes($array)); // return slash'ed value
       }
     }
   ? > 

Age from DATE


  //Input format: YYYY-MM-DD
  function years_age($birthday)
  {
     list($year,$month,$day) = explode("-",$birthday);
     $year_diff = date("Y") - $year;
     $month_diff = date("m") - $month;
     $day_diff = date("d") - $day;
     if ($day_diff < 0 || $month_diff < 0)
       $year_diff--;
     return $year_diff;
  } 

Array Insertion


  class arrayAll
  {
     var $startError = 'Warning:Check your input parameters';
     var $endError = '';
     function Insert($array = '', $position = '' , $elements= '')
     {
       if ($position == '' || $array == '' || $elements == '' || $position < 1 || $position > count($array)+1)
       {
         echo $this->startError . "insert".$this->endError;
       }
       else
       {
         $left = array_slice ($array, 0, $position+1);
         $right = array_slice ($array, $position+1,count($array));
         for($i=1; $i< COUNT($elements) ; $i++)
         {
           $insert[$i] .= $elements[$i] ;
         }
         $array = array_merge ($left, $insert, $right);
         // echo " Left Count : " . COUNT($left) . "
\n";
         // echo " Insert Count : " . COUNT($insert) . "
\n";
         // echo " Right Count : " . COUNT($right) . "
\n";
         unset($left, $right, $insert);
       }
       unset ($position, $elements);
       return $array ;
     }
  } 

Binary to Text 


  < ?
     function bin2text($bin_str)
     {
       $text_str = '';
       $chars = explode("\n", chunk_split(str_replace("\n", '', $bin_str), 8));
       $_I = count($chars);
       for($i = 0; $i < $_I; $text_str .= chr(bindec($chars[$i])), $i );
       return $text_str;
     }
     function text2bin($txt_str)
     {
       $len = strlen($txt_str);
       $bin = '';
       for($i = 0; $i < $len; $i )
       {
         $bin .= strlen(decbin(ord($txt_str[$i]))) < 8 ? str_pad(decbin(ord($txt_str[$i])), 8, 0, STR_PAD_LEFT) : decbin(ord($txt_str[$i]));
       }
       return $bin;
     }
     print text2bin('How are you gentlements?');
  ? > 

Cookie

  • What is a Cookie?
    A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

  • How to Create a Cookie?
    Syntax:
    setcookie(name, value, expire, path, domain);
    Example -
    setcookie("user", "Alex Porter", time()+3600);

  • How to Retrieve a Cookie Value?
    The PHP $_COOKIE variable is used to retrieve a cookie value.
    Example -
    // Print a cookie
    echo $_COOKIE["user"];
    // A way to view all cookies
    print_r($_COOKIE);

  • How to Delete a Cookie?
    When deleting a cookie you should assure that the expiration date is in the past.
    // set the expiration date to one hour ago
    setcookie("user", "", time()-3600);

Cookie Example

  • Checking for Cookie Support from PHP


      < ? php
         if(!isset($_GET['testcookie']))
         {
           setcookie("testcookie", "test value");
           header("Location: {$_SERVER["PHP_SELF"]}?testcookie=1");
           exit;
         }
         else
         {
           if(isset($_COOKIE['testcookie']))
           {
             setcookie("testcookie");
             echo "You have cookies enabled";
           }
           else
           {
             echo "You do not support cookies!";
           }
         }
      ? >
  • Reading all cookie values


      < ? php
         foreach ($_COOKIE as $cookie_name => $cookie_value)
         {
           print "$cookie_name = $cookie_value
    ";
         }
      ? >
  • Still Logged In with cookie


      < ? php
         $auth = $_COOKIE['auth'];
         header( "Cache-Control:no-cache" );
         if( ! $auth == "ok" )
         {
           header("Location:login.php" );
           exit();
         }
      ? >
  • Printing a cookie value


       < ? php
         print 'Hello, ' . $_COOKIE['userid'];
       ?>
  • Reading a cookie value


      < ? php
        if (isset($_COOKIE['flavor']))
        {
           print "You ate a {$_COOKIE['flavor']} cookie.";
        }
      ?> 

Create a database


  < ? php
     $db = "newdb";
     //connect to server with username and password
     $connection = @mysql_connect ("localhost","root", "") or die (mysql_error());
     //connect to database
     $result = @mysql_create_db($db, $connection) or die(mysql_error());
     if ($result)
     {
       echo"Database has been created!";
     }
  ?> 

Authenticate user: Database based 


  < ? php
     function authenticate_user()
     {
       header('WWW-Authenticate: Basic realm="Secret Stash"');
       header("HTTP/1.0 401 Unauthorized");
       exit;
     }
     if (! isset($_SERVER['PHP_AUTH_USER']))
     {
       authenticate_user();
     }
     else
     {
       mysql_pconnect("localhost","authenticator","secret") or die("Can't connect to database server!");
       mysql_select_db("abcd") or die("Can't select authentication database!");
       $query = "SELECT username, pswd FROM user WHERE username='$_SERVER[PHP_AUTH_USER]' AND pswd=MD5('$_SERVER[PHP_AUTH_PW]')";
       $result = mysql_query($query);
       // If nothing was found, reprompt the user for the login information.
       if (mysql_num_rows($result) == 0)
       {
         authenticate_user();
       }
     }
  ? >             

Get data from database query


   < ? php
     $cnx = mysql_connect('mysql153.secureserver.net','abcd','password');
     mysql_select_db('abcd');
     $employees = @mysql_query('SELECT ID, FirstName FROM Employee');
     if (!$employees)
     {
       die('Error retrieving employees from database!'.
       'Error: ' . mysql_error() );
     }
     while ($employee = mysql_fetch_array($employees))
     {
       $id = $employee['ID'];
       $name = htmlspecialchars($author['Name']);
       echo("$name ");
  v     echo("$id");
     }
   ? > 
Php Tutorial 1-10/46 Php Tutorial 1-10/46 Reviewed by Abdul hanan on 05:20:00 Rating: 5
Powered by Blogger.