Command line interpreter: php
not interactive
must enclose executable statements in
--one exception is if you want to interpolate a variable's value
into the web page. Then you can write:
=$varname?>
Note the '=' sign in front of the variable name
if you run on the UTK system, use web.eecs.utk.edu and it will
report syntax errors
Variables
Do not have to be declared
Start with $
Strings: $vars inside double quotes are interpolated while they
are literal inside single quotes
e.g. $a = 20
"$a" = "20"
'$a' = '$a'
Put curly braces around vars to indicate where they begin and end
e.g.; "{$a}lbs" = "20lbs"
Concatenation operator is .
casts ints and doubles to strings
String comparison is same as numeric comparison: ==, !=, <, >, etc.
Useful functions
strip_tags($string): strips all html and php tags from the string
a) this function is useful for "disinfecting" a string since a
hacker might try to insert malicious code using php tags
substr($str, position, length)
position starts at 0
if position is negative then substr counts from the end of the
string
if length is omitted then you get the rest of the string starting
from position
strlen($str): returns the length of the string
strpos($str, $substr): returns the position of the first occurrence
of $substr or NULL
trim($string, "charlist"): returns a string with all characters
in charlist stripped from the beginning and end of string. If
"charlist" is omitted, then trim strips whitespace (blankspaces,
tabs, newlines, return characters (\r), and null characters (\0)).
a. ltrim: strips only leftmost characters
b. rtrim: strips only rightmost characters
c. unlike chomp, trim does not do inplace editing of the string.
You must write:
$line = trim($line);
$array = explode(char, $string): returns an array that splits the
string based on the delimiter character. It will not collapse
white space. For example:
$array = explode(" ", "a b") returns the array ("a", "", "b")
$array = preg_split("/perl_pattern/", $string): returns an array that
splits the string based on the given perl pattern
$array = preg_split("/\s+/", a b") returns ("a", "b")
explode is faster if you have a simple delimiter
Data Types
boolean: TRUE/FALSE or true/false
null (case insensitive, so Null and NULL work equally well): A variable
is considered to be null if:
1) it has been assigned the value null
2) it is undefined
gettype($var): returns the type of the variable
legitimate types:
integer
boolean
double
string
array
e.g., $a = 6.2;
if (gettype($a) == double) ...
settype($var, "type"): coerces value of $var to that type
a) Example:
$a = "10";
settype($a, "integer"); // $a = 10
b) returns true on success and false on failure. For example, if
$a were "brad" in the above example, settype would return
false
c) I can also cast variables to new types using C-style casting.
For example:
$a = (int)$a;
Casting has the same effect as settype, but you will not know
whether or not the cast succeeded.
d) When either settype or casting fails, the variable will be left
with the failed result. For example, if $a were "brad", then
both settype and casting will assign the value 0 to $a.
Conditionals
2 versions for and/or
and/&&: && has higher precedence than and
or/||: || has higher precedence than or
elseif used instead of "else if" but "else if" works too
switch: works with numbers and strings
use multiple case statements if multiple cases for the same code
use break to avoid executing the next case code
default keyword: executes the default code
Functions
introduced with function keyword
use global keyword to declare a variable global within a function
e.g., function change_value() {
global $value;
$value = $value * 2;
include keyword
include "tax.php"; // includes this file
include_once "tax.php"; // guarantees that the code for tax.php
// is only loaded once
include_once should be placed in front of a file every time it is loaded.
include_once checks to see if the file has already been loaded and, if
so, does nothing. However, suppose you try something like:
include_once "tax.php";
include "tax.php";
In this case tax.php gets reloaded because the second include does not
check whether or not tax.php has already been loaded
useful numeric functions
floor
ceil
max
min
rand(min,max): numbers between min/max inclusive
printf
place ' before padding char for a decimal number
e.g., printf("'05d", $a); // pads with 0's instead of spaces
sprintf fct returns a string: $a = sprintf(...)
file I/O: similar to C for file I/O and similar to Perl for directory
operations (many of these commands will not work on our
servers because they are too dangerous, so do not be surprised
if you try to use one of them and it fails. They will work if
you run the file from the command line, but not from within the
browser.).
a fairly complete list of file commands can be found
at http://www.w3schools.com/PHP/php_ref_filesystem.asp.
$file_handle = fopen(filename, "mode"): opens a file and returns either
a file handle on success or false on failure.
"r": read
"w": write, overwrite existing file
"a": append
"x": write, signal error if file already exists
--The return result of fopen shows the advantage of dynamic typing.
If you query the type of $file_handle using the gettype function,
you will find it is a resource if fopen succeeds
and a boolean (with the value false) if the fopen fails
fclose($file_handle): closes a file
reading input
string fgets($file_handle): returns the next line of input with the
newline character attached or the boolean false if the read
fails.
a) use the trim() function to strip the newline character, as
well as leading and trailing whitespace.
b) fgets(STDIN): reads from stdin
c) there is no gets function: PHP was originally intended for
server-side scripting from a browser, not a command line. Hence
it was not set up to easily access a keyboard (i.e., STDIN).
fscanf($file_handle, format_string, variables)
a) unlike C, fscanf reads an entire line of input and
discards the unused part
b) if there are too few fields provided, then the extra variables
retain their old values
c) fscanf(STDIN, ...): reads from stdin. Like gets, there is no
scanf in php
writing output
fprintf($filehandle, format_string, variables): writes a formatted
string to a file
fputs($filehandle, $string): writes a string to a file
bool feof($file_handle): returns true if eof, otherwise false
--you must attempt to read a line from $file_handle before feof will
return false. Hence the following idiom will attempt to
process one too many lines. In the last iteration, $line
will be set to false because the read has failed:
while (!feof($file_handle)) {
$line = fgets($file_handle);
... process $line ...
}
Instead use a priming read as follows:
$line = fgets($file_handle);
while (!feof($file_handle)) {
... process $line ...
$line = fgets($file_handle);
}
bool rename(string $oldname, string $newname): moves a file from
$oldname to $newname and returns true/false depending on whether
the move succeeds
bool unlink(string $name): deletes a file and returns true/false depending
on whether it succeeds
bool mkdir(string $path, string $permissions): creates a directory in
the specified path.
a. returns true/false depending on whether it succeeds
b. permissions are in UNIX form and should be in
octal format e.g., "0644"
bool chdir(string $path): changes to the indicated directory, returning
true/false depending on whether it succeeds
getcwd(): returns current directory path
arrays
numeric arrays
ways to create
1) $names = array("Peter","Quagmire","Joe");
2) $names[0] = "Peter"; $names[1] = "Quagmire";
3) $names[] = "Peter"; $names[] = "Quagmire";
array[] = value: appends value to the array
associative arrays
ways to create
1) $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34);
2) $ages['Peter'] = "32"; $ages['Quagmire'] = 30;
multi-dimensional arrays
ways to create
1) $families = array("Griffin"=>array("Peter","Lois","Megan"),
"Quagmire"=>array("Glenn","Joe"),
"Seuss"=>array("Mary","Nicole","Sue","Frank"));
access: $families['Griffin'][0];
useful functions
print_r($array): prints the elements of the array in a nice format
count($array): number of elements in the array
array_key_exists(): Checks if the specified key exists in the array
in_array($value, $array): Checks if the designated value is in the array,
regardless of whether it is a numeric array or an associative array
array_push: Inserts one or more elements to the end of an array
e.g., array_push($a, 10, 20, 30);
array_shift(): Removes the first element from an array and returns the
value of the removed element (not the key)
array_unshift: Inserts one or more elements at the front of the array
e.g., $a[0] = 10;
array_unshift($a, 1, 2, 3);
print_r($a);
output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 10
)
asort($array,[sorttype]), arsort($array,[sorttype]): sorts the array
based on element value in ascending/descending value. sorttype is
optional and may be either the constant SORT_NUMERIC or SORT_STRING
ksort($array,[sorttype]), krsort($array,[sorttype]): sorts the array
based on key value in ascending/descending value. sorttype is
optional and may be either the constant SORT_NUMERIC or SORT_STRING
Loops
while, for, and do..while are same as C
foreach($array as $value): assigns each element of a numeric array or
each key of an associative array to $value
foreach($array as $key=>$value): binds each value in an associative array
to its key. The key and value are assigned to $key and $value
Regular Expressions
preg_match("/perl pattern/", $string, $array): returns true if the
given pattern matches any subexpression in the string
--first entry in $array is the full match
--remaining entries contain matches for the parenthesized expressions
Example: preg_match("/\b(\d{1,2})\/\d{1,2}\/(\d{4})\b/", "brad 2/3/1964 42",
$matches);
$matches = (2/3/1964, 2, 1964)
preg_match_all("/perl pattern/", $string, $array): Searches string for all
matches to the given pattern and puts them in $array.
--returns the number of matches found
--first entry in $array is an array of all matches
--remaining entries in $array are arrays containing matches for the
first, second, third, etc. parenthesized expressions.
Example: preg_match_all("/\b(\d{1,2})\/\d{1,2}\/(\d{4})\b/",
"1/3/1964 2/3/1964 9/8/1965 10/28/1930", $matches);
$matches
Array
(
[0] => Array
(
[0] => 1/3/1964
[1] => 2/3/1964
[2] => 9/8/1965
[3] => 10/28/1930
)
[1] => Array
(
[0] => 1
[1] => 2
[2] => 9
[3] => 10
)
[2] => Array
(
[0] => 1964
[1] => 1964
[2] => 1965
[3] => 1930
)
)
preg_replace($pattern, $replacement, $string, $limit): replaces
with $replacement all subexpressions in $string that match $pattern
--if limit is specified then the number of replaced subexpressions
is limited to the value of limit
--$string can be an array of strings in which case all strings in
$string are searched and replaced
--$pattern and $replacement can also be arrays in which case the
pattern at $pattern[i] is replaced with $replacement[i]
Example: $pattern = "/\b(\d{1,2})\/(\d{1,2})\/\d{2}(\d{2})\b/";
$replace = "$1/$2/$3";
$s = preg_replace($pattern, $replace, "brad 2/3/1964 42");
print($s)."\n";
Result: brad 2/3/64 42
--$0 contains the entire matched pattern
--note the lack of delimiters for the replacement pattern
Retrieving Form Data
$_POST and $_GET contain keyword/value pairs for post and get methods
$_REQUEST contains contents of $_GET, $_POST, and $_COOKIE
Functions for Validating Form Data
empty($var): returns true if variable is 0 or an empty string--useful for
checking that text boxes haven't been left blank
isset($var): returns true if variable has a value, including 0 or an empty
string--useful for checking to ensure that the user entered a value for
a form element. Unfortunately, isset will always return true for textboxes.
You need to check whether it works with other form elements. It does
work with radio buttons and checkboxes.
e.g., isset($_POST['age'])
is_numeric($var): returns true if variable is numeric or can be converted
to a number. If the value is a string then the entire string must be
a number for is_numeric to return true. For example, is_numeric('10cubs')
returns false.
CGI stuff
id attribute: The ID attribute is used to explicitly associate the specific
Input tag with a specific LABEL tag. ID attributes are unique within
a page.
--see ~bvz/www-home/cgi-bin/upload.html for an example
label element: Used to provide a label for an input element in the browser
Note the following things about the upload.html file:
1) The enctype attribute of the