Document Sample
Php Powered By Docstoc
					Introduction to PHP

   PHP Fundamentals
What is PHP?
   PHP stands for "PHP Hypertext Preprocessor”
   PHP is a server-side scripting language designed
    specifically for the Web.
   An open source language
   PHP code can be embedded within an HTML page,
    which will be executed each time that page is visited.
   Example code (all equivalent):
       Short Style: <? echo “Hello World!”; ?>
       XML Style: <?php echo “Hello World!”; ?>
       Script Style: <SCRIPT LANGUAGE=‘php’> echo “Hello
        World!”; </SCRIPT>
       ASP Style: <% echo “Hello World!”; %>
               History of PHP

   Created by Rasmus Lerdorf in 1995 for tracking
    access to his resume
   Originally a set of Perl scripts known as the
    “Personal Home Page” tools
   Rewritten in C with database functionality
   Added a forms interpreter and released as
    PHP/FI: includes Perl-like variables, and HTML
    embedded syntax
Processing a PHP Page

    Zdnet Statistics
        PHP pumped out about 47 pages/second
        Microsoft ASP pumped out about 43 pages/second
        Allaire ColdFusion pumped out about 29 pages/second
        Sun Java JSP pumped out about 13 pages/second

         * From PHP HOWTO, July 2001
Features of PHP
   Very Efficient – Can serve millions of hits per day.
   Database Integration – Supports many databases, such as
    mySQL and Oracle. Also has excellent XML support as of PHP 5.
   Built-in Libraries – Tailored to web development, one can
    connect to other network services, send email, work with cookies,
    generate PDF documents, and make GIF images on the fly all with a
    few lines of code.
   It’s Free – Available on
   Easy to Learn – Very similar in syntax to C/C++/Java and Perl.
   Portable – Works on Unix based operating systems, on Mac OS X, as
    well as on versions of Microsoft Windows. Your PHP code will often
    work without modification on a different system running PHP.
What is PHP Good For?

   It is great for complex web page designs
       E-commerce sites with heavy traffic (ex. Amazon)
       Complex bulletin boards and forums (ex. phpBB)
       Secure websites (ex. Novasis)
       Email web hosts (ex. Gmail)
       Working with and integrating XML into your webpage
       Database management and search (ex. theFaceBook)
