php exam2

  • PHP:

    • Hypertext Preprocessor (PHP)

    • PHP is a widely-used, open source scripting language

    • PHP files can contain text, HTML, CSS, JavaScript, and PHP code

    • PHP files are executed on the server and the result is returned to the browser as plain HTML

    • PHP files have an extension of “.php”

      • Using PHP code

        • <?php // php code goes here ?>

  • Comments

    • // single line or # single line

    • /* multi-line */

  • Basic PHP Syntax rules

    • PHP statements end with a semi-colon.

    • The echo command is used for output.

      • Note: there is also a print command which differs slightly, but echo is more commonly/widely used.

    • String values are indicated within quotes (double or single).

    • Keywords (if, else, while, etc), classes, functions are NOT case sensitive.

  • Variables

    • Variable names:

      • Start with a $

      • The second character can be a-z, A-Z, or _

      • Can only contain a-z, A-Z, 0-9, or _

      • Cannot contain spaces

      • Are case sensitive

    • PHP is loosely typed. You do not need to declare a variable type, but type declarations were added beginning with PHP 7, so you can specify a type if you desire.

  • Operators

    • PHP uses the same operators as Java with a few variations/additions.

      • == is the comparison operator, but it will work with values of different types

      • === compares value and type

    • New Logical Operators

      • and (lower precedence than &&)

      • or (lower precedence than ||)

      • xor (returns true if one of operands is true but not both)

    • String Operators

      • . concatenates two Strings

      • .= appends two Strings

        • EXAMPLE

          • $msg1 = "Hello ";

          • $msg2 = "World";

          • echo "<p>";

          • echo $msg1 . $msg2;

          • echo "</p>";

            • output

              • hello world

          • $msg2 .= $msg1;

          • echo "<p>$msg2</p>";

            • output

              • worldhello

    • Conditionals

      • if

      • if else

      • if elseif

      • switch

        • uses cases and default:

    • Loops

      • while

      • do while

      • for

    • Functions

      • function functionName ( ) { }

  • Variable Scope

    • There are 3 different scopes for variables:

      • Local

        • created within a function and accessible only within the function

      • Global

        • created outside a function and directly accessible only outside a function; accessed within a function using the “global” keyword; global variables are also stored in an array called $GLOBALS[index] where index is the name of the global variable. Superglobals are predefined variables that are always accessible in PHP. $GLOBALS is an example of a superglobal. We will see other examples as we proceed.

      • Static

        • used within a function but maintain their values from one function call to another

  • Arrays

    • PHP supports 3 types of arrays:

      • Indexed arrays (what we are used to) which are created using:

        • $colors = array(“red”, “yellow”, “blue”, “green”);

        • Or

        • $colors = array();

        • $colors[0] = “red”;

        • $colors[1] = “yellow”;

        • $colors[2] = “blue”;

        • $colors[3] = “green”;

      • The count() function returns the length of an array

        • $arrlength = count($colors);

      • Associative arrays which use named keys instead of indexes

        • $favoriteColors = array(“Kristin” => “green”, “Hannah” => “pink”, “Holly” => “purple”);

        • Or

        • $favoriteColors = array();

        • favoriteColors[“Kristin”] = “green”;

        • favoriteColors[“Hannah”] = “pink”;

        • favoriteColors[“Holly”] = “purple”;

      • Multi-dimensional arrays which are arrays that contain arrays

  • The foreach loop

    • The foreach loop is a special loop used to process arrays in PHP:

      • foreach ($array as $value){ // code to be executed}

  • Array Operators

    • + union of 2 arrays (this only works with associative arrays)

    • == equality (have same key/value pairs)

    • === identity (have same key/value pairs in same order and same type

    • != inequality

    • <> inequality

    • !== non-identity (returns true if not identical)

  • Array Functions

    • is_array – returns true if the parameter is an array, false otherwise

    • count – returns the number of elements in the array

    • sort($colors) - sorts in ascending order

    • rsort($colors) – sorts in reverse order

    • asort – sorts associative arrays in ascending order according to value

    • ksort – sorts associate arrays in ascending order according to key

    • arsort – reverse sort of associative array in descending order

    • krsort – reverse sort of associative array in descending order

  • SuperGlobals

    • There are several predefined variables in PHP that are always accessible:

    • $GLOBALS – stores all global variables; variables are accessed using $GLOBALS[index] where index is the variable name

    • $_POST – used to collect form data after submitting an HTML form with method=”post”

    • $_GET – used to collect form data after submitting an HTML form with method=”get”

  • Forms and PHP

    • Action and method attributes on the form tag can be used to indicate what PHP file is executed when the form is submitted and how the data is sent to the form.

    • Specify the name of the PHP file to be executed as the value for the “action” attribute. Specify either “post” or “get” for the method. When you use post/get you can access the values from the form in the

      • superglobals $_POST and $_GET.

  • POST vs. GET

    • GET can be used for sending non-sensitive data. Because it sends information as URL parameters they are visible to everyone. GET also has a limit of length of about 2000 characters. Because of security issues, GET should NEVER be used to send sensitive information such as passwords.

    • POST uses the HTTP POST method to send information. The information is not displayed and there is no limit on the length. However, it can cause difficulties when bookmarking the page b/c it does not include required info for the page in the url.

  • A Security Consideration

    • Cross site scripting (XSS)

      • type of attack in which malicious scripts are injected into otherwise trusted websites. They occur when an attacker uses a web application to send malicious code, generally in the form of a browser side script, to an unsuspecting user.

    • One technique used to guard against XSS attacks is escaping any input from a form before it is used as output. PHP provides a special function called

      • htmlspecialchars() that will escape the value. Escaping refers to changing the special characters (< > & “ ‘) in a string to HTML entities.

        • (&lt; &gt; &amp; &quot; &#039;)

        • You should escape any values that have been input using a form before you display then on a webpage.

  • PHP Date and Time

    • The PHP date() function is used to format a date and/or a time.

      • date(format, timestamp)

    • Format uses the following

      • d – day of the month (01-31)

      • j – day of the month w/o leading zeros

      • m – month (01 to 12)

      • n – month w/o leading zeros

      • M – 3 letter textual representation of the month

      • y – year in 2 digits

      • Y – year in 4 digits

      • l – day of the week

      • D – 3 letter textual representation of the day of the week

      • H – 24-hour format of an hour w/ leading zeros (00 to 23)

      • G – 24-hour format of an hour w/leading zeros (0 to 23)

      • h – 12-hour format of an hour with leading zeros (01 to 12)

      • g – 12-hour format of an hour w/o leading zeros

      • i – minutes with leading zeros (00 to 59)

      • s – seconds with leading zeros (00 to 59)

      • a – am/pm

      • A – AM/PM

      • You can also include characters in the format.

        • For example date(‘m/d/y’) would give you 10/24/23.

    • Timestamp is optional. If timestamp is not used then the current date is used by default.

      • Use the mktime function to create a timestamp based on a specific date.

        • mktime(hour, minute, second, month, day, year)

          • For example date(‘m.d.y’, mktime(12, 31, 2023) ) would give you 12.31.23

  • Include and Require Statements in PHP

    • You can insert the contents of a PHP file into another PHP file before the server executes it

      using the include or require statements. This can be helpful if you want consistent content

      across multiple pages.

    • The difference between include and require is that if there is a problem the:

      • include function will continue executing the script;

      • the require function will halt execution of the script.

robot