Metropolitan State University

ICS 325

Internet Application Development

 

Class Notes – Chapter 1 – PHP Crash Course

 

What is PHP?

PHP is a server side scripting language, written specifically for the Web

PHP was developed in 1994 by Rasmus Lerdorf

PHP originally stood for Personal Home Page

PHP currently stands for PHP Hypertext Preprocessor

Current version of PHP is 4.3.6

Version 5 is available for early adopters

Home page = http://www.php.net

PHP strengths include: High performance, Interfacing with Different DBMS (uses ODBC), Libraries, Low Cost, Portability, open source, and thousands of functions.

Web server must have PHP installed.

PHP scripts are interpreted and executed on the server.

Output from a PHP script looks like plain old HTML.  The client cannot see your PHP code, only its output.

 

PHP Tags –

Short Style     <? echo ”<p>Short Style</p>”; ?>

XML Style      <?php print(“<p>XML Style</p>”); ?>

Script Style    <script language=’php’>printf(“<p>Script Style</p>”);</script>

ASP Style      <% echo “<p>ASP Style</p>”; %>

 

PHP Comments –

C  Style           /*          this is a multi line comment              */

C++ Style       //          this is a single line comment

PERL Style    #          this is a single line comment

 

Most PHP code statements must end with a  ; (semi-colon)

          Conditionals and loops are an exception to the rule

Variables:

All variables in PHP begin with $ (dollar sign)

All variables are created the first time they are assigned a value.

PHP does not require you to declare variables before using them.

PHP variables are multi-type (may contain different data types at different times)

Variables from a form are the name of the attribute from the submitting form.

Can have any length, may consist of letters, numbers, underscores, and $

Cannot start with a digit

Are case sensitive

Can have the same name as built-in functions, but avoid doing so.

 

PHP’s data types:

                        Integer            (whole numbers)

                        Float               (real numbers)

                        String              (text enclosed in single or double quotes)

                        Boolean          (true or false)

                        Object             (instance of a class)

                        Array               (group of values, usually of the same type)

                        Resource       (external data source i.e. database record)

                        Null                  (null – for undeclared, uninitialized variables or those set to NULL)

Integers:

Integers can be specified in decimal notation, optionally preceded by a sign (- or +).

octal (8-based) notation is preceded with a 0, optionally preceded by a sign (- or +).

hexadecimal notation precedes the number with 0x.

$a = 1234;     # decimal number
$a = -123;      # a negative number
$a = 0123;     # octal number (equivalent to 83 decimal)
$a = 0x1A;     # hexadecimal number (equivalent to 26 decimal)

 

Floats: (a.k.a. doubles, real numbers):

Floating point numbers can be specified using any of the following syntaxes:

$a = 1.234;

$a = 1.2e3;

$a = 7E-10;

The size of a float is platform-dependent, although a maximum of ~1.8e308 with a