Differences From Java

   Data types are not required in variable
   The $ symbol precedes all variables in PHP
   Constants are declared using the define()
    method in PHP: ex. define(“AOL", "something");
   Constructors do not necessarily have to be
    the same name as the class name.
   Destructors are used in PHP to remove
    objects from memory after they are
The Basics
The Results

                 Output from a script
                  goes directly into the
                  HTML that is parsed
                 This is what is meant
                  by a ‘dynamic’

   Variables in PHP are represented by a dollar
    sign followed by the name of the variable.
    The variable name is case-sensitive.
   Variable names follow the same rules as
    other labels in PHP. A valid variable name
    starts with a letter or underscore, followed by
    any number of letters, numbers, or
Example Script

$subj = 'E Commerce ';
echo $subj ;
echo "$subj";
echo "\$subj";
Data Types

   Four scalar types:
   boolean integer        double             string
   Two compound types:
   array            object
   The type of a variable is usually not set by the
    programmer; rather, it is decided at runtime by
    PHP depending on the context in which that
    variable is used.
   To get the data type of some particular variable, we
    can use gettype() function.
Example Script
echo gettype($varint),"<br>";
echo gettype($vardouble),"<br>";
echo gettype($varstring1),"<br>";
echo gettype($varstring2),"<br>";
echo gettype($varbool),"<br>";
PHP Language Basics

   Constants, Data Types and Variables
       Operators
             Contains all of the operators like in C and Perl (even the
       Statements
             if, if/elseif
             Switch/case
             for, while, and do/while loops
             Include and require statements for code reuse
PHP Language Basics
   Arithmetic Operators
   $m=$a + $b ; $n= $a - $b ; $p= $a * $b ; $q=$a / $b;
   $r=$a % $b;
   Assignment Operators
   $a = 4;            $b = $a;

   Comparison Operators
   $a == $b   $a != $b        $a < $b $a > $b $a <= $b    $a >=
   Increment & Decrement Operators
   PHP also supports the standard increment and decrement
PHP Language Basics

   Concatenating Strings
   The "." operator concatenates two values:
    $sentence_a = "statement 1 ";
    $sentence_b = " statement 2”
    $sentence_c = $a . $b;
PHP Language Basics

   if (condition here) { }
   if (condition here) { }
    else { }

   if (condition here) { }
     elseif ( another condition here ) { }
    elseif ( yet another condition here ) { }
    else { }       //none of the other conditions
PHP Language Basics
switch(condition variable to check)
  { case "true":
     do some stuff here;
  case "another condition is true":
    do some more processing here;
  default:            // no above
  conditions are true
     perform some default processing
PHP Language Basics

WHILE (condition here) {}

FOR (first condition, test
  condition,    increment
  condition   ) { }
PHP Language Basics

   Hello World!: An Example
       There is more than one way to do it
          echo “Hello World!”; ?>

          $greeting = “Hello World!”
          printf(“%s”, $greeting);

          $hello = “Hello”;
          $world = “World!”;
          print $hello . $world;

Constants & Data Types

    Constants define a string or numeric
    Constants do not begin with a dollar
    Examples:
        define(“COMPANY”, “Acme Enterprises”);
        define(“YELLOW”, “#FFFF00”);
        define(“PI”, 3.14);
        define(“NL”, “<br>\n”);
Constants & Data Types

    Using a constant
        print(“Company name: “ . COMPANY . NL);
    Data types
        Integers, doubles and strings
            isValid = true;   // Boolean
            25                     // Integer
            3.14                  // Double
            ‘Four’                // String
            “Total value”     // Another string
Constants & Data Types

    Data types
        Strings and type conversion
              $street = 123;
              $street = $street . “ Main Street”;
              $city = ‘Naperville’;
               $state = ‘IL’;
              $address = $street;
              $address = $address . NL . “$city, $state”;
              $number = $address + 1;         // $number equals 124
Introduction to PHP

   Array Processing
Creating an array
    There are more ways to create an array in PHP.

    $colorList = array("red","green","blue","black","white");

    $colorList[]   =   "red";     $colorList[0]   =   "red";
    $colorList[]   =   "green";   $colorList[1]   =   "green";
    $colorList[]   =   "blue";    $colorList[2]   =   "blue";
    $colorList[]   =   "black";   $colorList[3]   =   "black";
    $colorList[]   =   "white";   $colorList[4]   =   "white";
    Display the array content
   If you want only display one element of the array then you can just
    write the following code
    echo $colorList[0];

   You can write a loop and display all the elements like this:
    for ($i=0;$i<=4;$i++){
               echo $colorList[$i];

   use a foreach loop as this:
    foreach ($colorList as $value) {
               echo $value;

   If you want to display array content for debugging purposes then you can
    use 2 built in PHP functions. These are the print_r and var_dump.
    print_r($ colorList);
     Associative arrays
   In general PHP arrays are maps, which means that it is a type that
    maps values to keys.
   Associative array means that you can assign an arbitray key to every
                       $colorList = array("apple"=>"red",

    Array keys are case-sensitive, but type insensitive.
   It means that 'a' differs from 'A' but '1' is the same as 1.

$colorList["apple"]      =   "red";
$colorList["grass"]      =   "green";
$colorList["sky"]        =   "blue";
$colorList["night"]      =   "black";
$colorList["wall"]       =   "white";
    Associative arrays

echo "The sky is ".$colorList["sky"]
    ." and the grass is ".$colorList["grass"];

   You can mix your array and use numbers and strings in
    the same list like this:
$colorList["apple"]   =   "red";
$colorList[5]         =   "green";
$colorList["sky"]     =   "blue";
$colorList["night"]   =   "black";
$colorList[22]        =   "white";

   As you can see even the numbers can be any so you don't
    have to make it continuous. However be aware of using
    such mixed arrays as it can result errors.
 Multidimensional arrays
$myLists['colors'] = array("apple"=>"red",

$myLists['cars'] = array("BMW"=>"M6",
                                  "Mercedes"=>"E 270 CDI",
                                  "Lexus"=>"IS 220d",
 To acces and display an element in the multidimensional array you just
  extend the key list as follows:
  echo $myLists['cars']['Toyota'];
Introduction to PHP

   File Handling
fopen( )
   fopen() has two main input fields. The file and the opening mode.
    Here are the opening modes that you can specify:
     'r' - Open for reading only; place the file pointer at the beginning of
       the file.
     'r+' - Open for reading and writing; place the file pointer at the
       beginning of the file.
     'w' - Open for writing only; place the file pointer at the beginning of
       the file and truncate the file to zero length. If the file does not exist,
       attempt to create it.
     'w+' - Open for reading and writing; place the file pointer at the
       beginning of the file and truncate the file to zero length. If the file
       does not exist, attempt to create it.
     'a' - Open for writing only; place the file pointer at the end of the
       file. If the file does not exist, attempt to create it.
     'a+' - Open for reading and writing; place the file pointer at the end
       of the file. If the file does not exist, attempt to create it.
Sample Code
// This will open the file in read-only mode
$fh = fopen('test.file','r');
// This will open the file in read and write mode
   (not blanking the file)
$fh = fopen('test.file','r+');
// This will open the file in write only mode
   (this will blank the file when opening)
$fh = fopen('test.file','w');
// This will open the file in read and write mode
   (this will blank the file when opening)
$fh = fopen('test.file','w+');
Open and Write to a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or
  die('Cannot open file:
$data = 'This is the data';
fwrite($handle, $data);
Append to a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or
  die('Cannot open file: '.$my_file);
$data = "\n".'New data line 1';
fwrite($handle, $data);
$new_data = "\n".'New data line 2';
fwrite($handle, $new_data);
Read a File

$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data =
print "file contents:";
print $data;
Read Line by Line & Deleting a file

$handle = fopen($my_file, 'r') or die('Cannot open
  file: '.$my_file);

echo "<br> reading line by line..<br>";

while (!feof($handle)){
  $line = trim(fgets($handle));
  echo "line content: $line"."<br>";


Introduction to PHP

   Form Processing
Example Form

<form action="action.php" method="post">
 Your name: <input type="text"
  name="name" />
 Your age: <input type="text" name="age"
 <input type="submit" />
Form Processing

<?php echo $_POST['name']; ?>.
  You are <?php echo $_POST['age']; ?>
years old.

   To get the values of those input items at PHP code,
    we can use $_POST['InputName'] syntax. It will
    return the value entered by user to that particular
    input field as String.
   Modify $-POST into $_GET and see the difference in
    the url.

Shared By: