Monday 2 February 2015

PHP Basics

PHP is a scripting language that can be embedded in HTML.
  1. Tags and SyntaxPHP commands are embedded into HTML by one of several ways. The preferred method is include the code using the special tags <?php PHP_code_goes_here ?>. A second way is to include the code within a <script language="php"?> - </script> block. Each PHP statement should end with a semicolon. Many statements can be contained in a single block and a single statement can span several blocks:
    <?php
    if ($condition) {
       ?>
       <b>This is true.</b>
       <?php
    } else {
       ?>
       <b>This is false.</b>
       <?php
    }?>

    Comments are supported in the normal C/C++ and Java style:

    <?php
    echo "This is a test"; //This is a one-line comment. 
    /* This is a multi-line
    comment */
    ?>

  2. Variables and Datatypes
    Variables in PHP are represented by a dollar sign followed by an alphanumeric name beginning in a letter or underscore. Variable names are case sensitive. Variables do not need to be declared and their datatypes are inferred from the assignment statement.
    PHP supports the following data types:
    • boolean
    • integer
    • float
    • string
    • array
    • object
    • resource
    • NULL

    Example:
    <?php
    $bool = TRUE;
    $name = "Craig";
    $age = 25;
    $pi = 3.14159;
    echo $name . ' is ' . $age . ' years old.';
    ?>
    -> Craig is 25 years old.
    Variable Scope: The single scope of most variables in PHP spans the entire file plus any included files. For instance if you define $a = 1; then a will be available within any included files. 
    Local Variables: Any variable used inside a user-defined function, however, has its scope limited to the local function. In addition, global variables are not available inside local functions unless declared with the global keyword: 
    $a = 1;
    $b = 2;
    function Sum() {
       global $a, $b;
       $b = $a + $b; }
    Sum();
    Pointers can be assigned with an ampersand sign: $a = &$b;

  3. Statements and Expressions
    Some basic PHP statements include:
    • echo: Output one or more strings.
    • print: Also output one or more strings.
    • The assignment statement: Assigns a value to a variable.
    • include: Include and evaluate the specified file.
    • require: Same as include except it produces a fatal error on failure instead of a warning.

    Examples:
    echo "Hello World.";
    echo "Text can span
    multiple lines. Newlines will be
    output as well or can be done \nlike this.";
    echo $bool ? 'true' : 'false'
    $a = ($b = 5) + 4;
     // a = 9, b = 5
    echo $a,$b;
    $c = 'A equals ' . $a;
    print $c;
    include 'test.php'
     // The code in test.php will be evaluated here
    PHP expressions can include:
    $a = $b = 5; //The assignment statement
    $b = $a++; //Post-increment a
    $b = ++$a; //Pre-increment a
    $x = $bool ? $a : $b; //Ternery conditional
    The last expression evaluates to if ($bool) $x = $a else $x = $b.

  4. Operators and Maths
    Operators:
    • Arithmatic: +, -, *, /, and % (modulus)
    • Comparison: ==, !=, <, >, <=, >=
    • Logical: &&, And; ||, Or; ! (NOT); Xor
    • Execution: $output = `ls -l`;
         echo $output;
       //commands enclosed with backticks are executed and returned
    • Type: $obj = new A;
         if ($thing instanceof A) echo 'A';
    Maths:
    • Absolute Value: $a = abs(-7.5);
    • Arc sine: $x = asin(0.5); //returns in rads
    • Ceil (round up): echo ceil(4.2);
    • Cosine: $a = cos($x); //$x in rads
    • Deg2rad: $a = cos(deg2rad(45)); //cos 45 deg
    • Exp: $y = exp($x); //y=e^x
    • Floor (round down): $a = floor($a+0.5);
    • Is_Finite: $bool = is_finite($x);
    • Is_Infinite: $bool = is_infinite(log(0));
    • Is_NAN: $bool = is_nan(acos(1.01));
    • Log: $x = log($y); //Natural Log
         $x = log($y,5); //Base-5 log
    • Log Base 10: $x = log10($y);
    • Max: $mx = max(1, 7, 3, 4); //7
         $mx = max($arr); //max value in array
    • Min: $mn = min(3, 0, -1, $x); //min value
    • Powers: $x = pow($y,3); //x=y^3
    • Rad2deg: $a = rad2deg(asin(0.5)); //$a = 30
    • Random #: $x = mt_rand(1,100); //int 1-100, inclusive
         $x = rand(1,100)/100. //slower than mt_rand
    • Round: echo round(3.793,1); //3.8 - rounded to 1 decimal
         $a = round(3.793,0); //4
    • Sine: $a = sin(1.57); //in rads
    • Square Root: $x = sqrt(10); //3.16...
    • Tangent: echo tan(3.14); //in rads

  5. Strings
    Strings can be specified in 3 ways: single quotes, double quotes, or heredoc. Strings in single quotes do not expand variables or escape sequences except for single quotes: echo 'I\'ll be back.';.
    echo 'The newline \n will not expand';
    $a = 'Gators';
    echo 'The value of $a is ' . $a;

    -> The value of $a is Gators
    If a string is enclosed in double quotes, escapes such as \n, \r, \t, \\, and \" may be used and variables are expanded:echo "Go $a";
    -> Go Gators
    echo "{$a}bait!";
    -> Gatorbait!
    Heredoc syntax: Starts with <<< followed by an identifier. Ends with the identifier repeated at the start of a line.
    echo <<<ABC
    This is an example of a string in the heredoc syntax.
    Always use braces around arrays when inside of strings:
    The 3rd person's name is {$people['names'][3]}
    ABC;

    String Operators:
    Concatenation is done with the '.' operator.
    Converting to numbers:
    $x = 1 + "10.5"; //$x=11.5, float
    $x = 4 - "3"; //$x=1, int
    You can convert to a string with the (string) cast or thestrval function Booleans are converted to strings as "1" or "" (empty string). Values are also converted to strings when a string is needed, such as when using the echo or print functions.
    String Functions:
    • array explode(string separator, string string [,int limit]): parse a string into an array
        $pizza = "piece1 piece2 piece3";
         $pieces = explode(" ", $pizza);
    • string implode(string glue, array pieces): combine array elements into a string
        $array = array('name', 'email', 'phone');
         $comma_separated = implode(",", $array);
    • string str_replace(string search, string replace, string subject [,int count]):
        $bodytag = str_replace("%body%", "black", "text='%body%'");
        -> text='black'
        $vowels = array("a", "e", "i", "o", "u");
         $novowels = str_replace($vowels, "", "Hello World of PHP");

        -> Hll Wrld f PHP
    • str_ireplace: Case-insensitive version of str_replace.
    • string str_repeat(string input, int multiplier):
        echo str_repeat(" ",10);
    • array str_split(string string [,int split_length]):
        $arr = str_split("ABCDEFGHIJKL",3); //$arr[0]="ABC" ... $arr[3]="JKL"
    • int strcmp(string str1, string str2): returns <0 if str1 is less than str2, 0 if they are equal, and >0 if str1 is greater.
        if (strcmp($s1,$s2) > 0) echo "greater";
    • int strncmp(string str1, string str2, int len): Same as strcmp except it compares only the first len characters.
    • int strlen(string str): returns the length of a string
        $n = strlen($s);
    • int strpos(string haystack, string needle [,int offset]): Returns the numeric position of the first occurance of needle in haystack. Returns FALSE if needle is not found. Because position 0 also evaluates to FALSE, check with '===' and '!==' (identical value and type instead of equality).
        $p = strpos("This is a test","is");
         if ($p !== false) echo 'Position ' . $p;
    • int stripos(string haystack, string needle [,int offset]): Same as strpos but case insensitive.
    • string strtolower(string str): Convert a string to lowercase.
    • string strtoupper(string str): Convert a string to uppercase.
    • string substr(string string, int start [,int length]): Return a substring of string. A negative value for start results in starting at the nth character from the end of the string.
        echo substr("abcdef",1,3); //bcd
    • string trim(string str): Strip whitespace from the beginning and end of a string.

  6. Arrays
    Arrays in PHP are actually ordered maps, almost like hash tables. They map values to keys that can be either integers or strings.
    • Defining with array(): An array can be defined defined by the keyword array array([key => ]values):
      $arr = array(0 => 5, 3 => "text", "test" => true); 
      -> $arr[0]=5, $arr[3]="text", $arr["test"]=true 
      If no key is specified, then 1 + the maximum integer key is taken for the new key. The first element defaults to 0 if no key is given.
      $arr = array(0,1,4,9,16,25); //a 6-element array with each value equal to the square of its key.
      $arr = array(3 => 24, "a" => 32, 40, 48);
      -> $arr[3]=24; $arr["a"]=32; $arr[4]=40; $arr[5]=48 
    • Defining with []: You can also define an array or add values to it using the [] notation:
      $arr[5] = 100;
      This will set $arr[5] to 100, overwriting any previous value of $arr[5]. If $arr does not exist yet, it will be created.
      $arr = array(3, 12 => 2);
      $arr[] = 19;
      $arr[0] = "some text";
      $arr["x"] = 5;

      -> $arr[0] = "some text" (replacing 3), $arr[12] = 2, $arr[13] = 19, $arr["x"] = 5
    • Deleting values with unset(): The function unset() allows you to delete elements from an array.
      $a = array(1 => 'one', 2 => 'two', 3 => 'three');
      unset($a[2]);

      -> $array[1]='one', $array[3]='three' Note that $array[2] no longer exists but the other keys and elements are unaffected.
    • Multi-dimensional arrays: Because PHP arrays are actually ordered maps, you are allowed to have jagged arrays:
      $arr = array("fruits" => array ( "a" => "orange", "b" => "banana", "c" => "apple"),
      "numbers" => array(1, 2, 3, 4, 5, 6),
      "holes => array("first", 5 => "second", "third")); 
      -> $arr["fruits"]["b"] = "banana"; $arr["numbers"][4]=5; $arr["holes"][6]="third"... 
      $a = array(0, 1, 2, 3);
      $var = 5;
      $b = array("a" => $a, "var" => $var, 3 => array("first", "second", "third")); 

      -> $b["a"][2]=2; $b["var"]=5; $b[3][1]="second"...
    Array Operators:
    • Union: $a + $b
      The + operator appends the array on the right ($b) to the array on the left ($a) and duplicate keys are thrown away and not overwritten.
      $a = array(3, "a" => "Roberson", "b" => "Walsh");
      $b = array(4, "a" => "Lee", "c" => "Humphrey");
      -> $a+$b = {3, "a" => "Roberson", "b" => "Walsh", "c" => "Humphrey"}
      $b+$a = {4, "a" => "Lee", "b" => "Walsh", "c" => "Humphrey"}
    • Equality: $a == $b and Inequality: $a != $b
      $a is equal to $b if their elements all have the same key and value. The following two arrays are equal:
      $a = array("apple", "banana");
      $b = array(1 => "banana", "0" => "apple");
    • Idendical: $a === $b and Not Identical: $a !== $b
      $a is identical to $b if they have the same elements in the same order.
    Array Functions:
    • array array_combine(array keys, array values): creates a new array by using one existing array for keys and another for values. Returns false if it fails.
        $a = array('a','b','c');
         $b = array('red','green','blue');
         $c = array_combine($a, $b);
    • array array_flip(array input): swaps the keys and values of the array input. All values from input must be valid keys (integer or string). If a value occurs more than once, the latest key will be used as its value and all others will be thrown away. Returns false if it fails.
        $a = array("a" => 1, "b" => 2, "c" => 2);
      $b = array_flip($a);

        -> $b = {1 => "a", 2 => "c"}
    • array array_keys(array input [,mixed search_value]): returns all keys from the input array as the values of a new array. The new array has keys numbered from 0 to n_elements-1. If a search_value is specified, then only the keys for that value are returned.
        $a = array (0 => 100, "color" => "orange");
         $b = array("blue", "red", "blue", "green");
        -> array_keys($a) = {0, "color"}
         array_keys($b, "blue") = {0, 2}
    • array array_merge(array array1, array array2 [, array ...]): merges the elements of multiple arrays into one array. If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. However, if the arrays contain the same numeric keys, the later value will be appended with a new numeric key.
    • mixed array_pop(array array): pops and returns the last value of the array, shortening the array by one element. NULL is returned from an empty array.
        $var = array_pop($arr);
    • int array_push(array array, mixed var [,mixed ...]): pushes the variable(s) onto the end of array. Same effect as $arr[] = $var;. Returns the new number of elements in the array.
        array_push($arr, "Roberson", "Walsh");
    • array array_reverse(array array [,bool preserve_keys]): reverses the order of elements in the array. If preserve_keys is TRUE, the keys will be preserved in the reversed array.
    • mixed array_search(mixed needle, array haystack): Searches the array haystack for needle and returns the key if it is found and false otherwise.
        $key = array_search('Lee',$players);
    • mixed array_shift(array array): pops the first element out of the array and returns it. All numerical keys in the rest of the array will be modified to start counting from zero, while string keys won't be touched.
    • mixed array_sum(array array): returns the sum of the values in the array as an int or float.
    • int count(mixed var [,int mode]): Returns the number of elements in var if var is an array, and returns 1 if var is not an array. Returns 0 if var is null. If mode is set to 1, then count will recursively count the array. This is useful for counting all elements in a multi-dimensional array. Each subarray and element will be counted though so a 2x3 array will return 8 when counted recursively (and 2 when counted normally).
    • bool sort(array array): Sorts an array from lowest to highest. New keys will be assigned for the elements in array (numeric, starting with zero) and any existing keys will be removed. Returns true or false. Other types of sort include:
      • asort: Sort an array and maintain the current keys.
      • ksort: Sort an array by key instead of by value.
      • rsort: Sort an array in reverse order (highest to lowest).
      • arsort: Sort an array in reverse order and maintain keys.

  7. Conditionals
    • if: if (expr) statement;
    • if-else: if (expr) statement1; else statement2;
    • if-elseif: if (expr) statement1;
         elseif (expr) statement2;
         else statement3;
      Multiple elseifs can be included in the same if statement.
    • switch: switch($var) {
         case 0: statements;
         break;
         case "n": statements;
         break;
         default: statements;
        }
      Note that if you do not include the break; statement, PHP will continue to execute code for the next cases until it encounters a break;.

    Examples:
    if ($a > $b) echo "a is greater than b";

    if ($a > $b) {
       echo "a is greater than b";
    } elseif ($a < $b) {
       echo "a is less than b";
    } else {
       echo "a is equal to b";
    }

    switch ($a) {
      case 0:
        echo "i equals 0";
        break;
      case 1:
        echo "i equals 1";
      case 2:
        echo "i is greater than 0 and less than 3";
        break;
      case "a":
        echo "i equals a";
        break;
      default:
        echo "i does not equal 0,1,2, or a.";
    }

  8. Loops
    • for: for (expr1; expr2; expr3) statements;
      Same syntax as Java/C++. expr1 sets the initial condition and the loop executes as long as expr 2 true, executing expr3 each iteration.
    • while: while (expr) statements;
      Executes statements while the expression is true.
    • do...while: do { statements; } while (expr);
      Similar to while loops except that the condition is checked after the body of the loop, meaning that the body will always be executed at least once.
    • continue: continue [int arg];
      Skips the rest of the body of the loop for the current iteration and continue execution at the beginning of the next iteration. The optional arg tells it how many levels of loops it should skip to the end of (useful when using nested loops).
    • break: break [int arg];
      Ends the execution of the current loop. The optional arg tells it how many levels of loops it should break out of.
    • foreach: foreach (array_expression as [$key =>] $value) statements; 
      Loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one. If specifiec, the current element's key will be assigned to $key each iteration.

    Examples:
    for ($j = 0; $j < 10; $j++) {
       echo "Value number $j is {$value[$j]]}";
    }

    while ($b < $a) {
       echo "b is less than a.";
       $b++;
    }

    $i = 10;
    do {
       echo "This will execute at least once.";
    } while ($i < 10);

    for ($j = 0; $j < 10; $j++) {
       while($k < $j) {
         echo "j = $j, k = $k";
         if ($j == 1) break;
         if ($j % 2 == 1) continue 2;
         $k++;
      } echo "j is even or j equals 1.<br>";
    }

    foreach ($arr as $key => $value) {
       echo "Key: $key, Value: $value<br>\n";
    }

  9. Functions
    • Definition: Functions in PHP are defined with the following syntax:
      function funct($arg_1, $arg_2, ..., $arg_n) {
         echo "This is a function.";
         return $value;
      }
      Any PHP code, including other function and class definitions, may appear inside a function. Functions may also be defined within a conditional, but in that case the function's definition must be processed prior to its being called. PHP does not support function overloading but does support variable numbers of arguments as well as default arguments. Return types are not specified by function.
    • Arguments: By default, function arguments are passed by value so that if you change the value of the argument within the function, it does not get changed outside of the function. If you want the function to be able to modify its arguments, you must pass them by reference by prepending an ampersand to the argument name:
      function modify_arg(&$arg1, $arg2) {
         $arg1++;
       //$arg1 has now been modified
         $arg2++; //$arg2 has not
         return;
      }
    • Default Arguments: A function may define default values for scalar arguments. The default must be a constant expression and any defaults should be on the right side of any non-default arguments.
      function square($x = 5) {
         return x*x;
      }

      If this function is called with square();, it will return 25. Otherwise, if it is called with square($n); , it will return $n^2.
    • Variable length argument lists: The functions int func_num_args(), mixed func_get_arg(int arg_num), and array func_get_args() return the number of arguments passed to the function, the argument number arg_num as counted starting from zero, and an array of the function's argument list, respectively. To use a function with a variable length argument list, define the function with a void argument list: function var_arg_list() {...} and later call it with a variable number of arguments: $a = var_arg_list($b, "test", 3);. Within the function, use func_num_args, func_get_arg, and func_get_args to process and handle the arguments.
    • Return: Values are returned from the function with the return command: return $var;. You can not return multiple values, but that can be achieved by returning an array or object. Return immediately ends execution of the function and passes control back to the line from which it was called.
    • Variable Functions: PHP supports the concept of variable functions. That means that if a variable name has () appended to it, PHP will look for a function with the name of the value of the variable. Objects within a method can be called similarly.
      function test() {
         echo 'This is a test.';
      }
      $var = 'test';
      $var();
       //this calles test()
      $var = 'setRadius';
      $circle->$var(3);
       //this calls $circle->setRadius(3)

  10. Classes and OOP
    PHP supports OOP and classes. A class is a collection of variables and functions working with these variables. Classes are defined similarly to Java except that "->" is used instead of "." when referring to functions and elements of a class. You can NOT break up a class definition into multiple files or multiple PHP blocks.
    • Initializing vars: Only constant initializers for class variables are allowed (var $n = 1;). To initialize variables with non-constant values, you must use the constructor.
    • Encapsulation: PHP5 supports private and protected variables and methods. Prior to PHP5 however, everything is public and must be declared with either the var orfunction keywords.
    • Inheritence: PHP allows classes to be extended (see right) with the extendskeyword. The child class takes all the variables and functions from the parent class and can extend that class by adding additional variables and adding or overriding functions. If class B extends class A, then A or B can be used anywhere an A is expected, but only B can be used where a B is expected because it contains additional information/methods not found in A.
    • Abstract classes: Abstract classes are allowed in PHP5 but not before. Abstract classes create a template for other classes to extend and use. Instances can not be created of abstract classes but they are very useful when working with several objects that share many characteristics. For instance, when creating a database of people, one could define the abstract class "Person", which would contain basic attributes and functions common to all people in the database. Then child classes such as "SinglePerson", "MarriedCouple", or "Athlete" could be created by extending "Person" and adding appropriate variables and functions. The database could then be told to expect every entry to be an object of type "Person" and thus any of the child classes would be a valid entry.
    • Parent: The parent keyword allows you to call methods from the parent of the current class: parent::method_name(); (see right).
    • Constructors: Constructors are fuctions that are automatically called when you create a new instance of a class. They can be used for initialization purposes. A function is a constructor when it has the same name as the class it is defined in. When extending classes, if a new constructor is not defined, the constructor from the parent class is used (see right). When an object of type RectWithPerimeter is created, the constructor from Rectangle is called. If however, I were to add a function inRectWithPerimeter with the name RectWithPerimeter , then that function would be used as its constructor.
    • ::- PHP allows for referencing functions and variables in base classes or to functions in classes that do not yet have any instances with the :: operator. If you have a class A, and want to call its method test(); but do not yet have an instance of A, this can be done by: A::test();. Similarly, if class B extends A, functions in class B can refer to variables and functions in class A by: A::var and A::function($var);. It is recommended to use the parent keyword though to refer to members of the parent class.
    • Comparing Objects: Objects can, like arrays, be compared using the ==, !=, === (identical), and !== (not identical) operators. Two objects are equal if they have the same attributes and values and are instances of the same class.

    Example Class:
    class Rectangle {//Define variables width and height
       var $width, $height;
    //Constructor
       function Rectangle($width = 0, $height = 0) {
         $this->width = $width;
         $this->height = $height;
       }
    //functions
       function setWidth($width) {
         $this->width = $width;
       }
       function setHeight($height) {
         $this->height = $height;
       }
       function getArea() {
         return $this->width * $this->height;
       }
    }
    $arect = new Rectangle();
     //create a new Rectangle with dimensions 0x0. 
    $arect->setWidth(4);
    $arect->setHeight(6);
    echo $arect->getArea();

      -> 24
    $rect2 = new Rectangle(7,3); //new Rectangle with dimensions 7x3.

    Extended Class:
    class RectWithPerimeter extends Rectangle {//add new functions
       function getPerimeter() {
         return 2*$this->height + 2*$this->width;
       }
       function setDims($width, $height) {
    //use the parent keyword to call methods from Rectangle 
         parent::setWidth($width);
         parent::setHeight($height);
       }
    }
    $arect = new RectWithPerimeter(6,5);
     //Uses the constructor from Rectangle because no new constructor is provided to override it.
    echo $arect->getArea(); //Uses the getArea function from Rectangle and prints 30.
    echo $arect->getPerimeter(); //Uses getPerimeter from RectWithPerimeter and prints 22.
    $arect->setDims(4,9); //Use setDims to change the dimensions.

  11. File I/O
    PHP allows for reading/writing to files on the server that have correct permissions.
    • Opening Files: resource fopen(string filename, string mode): 
      fopen can be used to open local files or if enabled, remote files using http:// or ftp://. It binds a named resource to a stream that can then be used to read/write data. Possible modes include:
      • 'r': Open for reading.
      • 'w': Open for writing. Any existing data will be overwritten.
      • 'a': Open for writing. New data will be appended to existing data.
      • 'x': Create a new file and open for writing. If the file exists, fopen will fail and return FALSE.
      • 'b': Use this flag when working with binary files (e.g. 'rb').
    • Checking Files: PHP supports several methods of checking if a file exists and checking its properties:
      • bool is_dir(string filename): returns TRUE if the filename exists and is a directory.
      • bool is_file(string filename): returns TRUE if the filename exists and is a regular file.
      • bool is_readable(string filename): returns TRUE if the filename exists and is readable.
      • bool is_writable(string filename): returns TRUE if the filename exists and is writable.
    • File Operations: PHP also supports file operations such as copying and deleting files.
      • bool copy(string source, string dest): Copies the file source to dest. Returns TRUE if successful.
      • bool mkdir(string pathname, int mode): Makes a directory pathname with permissions mode (e.g. mkdir('new_dir', 0700);)
      • bool rename(string oldname, string newname): Renames a file
      • bool symlink(string target, string link): Creates a symbolic link to the existing target with name link.
      • bool unlink(String filename): Deletes filename.
    • Reading Files: Files can be read by several methods.
      • string fgets(resource handle [,int length]): Reads a line of up to a specified number of bytes from the file pointed to by handle into a string. It will read until it encounters a newline, EOF, or the specified length is reached (default is 1024 bytes). Handle is the handle created when the file was opened for reading with fopen.
      • string fread(resource handle, int length): Reads up to length bytes from the file pointed to by handle into a string. Can be used with binary files. Reading stops when length bytes have been read or EOF is reached.
      • int readfile(string filename): Reads a file and writes it to the output buffer. Returns the number of bytes read from the file.
      • string file_get_contents(string filename): Reads an entire file and returns it as a string.
      • array file(string filename): Reads an entire file and returns it as an array. Each element of the array corresponds to a line in the file, with the newline still attached.
    • EOF: bool feof(resource handle) can be used to check for end of file. while (! feof($handle)) { do_something }
    • Writing to files: Files that have been opened for writing with fopen can be written to by several methods.
      • int fwrite(resource handle, string string [,int length]): Writes the contents of string to the file stream pointed to by handle. Handle is the handle created when the file was opened for writing or appending with fopen. Writing stops after length bytes or the end of string is reached. Returns the number of bytes written or FALSE on error.
      • int file_put_contents(string filename, string data [,int flag]): Writes the string data to the file. If flag is set to FILE_APPEND, the file will be appended instead of overwritten.
    • Concurrency: File locking is available through the flock method. bool flock(resource handle, int operation), where operation can be LOCK_SH to acquire a shared lock (reader), LOCK_EX to acquire an exclusive lock (writer), LOCK_UN to release a lock, or LOCK_NB if you don't want flock to block while locking (or 1, 2, 3, or 4 respectively). Alternatively, you can write your own semaphors.
    • Serializing Objects: An object can be serialized with the method string serialize(mixed value). This will return a string representation of the object that can be stored anywhere (e.g. in a file for instance) and later reconstructed into the object with unserialize. mixed unserialize(string str) can then take a string representing a serialized object and reconstruct the object. If the object is an instance of a class, that class must be defined in the PHP page that unserializes the object (i.e. if you have an object of type A on page1.php, serialize it, write it to a file, and on page2.php you read it back in from the file, then class A must be defined on page2.php to unserialize the object. An easy solution is to put the definition of class A in a file to be included in both page1.php and page2.php). Arrays can be serialized as well.
    • Sockets: A socket can be opened with resource fsockopen (string target, int port [,int errno [,string errstr [,float timeout]]]). It returns a resource that can then be used with methods such as fgets, fwrite, feof, and fclose. Sockets are closed with fclose. If specified, errno and errstr will return the error number and details if an error occurs. Example: $s = fsockopen("www.example.com", 80, $errno, $errstr)
    Examples:
    $file = fopen("data/teams.txt","r");
    while (!feof($file)) {
       $team = fgets($file);
       echo $team;
    }
    fclose($file);

    $imgf = fopen("../img/football.jpg","rb");
    $image = "";
    while (!feof($imgf)) {
    $image .= fread($imgf,1024);
    }
    fclose($imgf);

    $player = serialize(new Player("J.J. Redick", "Duke", 4));
    $file = fopen("data/players.txt", "a");
    if (flock($fp, LOCK_EX)) {
       fwrite($file, $player);
       flock($file, LOCK_UN);
    } else echo "Couldn't lock the file!";
    fclose($file);

    $html = file_get_contents('http://www.example.com/');

  12. PHP and HTML Forms (User Input)
    When a form is submitted to a PHP script, the information from that form is automatically available to the script via several methods. First, you will want to set a form's action="script.php" and choose which method to use, "get" or "post". Get appends the arguments to the URL, while Post does not. PHP can then access the information from the form by the arrays $_GET and$_POST, depending on which method you used. The syntax is $var = $_POST['element_name'];, where element_name is the name assigned to a particular form element in the HTML code. If you do not care which method the form used, you can use the $_REQUEST array, which contains the contents of $_GET, $_POST, and $_COOKIE. 

    bool isset(mixed var): isset can be used to check whether a form has been submitted. It can also be used on any variable, returning TRUE if the variable exists. if (isset($_POST['name'])) ... 

    Image Submit variables: When using an image to submit a form instead of a standard submit button (<input type="image" src="image.gif" name="image_submit">), the form will be transmitted to the server with two additional variables, sub_x and sub_y. These contain the coordinates of the user click within the image. 

    Reading into arrays: By using [] or [key] within the name of the form element in the HTML, you can read the form information into arrays, i.e. $_POST['personal']['name'] or $_POST['beer'][0]. See the example to the right. If I had used personal[] for both Name and E-mail, then those values could be accessed by $_POST['personal'][0] and $_POST['personal'][1] respectively.

    Examples:
    < form action="script.php" method="post">
    Name: <input type="text" name="name"><br>
    E-mail: <input type="text" name="email"><br>
    </form>

    script.php:
    <?phpecho "Your name is " . $_POST['name'];
    $email = $_POST['email'];
    echo '<a href="mailto:' . $email . '">Send e-mail</a>
    ?>

    A more complex example:
    <?php
    if (isset($_POST['is_submitted']) && $_POST['is_submitted'] == 'submitted') {
    print_r($_POST);
    echo '<a href="'. $_SERVER['PHP_SELF'] .'">Try again</a>';
    } else {
    ?>
    <form action="<?php 
    echo $_SERVER['PHP_SELF']; ?>" method="post">
    Name: <input type="text" name="personal[name]"><br>
    E-mail: <input type="text" name="personal[email]"><br>
    Beer:<br>
    <select multiple name="beer[]"> <option value="warthog">Warthog
    <option value="guinness">Guinness
    <option value="stuttgarter">Stuttgarter Schwabenbräu
    </select><br>
    <input type="hidden" name="is_submitted" value="submitted">
    <input type="submit" name="submit" value="submit me!">
    </form>
    <?php
    }?>

  13. Guess My Number
    Here is the code for Guess My Number in PHP, a program that generates a random number between 1 and 100 and asks the user to guess it. It will tell the user if the number is higher or lower after each guess and keep track of the number of guesses. This is just one way to write it in PHP.

    <title>Guess My Number (PHP)</title>
    <h1>Guess My Number (PHP)</h1>
    <?php
    $b = $_POST['b'];
    $x = $_POST['x'];
    $out = $_POST['out'];
    ?>
    <form action="gmn.php" method="post">
    Guess My Number (1-100): <input type="text" name="number" size=3>
    <br>
    <input type="submit" value="Guess">
    <?php
    if ($b == 0) {
       $x = mt_rand(1,100);
       $out = "";
    }
    ?>
    <input type="hidden" name="b" value=<?php echo ++$b;?>>
    <input type="hidden" name="x" value=<?php echo $x;?>>
    <?php
    if ($b > 1) {
       $a = $_POST['number'];
       if ($a != $x) $out .= ($a < $x) ? "Higher than $a.<br>" : "Lower than $a.<br>";
    ?>
    <input type="hidden" name="out" value="<?php echo $out;?>">
    </form>
    <?php
       echo $out;
       if ($a == $x) {
          echo "$a is correct!  " . ($b-1) . " tries.";
       }
    }
    ?>
    <br><br>
    <a href="gmn.php">Play Again</a>

  14. PHP reference
    PHP.net: includes an introductory tutorial and a full manual.

0 comments:

Post a Comment