precision of roughly 14 decimal digits is a common value (that's 64 bit IEEE format).

 

Strings:

Strings are placed between quotes ( ‘ ) or double quotes ( “ ).

The string concatenation operator is a dot (.)

The escape character is a back slash(\)

A string can be specified in three different ways:

 

1. Single quotes

<?php

echo 'this is a simple string <br />'; // this is a simple string

echo 'I\'ll be back <br />';                              // output: ... I'll be back

echo ‘delete C:\\*.*?<br />';                          // output: ... delete C:\*.*?

echo ‘You entered $value’;                           // You entered $value

?>

Note: Variables will not be evaluated when they occur in single quoted strings.         

 

2. Double quotes:

If the string is enclosed in double-quotes ("), PHP understands more escape sequences for special characters:

\n         new line

\r          carriage return

\t          horizontal tab

\\          backslash

\$         dollar sign

\”          double quote

 

3. Heredoc syntax:

Heredoc text behaves just like a double-quoted string except the string can span across multiple consecutive lines, without the double-quotes.

 

<?php        //string using heredoc “<<< “  EOD can be any identifier

   $str = <<<EOD      

   Example of string  spanning multiple lines

   using heredoc syntax. 

   EOD;          

   print(“$str”);

?>

Note: No comments can go within the heredoc statement or they become part of it

 

Boolean:

To specify a Boolean you can use the keywords true or false:

$formOK = true;

Other PHP variables will return Boolean values:

The integer 0, the float 0.0, the string “0”, the empty string, an array w/zero elements, an object w/zero elements, and NULL,  all evaluate to FALSE.

 

Every other value is considered TRUE.

$x = -1;

if($x)   //evaluates to true.

 

Object:

An instance of a class, use the new keyword to instantiate a class object.

class Test       {

            function doTest( )      {

print (“doing the test”);  

}

}

$myTest = new Test( );

$myTest->doTest( );         //the object->method syntax

 

Arrays:

an ordered map. You can map values using key, value pairs or numbered indices. Arrays in PHP can be used as hashes, vectors, stacks, queues, etc.

$arr = array(“fruit”=>”apple”, “vegetable”=>”potato”);    //key-value indices

$arr = array(“apples”, “oranges”, “bananas”);                    //number indices

 

Null: Any variable that has no value or has been assigned the constant NULL:

$x ;

print ("x is ".getType($x));           //outputs: x is NULL

 

Embedding PHP in HTML:

PHP may be embedded directly into HTML and is inserted between scripting delimiters:

<?php and ?> PHP tags allow the programmer to “escape” from HTML.

<?=  and ?> PHP tags allow the programmer to insert PHP values into html

With PHP, all statements end with a semicolon (;)

PHP code is never visible to the client; instead, the PHP interpreter outputs the scripts statements. (print, echo)

 

<html>….

<?php

$name = “Bob”;

?> ….

  <td>Hello, <?=$name ?></td>

 

or

 

<?php

echo “<html>”;

           

$name = “Bob”;

echo “<td>Hello $name</td>”;

…?>

 

 

PHP’s Predefined Variables:

$PHP_SELF                                                 the filename of the current script.  <form action=”<? $PHP_SELF ?>” method = “post”>

$DOCUMENT_ROOT                                 the root directory under which the current script is executing, defined by server configuration. This is usually the root folder of the server. /usr/local/httpd/htdocs

Note : this is not available for this class.

$HTTP_USER_AGENT                             contains the user’s browser & os information, i.e. Mozilla/4.0 (compatible; MSIE 6.0;

Windows NT 5.0)

$HTTP_POST_VARS or $_POST           Associative array of form variables passed using http post method.

$HTTP_GET_VARS or $_GET                 Associative array of form variables passed using http get method.

 

Accessing Form variables:

PHP is configured on our server with register_globals=on . This means we have immediate access to our form variables once they are submitted. When this directive is set to “off”, you must use one of the predefined variables: $HTTP_POST_VARS, $HTTP_GET_VARS etc.

 … <form action=”” method=post>

        <input type=”text” name=”myText”>

… </form>

 

To access the text field use

$Name = $myText

Note: If globals were off, the way to access these variables would be:

$Name = $HTTP_POST_VARS[“myText”];          // or $_POST[“myText”]

 

Note: Currently PHP does not recognize html attribute “id”, so

<input type=”text” id=”firstName” />    will result in variable firstName not being submitted.

 

 

Type Casting

          Because PHP is a weakly typed language we can use type casting to ensure correct data in a variable.

            Type casting sets the data type for a variable

            PHP automatically assumes the correct data type

            $money = 0;

            $correctMoney = (double)$money;

         

Constants

          Constants are variables that can also store any value, but cannot be reset.

            Once a constant is set in a script it cannot be modified.

                        define(“SCHOOL”, “Metropolitan State University”);

            Do NOT use the $ (dollar sign) while referring to a constant.

                        echo SCHOOL;

                  

Variable Scope:

Global: declared inside the script, visible throughout the script but not inside functions.

Local: variables declared or used within functions.

 

Operators:

            Mathematic Operators      +, -, *, /, and %           (See Table 1.1 for other examples)

                        $value1 = 10;

                        $value2 = 8;

                        $remainder = $value1 % $value2;

 

                        echo $remainder //    value of 2 is display on screen

If you apply arithmetic operators to strings, PHP will look for and convert any digits at the start of the string.  If there are no digits, PHP will use 0.

            String Operators

            The only string operator in PHP is the concatenation operator

            The concatenation operator is denoted by a . (dot).

                        $value1 = “This class is located at: “;

                        $value2 = “St. Paul Campus”;

                        $stringValue = $value1 . $value2;

 

                        echo $stringValue     // This class is located at: St. Paul Campus  - is display on screen

           

Assignment Operators

            PHP has a few different assignment operators

            The standard assignment operator =

            Combination assignment operators           +=, -=, *=, /=, %=, and .=  (See Table1.2 for other examples)

            The Pre and Post Increment and Decrement operators   -- ++

 

The combination assignment operators are shorthand notation for performing an operation and assigning the value to the current variable.          

$value *= 2;

this statement is equivalent to the following

$value1 = $value1 * 2;

 

The Pre and Post Increment and Decrement operators increment or decrement the current value by one.

                        The value is changed before an operation happens with the Pre Increment and Decrement operators

                        The value is changed after an operation happens with the Post Increment and Decrement operators

                                    $value = 5;

                                    echo ++$value;          //          Pre Increment – output would be 6 – current value = 6

                                    echo $value--;            //          Post Increment – output would be 6 – current value = 5

            Comparison Operators                 ==, ===, !=, <>, <, >, <=,  and >=                 See Table 1.3 for other examples

                        Remember     Comparison   == 

Assignment    =

                        if ($value1 == $value2){…

                       

            Logical Operators                          !, &&, ||, and, and or                                        See table 1.4 for other examples

                        if ($value1 == $value2) || ($value1 == $value3){…

                        &&  and (and) provide the same service, except (and) has a lower order of precedence

                        ||  and (or) provide the same service, except (or) has a lower order of precedence

 

            See Table 1.6 for order of precedence

Values are passed by copy in PHP. Use the reference operator ( & ) to pass values by reference:

 

Ternary operator: condition? value if true: value if false;

$c= ($a==5? true: false);      //this operator does not nest as in Java

 

            Error Suppressor Operator                     @

                        The error suppressor operator can be used in front of any expression that could potentially contain an error.

                        The Error Suppressor suppresses errors.

                                    $value = @(21/0);

                        NOTE: If you suppress your errors, you should write other code to handle the errors.

 

            Variable Status Checking

                        PHP has built in functions for checking the status of variables

                        isset                returns true if the variable has been created, false otherwise

unset               deletes the variable

empty              checks to see if the variable is empty if so returns true

            Conditional Statements

                        PHP supports all control structures available in common programming languages

                        One of the most common is the if statement

                        If statement has three different forms in PHP

                        Form1 - Single Statement                if (logical expression) statement;

                        Form2 - Multiple Statements            if (logical expression) {

statement1;

statement2;

                                                                                    }

                        Form3 – Multiple Statements          if (logical expression):

statement1;

statement2;

                                                                                    endif;

           

            Else and else if follow the same format as the if statements

                        if (logical expression) {

statement1;

statement2;

                                    }

                                    elseif (logical expression){

statement1;

statement2;

                                    }          

                                    else{

statement1;

statement2;

                                    }

                        The Switch Statement is a handy tool for replacing multiple else-ifs

                                    switch (expression){

                                                case expression1:

                                                            statement;

                                                            break;

                                                case expression2:

                                                            statement;

                                                default:

                                                            statement;

                                    }                                  

 

                        NOTE: the break statement can also be used to exit out of loops and scripts

 

            Iteration

                        PHP support three of the most common looping structure: for, while, and do…while.

                        While Loops              Check condition, execute statements, and then loop

                                    While(logical expression)

                                                Statements;

                        For Loops                  Loop a set number of times executing statements each time

                                    For (expression1; comparison; expression2)

                                                Statements;

                        Do…While Loops     execute statements, check condition, and then loop

                                    Do

                                                Statements;

                                    While (logical expression)

 

NOTE: Code readability.  Indent your code.  Use comments.  Describe functions and web pages.