COMP 484 - Ch.19 PHP

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

Method 1 for creating and iniIalizing an array:

$first[ 0 ] = "zero"; $first[ 1 ] = "one"; $first[ 2 ] = "two"; $first[] = "three";

How to use $_POST to extract all key, value pairs?

. var_dump($_POST).

PHP script file names end with

.php

#matches Now as a word or a part of a word only at the end of a line

/Now$/

# Matches Now as a word or a part of a word anywhere in the text

/Now/

# case-insensitive matching for any word with a length of at least 2 that ends in ow

/\b([a-zA-Z]*ow)\b/i

# case-insensitive matching for any word with a length of at least 2 that starts with t following one or more alphabetic characters.

/\b(t[[:alpha:]]+)\b/i

# case-sensitive matching for any word with a length of at least 1 that starts with the letter and follows any number of letters a,b,c,d

/\b(t[a-d]*)\b/

When using form validation with REGEX what indicates the start and end of the string?

/^ and $/

#matches Now as a word or a part of a word only at the beginning of a line

/^Now/

Rules for PHP variables

1. A variable starts with $ sign, followed by the name of the variable. 2. A variable name must start with a letter or underscore character. 3. A variable cannot start with a number. 4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0- 9, and _ ). 5. Variable names are case-sensitive ($age and $AGE are two different variables).

What can PHP do?

1. Generate dynamic page content 2. Create, open, read, write, delete, and close files on the server 3. Collect form data 4. Send and receive cookies 5. Add, delete, modify data in your database 6. Control user-access 7. Encrypt Data 8. Output HTML, images, PDF files, Flash movies, and any text, such as XHTML, and XML.

Example of key cast in associative array

<?php $array1 = array( 1 => "a", "1" => "b", 1.5 => "c", true => "d", ); var_dump($array1); ?> The above example will output: array(1) { [1]=> string(1) "d" }

What are super global arrays? (Sec. 19.8)

Are associative arrays pre defined by PHP that hold variables acquired from user input, the environment or the web server and are accessed in any variable scope. Fig. 19.12 has a full list of them.

What are bracketed expressions used for in Regex?

Are lists of characters enclosed in square brackets ( [ ] ) that match any single character from the list. Ex. [a-zA-Z]

PHP Arrays

Array names, begin with $ symbol. If a value is assigned to an array element of an array that does not exist, then the array is created. Assigning a value to an element where the index is omitted appends the element to the end of the array.

Associative arrays

Arrays with nonnumeric indices Create an associative array using the operator =>, where the value to the left of the operator is the array index and the value to the right is the element's value. Ex. $fourth = array( "January" => "first", "February" => "second", "March" => "third", "April" => "fourth", "May" => "fifth", "June" => "sixth", "July" => "seventh", "August" => "eighth", "September" => "ninth", "October" => "tenth", "November" => "eleventh","December" => "twelfth" ); As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

How are function arguments passed by default in PHP?

By default they are passed by value. To pass by reference: prepend an ampersand (&) to the argument name in the function definition. Ex. <?php function foo(&$var) { $var++; } $a=5; foo($a); print($a) // $a is 6 here ?>

PHP Interpretation can be run as...

CGI or Server Module

CGI

Common Gateway Interface Scripts executed by the operating system and the results were served back by the web server. Standard way for server to delegate content-generation to executable file(s). CGI defines a common way for webserver software to interface with scripts.

What are POSIX character classes enclosed in?

Delimiters [: and :]

Casting or type casting

Does not change a variable's content. It creates a temporary copy of a variable's value in memory. Ex. (double) $data; (integer) $data; Casting the original variable keeps its original type.

All operations requiring PHP interpolation...

Execute on the server before the HTML5 document is sent to the client.

(Sec. 19.9) Reading from a database How do we connect to a MySQL database?

FuncIon mysql_connect connects to the MySQL database. It takes three arguments— § the server's hostname § a username § a password § returns a database handle—a representaIon of PHP's connecIon to the database, or false if the connecIon fails. § $database = mysql_connect( "localhost", "iw3htp", "password" )

Method 2 for creating and initializing an array:

Function Array

What are the functions that arrays have to work with pointers? What is passed to these functions as an argument?

Function reset, Function key, and Function next. The name of the array is passed to those functions as an argument.

Function preg_match

In PHP uses regular expressions to search for a specified pattern using Perl-compatible regular expressions (PCRE) If a pattern is found, preg_match returns the length of the matched string - which evaluates to true in a boolean context. Only returns the first instance of match it encounters. Takes two arguments: a regular-expression pattern to search for and the string to search. Has an optional third argument (array), if the third argument is provided, then it is filled with the results of search. Ex. preg_match( "/\b(t[[:alpha:]]+)\b/i", $search, $match) $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

Undefined values

In a numeric context, it evaluates to 0. In a string context it evaluates to the string "undef"

PHP Code

