320 likes | 569 Views
PHP. Chapter 5. Server-Side Basics. URLs and web servers http :// server / path / file usually when you type a URL in your browser your computer looks up the server's IP address using DNS your browser connects to that IP address and requests the given file
E N D
PHP Chapter 5
Server-Side Basics • URLs and web servers • http://server/path/file • usually when you type a URL in your browser • your computerlooks up the server's IP address using DNS • your browserconnectsto that IP address and requests the given file • the web server software (e.g. Apache) grabs that file from the server's local file system, and sends back its contents to you • some URLs actually specifyprograms that the web server should run, and then send their output back to you as the result: • http://www.cs.aub.edu.lb/hsafa/cmps278/first.php • the above URL tells the server www.cs.aub.edu.lbto run the program first.phpand send back its output
Server-Side Basics • server-side pages are programs written using one of many web programming languages/frameworks • examples: PHP, Java/JSP, Ruby on Rails, ASP.NET, Python, Perl • They are called server-side scripting languages • They allow web developers to write dynamically generated pages quickly • the web server contains software that allows to run those programs and send back their output • each language/framework has its pros and cons • we use PHP for server-side programming in this textbook
What is PHP and Why PHP? • PHP stands for "PHP Hypertext Preprocessor“: a server-side scripting language. • Procedural language that have many similarities to C and perl • authenticate users and process form information • PHP code can be embedded in HTML code • simple: lots of built-in functionality; familiar syntax • free and open sourceand platform independent • implementations exist for all major operating systems. • supported by most popular web servers • anyone can run a PHP-enabled server free of charge • supports a large number of databases and other services such as email, etc. • well-documented: type php.net/functionName in browser Address bar to get docs for any function • http://php.net/print
Lifecycle of a PHP web request (5.1.1) • browser requests a .html file (static content): server just sends that file • browser requests a .php file (dynamic content): server reads it, runs any script code inside it, then sends result across the network • script produces output that becomes the response sent back
Hello, World! • The following contents could go into a file hello.php: PHP <?php print "Hello, world!"; ?> Hello, world! Output • a block or file of PHP code begins with <?phpand ends with ?> • PHP statements, function declarations, etc. appear between these delimiters . • PHP code can be placed anywhere in HTML, as long as the code is enclosed in <?php and ?>. • PHP statements terminate with a semicolon (;). • Forgetting to terminate a statement with a semicolon (;) is a syntax error.
Viewing PHP output • you can't view your .phppage on your local hard drive; you'll either see nothing or see the PHP source code • if you upload the file to a PHP-enabled web server, requesting the .phpfile will run the program and send you back its output
PHP Basic Syntax- Console output: print print "text"; PHP PHP print "Hello, World!\n"; print "Escape \"chars\" are the SAME as in Java!\n"; print "You can have line breaks in a string."; print 'A string can use "single-quotes". It\'s cool!'; Output Hello, World! Escape "chars" are the SAME as in Java! You can have line breaks in a string. A string can use "single-quotes". It's cool! • some PHP programmers use the equivalent echoinstead of print • A print statement splitover multiple lines prints all the data that is enclosed in its parentheses
Syntax errors PHP print Hello, World!\n"; Output Parse error: syntax error. Unexpected ‘,’ in C:\users\author\examples\error.php on line 11 PHP print "Hello, World!; Output Parse error: syntax error. Unexpected $end in C:\users\author\error2.php on line 16
Types • PHP variables are loosely typed; they can contain different types of data at different times • basic types: int, float, boolean, string, array, object, NULL • PHP converts between types automatically: variables are convertedto the type of the value they are assigned • string → intauto-conversion on + ("1" + 1 == 2) • int → float auto-conversion on / (3 / 2 == 1.5)
Types • test what type a variable is with is_type functions, e.g. is_string • gettype function returns a variable's type as a string (not often needed) • Settypefunction can also perform type conversions. • It takestwo arguments, a variable whose type is to be changed and the variable’s new type • Calling function settype can result in loss of data. • doubles are truncated when they are converted to integers • When converting from 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. • Another option for conversion between types is type casting. • Casting does not change a variable’s content, it creates a temporary copy of a variable’s value in memory • (int) "2.1“ = 2; (int) 2.1 = 2
Variables $name = expression; PHP PHP $user_name = "PinkHeartLuvr78"; $age = 16; $drinking_age = $age + 5; $this_class_rocks = TRUE; print "Hello, $user_name"; • Variables are preceded by a $ and are created the first time they are encountered. • Failing to precede a variable name with a $ is a syntax error. • Variable names in PHP are case sensitive. • Variable encountered inside a double-quoted ("") string, are interpolated. • i.e., PHP inserts the variable’s value where the variable name appears in the string. • All operations requiring PHP interpolationexecuteon the server before the HTML document is sent to the client.
Variables & Integers <?php$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)$a = 0b11111111; // binary number (equivalent to 255 decimal)?> PHP • Integers can be specified in decimal (base 10), hexadecimal (base 16), octal (base 8) or binary (base 2) notation, optionally preceded by a sign (- or +). • To use octal notation, precede the number with a 0 (zero). • To use hexadecimal notation precede the number with 0x. • To use binary notation precede the number with 0b.
Arithmetic operators (5.2.4) + - * / % . ++ -- = += -= *= /= %= .= === == != !== && || ! • The concatenation operator (.) combines multiple strings. • == just checks value ("5.0" == 5 is TRUE) • === also checks type ("5" === 5 is FALSE) • many operators auto-convert types: • 5 < "7" is TRUE • 5 + "7" is 12
Comments PHP # single-line comment // single-line comment /* multi-line comment */ • like Java, but # is also allowed • a lot of PHP code uses # comments instead of // • we recommend # and will use it in our examples
PHP syntax template HTML content <?php PHP code ?> HTML content <?php PHP code ?> HTML content ... PHP • any contents of a .phpfile between <?phpand ?> are executed as PHP code • all other contents are output as pure HTML • can switch back and forth between HTML and PHP "modes" 16
Automatically declares a string Automatically declares a double Automatically declares an integer Outputs the type of $testString Modifies $testString to be a double Modifies $testString to be an integer Modifies $testString to be a string
Temporarily casts $data as a double and an integer Concatenation
Constants and variable initialization • Function define creates a named constant. • Assigning a value to a constant after it is declared is a syntax error. • Uninitialized variables have the valueundef, which has different values, depending on its context. • In a numeric context, it evaluates to 0. • In a string context, it evaluates to an empty string (""). • Initialize variables before they are used to avoid subtle errors. • For example, multiplying a number by an uninitialized variable results in 0. • Keywords may not be used as identifiers. <?php $a = 5; $num = $a; print( "The value of variable a is $a <br />" ); define( "VALUE", 5 ); $a = $a + VALUE; print( "Variable a after adding constant VALUE is $a <br />" ); $num= $num + VALUE; print( "Variable num after adding constant VALUE is $num <br/>" ); $str = "3 dollars"; $a += $str; print $a; ?>
for loop (same as Java) PHP for (initialization; condition; update) { statements; } for ($i = 0; $i < 10; $i++) { print "$i squared is " . $i * $i . ".\n"; }
if/else statement PHP if (condition) { statements; } elseif (condition) { statements; } else { statements; } <?php $a = 10; $a *= 2; if ( $a < 51 ) print "Variable a is less than 50"; elseif( $a < 101 ) print "Variable a is between 50 and 100 inclusive"; else print "Variable a larger than 100"; ?> • NOTE: although elseif keyword is much more common, else if is also supported 21
while loop (same as Java) while (condition) { statements; } PHP do { statements; } while (condition); PHP • break and continuekeywords also behave as in Java 22
Math operations $a = 3; $b = 4; $c = sqrt(pow($a, 2) + pow($b, 2)); PHP • math functions • math constants 3.14159265… 2.7182818… loge2=0.693147… • the syntax for method calls, parameters, returns is the same as Java 23
int and float types $a = 7 / 2; # float: 3.5 $b = (int) $a; # int: 3 $c = round($a); # float: 4.0 $d = "123"; # string: "123" $e = (int) $d; # int: 123 PHP • int for integers and float for reals • division between two int values can produce a float 24
Stringtype $favorite_food = "Ethiopian"; print $favorite_food[2]; # h $favorite_food = $favorite_food . " cuisine"; print $favorite_food; # Ethiopian cuisine PHP • zero-based indexing using bracket notation • there is no char type; • each letter is itself a String • string concatenation operator is . (period), not + • 5 + "2 turtle doves" => 7 • 5 . "2 turtle doves" => "52 turtle doves" • can be specified with "" or ‘’ 25
Stringtype Large set of other functions exists. Example: PHP # index 0123456789012345 $name = "Stefanie Hatcher"; $length = strlen($name); # 16 $cmp = strcmp($name, "Brian Le"); # > 0 $index = strpos($name, "e"); # 2 $first = substr($name, 9, 5); # "Hatch" $name = strtoupper($name); # "STEFANIE HATCHER" 26
Splitting and joining strings $array = explode(delimiter, string); $string = implode(delimiter, array); • explode and implodeconvert between strings and arrays • for more complex string splitting, you can use regular expressions Example $s = "CMPS 278 M"; $a = explode(" ", $s); # ("CMPS ", “278", "M") $s2 = implode("...", $a); # "CMPS...278...M"
Interpreted/interpolated strings PHP $age = 16; print "You are " . $age . " years old.\n"; print "You are $age years old.\n"; # You are 16 years old. print 'You are $age years old.\n‘; # You are $age years old.\n print "Today is your $ageth birthday.\n“; # $ageth not found print "Today is your {$age}th birthday.\n"; 28 • strings inside " " are interpreted • variables that appear inside them will have their values inserted into the string • strings inside ' ' are not interpreted. • if necessary to avoid ambiguity, can enclose variable in {}.
bool (Boolean) type $feels_like_summer = FALSE; $php_is_rad = TRUE; $student_count = 217; $nonzero = (bool) $student_count; # TRUE PHP • the following values are considered to be FALSE (all others are TRUE): • 0 and 0.0 • "", "0", and NULL (includes unset variables) • arrays with 0 elements • Undefined variables • can cast to boolean using (bool) • FALSEprints as an empty string (no output); TRUEprints as a 1
NULL $name = "Victoria"; $name = NULL; if (isset($name)) { print "This line isn't going to be reached.\n"; } PHP • a variable is NULL if • it has not been set to any value (undefined variables) • it has been assigned the constant NULL • it has been deleted using the unset function • can test if a variable is NULL using the isset function • NULL prints as an empty string (no output)