Lecture 10 ● Log into Linux ● Questions? Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 1 Outline ● Introduction to PHP ● PHP data types ● Basic operations ● PHP control structures ● I/O Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 2 What is PHP? ● ● PHP is a portable (UNIX, Windows, Mac) scripting language with C++-like syntax with more high-level features than C++ especially designed for web programming. PHP was created by Rasmus Lerdorf in 1995 to make common web programming tasks easier. The name originally stood for "Personal Home Page," but has since become to mean "PHP: Hypertext Processor. PHP 5 is the current version. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 3 What is PHP? ● ● PHP also can be used at the command-line and is well-suited for text manipulation and system administration tasks. It can be used for rapid prototyping, system utilities, database access, network programming, and graphical programming, as well as web applications. There are several other scripting languages that are similar to PHP: Perl, Python, TCL, REXX, Ruby, etc., but PHP combines familiar syntax, ease of use, and efficiency of execution in a way that makes it very popular. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 4 PHP Documentation ● ● The PHP manual is on-line (PMAN) and is considered a very good source. Supplemental reading references have several tutorial sites (PINT, PZND, PW3S) Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 5 Hello World! ● Create a file helloworld.php: <?php print "Hello world!\n"; ?> ● Syntax is like a combination of shell and C++. ● To run this script type: $ php helloworld.php ● (Note: the php5-cli package must be installed) ● (Note: PHP files do not need to be executable) Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 6 Code Islands ● PHP scripts (called code islands) are embedded within static text. The static text is output verbatim by the PHP interpreter. E.g. This is text before the first code island <?php print "This line is generated by code\n"; ?> This is text between code islands <?php print "This line is generated by code\n"; ?> This is text after both code islands Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 7 Comments ● PHP comments are indicated by //, #, or /* */. For example: // This is a comment # This is a comment, too /* This is multi­line comment */ Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 8 Variables ● ● ● As with shell scripts, PHP variables are not declared and may change type through assignment. Be careful of spelling errors. PHP has seven data types: integer, float, boolean, string, array, object, and resource. However, PHP will do automatic conversion. PHP variable names always start with $. $msg = "Hello world!"; print "$msg\n"; // one string echo $msg, "\n"; // list of items Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 9 Constants ● PHP constants are defined using the define command. E.g., define ("SecondsPerDay", 86400); echo SecondsPerDay, "\n"; ● ● Unlike variables, constant names do not start with $ and cannot be used inside " ". There are several predefined constants. E.g., ● ● __FILE__, __LINE__ : the file and line being executed M_PI, M_SQRT2 : pi and square root of 2 Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 10 Arrays ● ● PHP has two types of arrays, indexed and associative, created using the array command. Unlike C++, the elements do not need to be of the same type. Indexed arrays are created and accessed as follows: $data = array(1,"abc",2.5); echo $data[2], "\n"; // 2.5 ● Can add to an array using [ ] (array operator): $data[] = $msg; // $data[3] Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 11 Arrays ● Associative arrays are created and accessed as follows: $fruits = array("a"=>"apple", "b"=>"banana", "c"=>"cantaloupe"); echo $fruits["b"], "\n"; // banana ● Use the array operator to add elements $fruit["d"] = "date"; ● For both kinds of arrays, can start with an empty one and just add elements. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 12 Special Variables ● $_SERVER is an associative array that is indexed by the shell environment variable names. E.g. echo $_SERVER['HOME'], "\n"; echo $_SERVER['SHELL'], "\n"; $argc = $_SERVER['argc']; // like C++ $argv = $_SERVER['argv']; echo "There are ", $argc, "args\n"; echo "They are:\n"; print_r($argv); Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 13 Using print_r( ) ● Structured data like an array or object can be displayed using the print_r( ) function. E.g., // print_r($data); // print_r($fruits) Array ( [0] => 1 [1] => abc [2] => 2.5 [3] => Hello world! ) Array ( [a] => apple [b] => banana [c] => cantaloupe [d] => date ) Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 14 Operators ● ● ● Arithmetic, equality, relational, and logical operators are as in C++. In addition, there are logical operators AND and OR. === (identity) can be used to check for unwanted type conversions. String concatenation is done using '.' E.g., $word1 = "hot"; $word2 = "dog"; $word3 = $word1 . $word2; // "hotdog" Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 15 Built-in Functions ● ● ● Math functions are as in C (abs, sin, cos, etc.). There is also deg2rad( ) for converting degrees to radians. C-string operations (strlen, strcmp, substr, etc.) are supported. Operations to split strings into an array of words and vice versa are supported. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 16 String and Array Tricks $line = "abc\ndef\nghijkl\nmnop"; $parts = explode("\n", $line); // array of elements between separator $size = count($parts); // 4 $parts[] = "qrst"; // add to end $partlist = implode(", ", $parts); // string of elements with separator $input = trim($input); // remove leading/trailing whitespace $input = rtrim($input); // remove only trailing whitespace Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 17 Here Documents ● Like the bash scripting language, PHP has here documents. Note the redirection operator is <<< and there is a semicolon at the end. print <<<EOT The data is $data[0], $data[1], $data[2], and $data[3] EOT; Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 18 Selection Constructs ● ● ● The if-else statement is same as C++. Multibranch selection has if-elseif-else. "" (empty string), "0", 0, 0.0 are false, but "0.0" is true. All other values are true. The switch statement is same as C++ (including case fall-through without a break statement), but also can use strings as case values. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 19 Repetition Constructs ● ● PHP has while, do-while, and for statements as in C++. PHP also has a foreach statement for use with arrays. foreach ($data as $item) { print "$item\n"; } foreach ($fruits as $key => $fruit) print "$key = $fruit\n"; } Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 20 Using isset( ) ● Since variables are not declared in PHP, sometimes we want to know whether a variable has been set (i.e., given a value). This can be done using the isset( ) function. This function returns true if the variable argument has been set and false if it has not. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 21 Using isset( ) $foo = 1; if (isset($foo)){ print "foo is set\n"; } else { print "foo is not set\n"; } if (isset($bar)) { print "bar is set\n"; } else { print "bar is not set\n"; } Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 22 File Input $filestring = file_get_contents ($filename); if ($filestring) print $filestring; else print "Could not open $filename\n"; $handle = fopen($filename, "rt") // or "wt","at" ­ t is for eol translation OR die ("Cannot open $filename\n"); while (!feof($handle)) { $line = fgets ($handle); print "$line\n"; } fclose ($handle); Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 23 Keyboard Input ● PHP was not designed to receive input interactively. Use the fopen function with "php://stdin" as the file name. print "Enter a file name: "; $handle = fopen ("php://stdin", "rt"); $input = fgets ($handle); $input = rtrim ($input); // remove '\n' print "You entered: $input\n"; Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 24 File Output $outfile = fopen($filename, "at"); $numbytes = fwrite ($outfile, $string); fclose ($outfile); $numbytes = file_put_contents($filename, $string); // 3rd arg FILE_APPEND to append Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 25 File Operations ● rename ( ), copy ( ), unlink ( ) ● rewind ( ), fseek( ) ● file_exists ( ) - returns true if filename exists ● ● fileatime ( ), filemtime ( ) - returns time in UNIX time_t format date ( ) - converts time_t to string $atime = fileatime($filename); $atimestr = date ("F jS Y H:i:s", $atime); print "File last accessed: $atimestr\n"; ● is_file ( ), is_dir ( ) ● is_readable ( ), is_writeable ( ), is_executable ( ), chmod ( ) Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 26 In-class Exercise ● Write a PHP program in file getinfo.php that takes a single username as an argument and then displays that username, uid, and home directory from file /etc/passwd in the form shown below (or an error message if not found): $ php getinfo.php lightdm lightdm (104) /bin/false $ php getinfo.php root root (0) /root ● Put your name in a comment and submit your program to the submission system. Tuesday, September 29 CS 375 UNIX System Programming - Lecture 10 27