Is embedded directly into text-based documents, such as HTML, through these scripts segments are interpreted by a server before delivering to the client. Are executed on the server, and the result is returned to the browser as plain HTML Code is inserted between the scripting delimiters "<?php" and "?>". Can be placed anywhere in HTML5 markup, as long as the code is enclosed in these delimiters.

What happens when an expression such as [:alpha:] is placed in another set of brackets? Where it looks like this: [ [:alpha:] ]

It becomes a regular expression matching all of the characters in the class.

What does the \b before and after the parentheses indicate?

It indicates the beginning and end of a word we are trying to match.

Server Module

Modern web servers can directly execute PHP either by the web server itself or via extension modules to the webserver. Example, mod_php: PHP, as an Apache module. Interprets Apache PHP files for the Apache server. PHP interpreter becomes part of server executable.

What happens when a variable is encountered inside a double-quoted ("") string?

PHP interpolates the variable. In other words, PHP inserts the variable's value where the variable name appears in the string.

How can ranges be specified in Regex?

Ranges can be specified by supplying the beginning and the end of the range seperated by a dash (-). ex. [a-z]

Function preg_replace

Replaces a string with another string. Ex. preg_replace( "/" . $match[ 1 ] . "/", "", $search ); preg_replace takes 3 arguments § the pattern to match § string to replace matched string § string to search § returns modified string

How would you check if the required form input fields have values?

Request Method is accessible as $_SERVER["REQUEST_METHOD"] Checking if required form input fields have values: if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { //show error message and ... }

Comments in PHP

Single-line comments which begin with two forward slashes (//) or a pound sign (#). - Text to the right of the delimiter is ignored by the interpreter. Multiline comments begin with delimiter /* and end with */ Ex. <?php $testString = "3.5 seconds"; //comment here $testDouble = 79.2; # comment here /*comment Here */ $testInteger = 12; ?>

What kind of data should always be validated on the server side?

Some data, such as passwords.

What other key casts will occur?

Strings containing valid integers will be cast to the integer type. "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer. Floats are also cast as integers. The fractional part is truncated. Ex. 8.7 will be 8. Bools are cast as integers to. True = 1, false = 0. Null will be cast to the empty string. Ex. The key null will actually be stored under "". Arrays and objects can not be used as keys. Doing so will result in a warning: illegal offset type. If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

In associate arrays the key can either be...

The key can either be an integer or a string. The value can be of any type.

Meta character that matches any single character?

The period (.)

What does a bracketed expression containing two or more adjacent character classes in the class delimiter represent?

Those character classes are combined. For example, the expression [ [:upper:] [:lower:] ]* represents all strings upper and lowercase letters in any order. While [[:upper:]] [[:lower:]] * matches strings with a single uppercase letter followed by any number of lowercase characters. Another example: The expression ( [[:upper:]] [[:lower:]] )* represents all strings that alternate between uppercase and lowercase characters (starting with uppercase and ending with lowercase)

True or false? $_POST has all the form input elements values by the input element's name ahribute in the data collecIng html markup.

True

True or false? Anything enclosed in single quotes in a print statement is not interpolated, unless the single quotes are nested in a double-quored string literal.

True

True or false? Each array has a built in internal pointers, which points to the array element currently being referenced.

True

PHP statements terminate with...

a semicolon (;)

Regular Expressions (Regex)

a series of characters that server as pattern-matching templates (or search criteria) in strings, text files, and databases.

PHP Variables

are preceded by a $ and are created the first time they're encountered. Are loosely typed - they can contain different types of data at different times. Are typed based on the values assigned to them. Ex. $testString = "3.5 seconds" // string type

Type conversions

can be performed using settype

Meta character in Regex that matches the beginning of the string?

carot (^) Ex. if( preg_match("/^Now/", $search) ) print("<p>'Now' found at beginning of the line.</p>");

In PHP, all keywords (e.g. if, else, while, echo, etc.) classes, functions, and user -defined functions are....

case-insensitive

Function preg_match performs what type of pattern matches by default?

case-sensitive. To Perform case-insensitive pattern matches you simply place the letter i after the regular expression pattern's closing delimiter, as in "/\b([a-z-A-Z]*ow)\b/i" The delimiter is: /

mysql_error

closes the connection to the database specified in its argument Ex. mysql_close($database)

Concatenation operator (.)

combines multiple strings. Ex. A print statement split over multiple lines prints all the data that is enclosed in its parenthesis. § print( "<p>$testString is a(n) " . geUype( $testString ). "</p>" ); § print( "<p class = 'space'>Using type casZng instead:</p> <p>as a double: " . (double) $data . "</p>" . "<p>as an integer: " . (integer) $data . "</p>" );

Function strcmp

compares two strings. Returns -1 if the string alphabetically precedes the second string Ex. strcmp("apple", "banana"); Returns 0 if the strings are equal Ex. strcmp("banana", "banana"); Returns 1 if the string alphabetically follows the second. Ex. strcmp("orange", "banana");

Function define

creates a named constant. It takes two arguments - the name and value of the constant. Ex. define("VALUE", 5); $a = $a + VALUE; An optional third argument accepts a Boolean value that specifies whether the constant is case insensitive - constants are case sensitive by default. Ex. define("GREETING", "Hello you.", true); echo GREETING; // outputs "Hello you." echo Greeting; // outputs "Hello you."

Function array

creates an array that contains the arguments passed to it. The first item in the argument list is stored as the first array element (index 0), the second item is stored as the second array element and so on. Ex. $second = array( "zero", "one", "two", "three" );

Meta character in Regex that matches the end of the string?

dollar sign "$" Ex. // search for 'Now' at the end of the string. if ( !preg_match ( " /Now$/", $search ) ) print( <p> 'Now' was not found at the end of the line. </p> " );

How to use $_POST to extract a specific element's value?

echo $_POST["name"];

What does the carot (^) character do in a set (inside [ ] )?

excludes characters from matching (i.e match not) Ex. /[^abc]/ #matches any single character except a,b,c See figure 19.11 for a full list of character classes.

What is the easiest and safest way to check whether an email address is well-formed?

filter_var() function Ex. if ( !filter_var( $_POST["email"] , FILTER_VALIDATE_EMAIL ) ) {//some error handling code }

PHP parser

finds <?php and ?> tags in the file. Starts and stops PHP interpreter to interpret inter-tag code. Everything else is ignored by PHP parser. Lets you jump in and out of PHP-mode in HTML files.

How to use $_POST to extract all indices?

foreach($_POST as $element => $value)

What do PHP functions look like?

function functionName() { // code to be executed } Ex. <?php function printName($name) { echo "<p>Name is $name.</p>"; } printName("Mary"); printName("John"); ?>

PHP or PHP:Hypertext Preprocessor

has become the most popular server-side scripting language for creating dynamic web pages. Is open source and platform independent. Implementations exist for all major UNIX, Linux, Mac, and Windows Operating Systems. Supports a large number of databases.

var_dump(...) function

is used to print complex variables (like arrays and objects) Arrays and objects are dumped recursively with values indented to show structure.

PHP Variables Scope can be...

local: within a function global: outside a function static: defined using static keyword inside a function. It will not be deleted after the function instance closes.

Difference between == and === comparision operators

loosely == equal operators. $a == $b is TRUE if $a is equal to $b after type juggling. Strict === identical operator $a === $b TRUE if $a is equal to $b, and they are of the same type. REMEMBER: !== is the not identical.

Function end

moves the internal pointer to the last element.

Function prev

moves the internal pointer to the previous element

Function next

moves the internal pointers to the next element

echo and print

often used to output data on screen. Parenthesis are optional: echo or echo(), print or print()

Text manipulation is usually done with...

regular expressions

mysql_fetch_row

returns an array containing the values for each column in the current row of the query result ($result). Ex. $row = mysql_fetch_row($result)

gettype

returns the current type of its argument. Ex. gettype($testString)

Function key

returns the index of the element currently referenced by the internal pointer

Function count

returns the total number of elements in the array. Ex. count ($first);

FuncIon mysql_select_db

selects and opens the database to be queried. Returns true on success or false on failure. Ex. mysql_select_db("products",$database)

Function reset

sets the internal pointer to the first array element

foreach statement

starts with the array to iterate through., followed by the keyword as, followed by two variables. The first variable is assigned the index of the current element. The second variable is assigned the value of that element. foreach ( $fourth as $element => $value ) print( "<p>$element is the $value month</p>" ); Does not assume that the array has consecutive integer indices that start at 0. If there's only one variable listed after as, it's assigned to the value of the array element.

settype

takes two arguments - a variable whose type is to be changed and the variable's new type. Cam result in loss of data. Ex. doubles are truncated when they are converted to integers. settype($testString, "double") When converting a string to a number, PHP uses the value of the number that appears at the beginning of the string. If no number appears at the beginning, the string evaluates to 0.

Function die in PHP

terminates script execution. The function's optional argument is a string, which is printed as the script exits.

PHP files can contain

text, HTML, CSS, JavaScript, and PHP code

What are quantifiers used for in regular expressions?

to denote how often a particular character or set of characters can appear in a match. See Fig. 19.10 for the full list of them.

mysql_query

to query the database, sepcifying the query string and the database (database handle) to query as arguments. This returns a resource containing the result of the query, or false if the query fails. Ex. $query = "SELECT * FROM books"; $result = mysql_query( $query, $database ) ;


Set pelajaran terkait

Drugs to Manage Cholesterol & Triglycerides

View Set

Niels Bohr Atomic Model Activity

View Set

IT Essentials (ITE v7.0) Chapter 6

View Set

Principles Of Accounting Chapter 4

View Set

Тема 2. Команда, продукт, розробка

View Set

Domain 5: Protection of Information Assets

View Set

Data Structures Final Exam Study Guide

View Set