PHP Overview

This is a short introduction to get you start and experience with php. For more information, please refer to "Programming the World Wide Web" by Robert W. Sebesta book and the PHP official website, http://www.php.net.

(Please tell me if you find any errors or omissions in the document —Upsorn Praphamontripong, 13-February-2021)

Overview

  What is PHP (PHP Hypertext Preprocessor)?  

  • PHP is a server-side scripting language
  • Scripts are embedded in HTML tags
  • Syntax looks similar to JavaScript (but runs on the server, not the client)
  • Dynamically typed
  • Interpreted language

  History of PHP  

PHP history image

  What does PHP do?  

  • Allow web developers to write dynamically generated pages quickly
  • Handle forms
  • Process files
  • Access databases

  Why is PHP popular?  

  • PHP is simple for new web developers, but offers many advanced features for professional programmers.
  • PHP code is enclosed in special start (<?php) and end (?>) tags, making the code easy to read and maintain.
  • PHP is executed on the server and thus the client receives the results of running the script without knowing the underlying code.

Server-side Processing


PHP Deployment

To deploy your PHP, you need:
  • Web server
  • PHP Engine
Note: (for CS 4640) we will use XAMPP which is a web server that includes PHP engine.

To view configuration,
  • Create a PHP file (named phpinfo.php) containing the following code
    <?php phpinfo(); ?>
  • Put the PHP file under XAMPP\htdocs folder
  • Start the web server (i.e., XAMPP)
  • Open http://localhost/phpinfo.php using a web browser

Basic structure and syntax

  Basic structure of PHP  

PHP documents look like HTML with code inside, but it is not HTML and the PHP code itself will not render inside a browser.
<?php
  ... php code (each statement ends with a semicolon) ...
?> 
When the container engine receives input from the web server, it reads the input from top to bottom (so-called "parsing"). During the parsing process, the PHP engine looks for the opening and closing (<?php .... ?>) tags and understands that the content between these tags is script code that it must interpreted. The engine ignores everything outside the <?php .... ?> and thus allowing (i) PHP files to have mixed content and (ii) PHP code to be embedded within HTML code.

PHP code is interpreted; only HTML is visible to user (observe the page source).

  How to embed PHP code  

  • External PHP file
    • Write PHP code and save it as an external file (e.g., sample.php)
    • <?php
        ... php code ...
      ?> 
    • Include it into another file by inserting <?php include('sample.php') ?>.

    For example, sample.php
        
    is included in external-php.php.
        

  • Internal to the file
    • Write PHP code directly in <body> ... </body> of html code
      <body>
        ...
        <?php
        ... php code ... 
        ?>
        ...
      </body>  
    For example, helloworld.php
        

  Tag rules  

Typically, PHP code (or script) always have opening and closing tags. However, where the PHP code intends only to insert a single string of text into an HTML document, an expression tag <?= php code; ?> may be used. For example:
         <?= "Hello world!"; ?> is equivalent to <?php echo "Hello world!"; ?>

  Statement rules  

Each statement must be terminated by a semicolon character (;).

For example, <?php echo "First statement"; echo "Second statement"; ?>

The closing ?> tag of a block of PHP code automatically implies a semicolon, and thus you can optionally omit the semicolon terminating the last statement of a PHP code block.

For example, <?php echo "First statement"; echo "Second statement" ?>

  Comments in PHP  

Three syntax styles for comments
// this is a comment
# this is a comment 
/* this is for 
   multiple lines of comments */ 

Variables

  • Variable names begin with a $
  • Variable names can comprise letters, numbers, and underscore characters, but not spaces
    • $variable_name = value;
  • The first character after the $ must be a letter or an underscore character; it cannot be a number
  • Variable names are case-sensitive
  • Variables may be initialized without being declared
  • Variables are "loosely typed."
    • They can contain data of any type (integer, float, string, Boolean, object, NULL)
    • The data type is determined dynamically
    • Unlike "strongly typed" variables where the data type must be specified when the variable is created.
  • The variable's value can be displayed as part of a mixed string by enclosing the string and variable name in double quotes regardless of the variable's data type. For example,
    $color = "blue";
    echo "My favorite color is $color";
    The above PHP code is equivalent to
    $color = "blue";
    echo "My favorite color is " . $color;   // string concatenation with a dot (.)    
    Note: The double quotes ensure that PHP will evaluate the entire string and substitute named variables with their values. This feature does not work if the string is enclosed in single quotes.
Examples:
    variable.php (text version),
    php-string.php (text version)

Data types


Type Description Type checking
string Series of characters is_string(param)
int Non-decimal number is_int(param)
float Floating-point decimal number is_float(param)
bool Expression of a Boolean truth value is_bool(param)
array Ordered map of multiple data values that associates keys to values (keys may be indexed number by default or may be explicitly specified labels) is_array(param)
object Class containing strored ata properties and providing methods to process data is_object(param)
NULL Variable with no value is_null(param)

Additional functions:
  • gettype(): return type
  • var_dump(): return type and dump structured information that displays its type and value
Example: variable-datatype.php (text version)

Arrays

  • Each array element consists of two parts: key and value (key may be integer or string)
    • Indexed array — key is integer. Index starts at zero. For example,
      $days[] = 'Monday';
      $days[] = 'Tuesday'; 
      $days[] = 'Wednesday';  
          
      // or
              
      $days = array('Monday', 'Tuesday', 'Wednesday');
            
      // both create an array where the value stored in each element 
      // can be referenced using its index number
       
      echo $days[1];      // Tuesday  
      var_dump($days);    // array(3) { [0]=> string(6) "Monday" [1]=> string(7) "Tuesday" [2]=> string(9) "Wednesday" } 
      
      // or 
      
      $days = array('Monday', 'Tuesday', 'Wednesday', 5 => 'Friday', '6' => 'Saturday', 7 => 'Sunday');
      var_dump($days);   // array(6) { [0]=> string(6) "Monday" [1]=> string(7) "Tuesday" [2]=> string(9) "Wednesday" 
                         //            [5]=> string(6) "Friday" [6]=> string(8) "Saturday" [7]=> string(6) "Sunday" }  
      
      
    • Associative array — key is primitive data type. For example,
      $months['jan'] = 'January';
      $months['feb'] = 'February';
      $months['mar'] = 'March';
          
      // or
              
      $months = array('jan' => 'January', 'feb' => 'February', 'mar' => 'March');
            
      // both create an array where the value stored in each element 
      // can be referenced using its key name
       
      echo $months['jan'];      // January  
      
      // Another example
      $mixedTypeArray['jan'] = 'January';
      $mixedTypeArray['2'] = 'February';
      $mixedTypeArray[3] = 'March';
      $mixedTypeArray[true] = 'April';
      
      echo $mixedTypeArray['2'] . "<br/>";      // February
      
      $mixedTypeArray[2] = 'another entry of February';
      echo $mixedTypeArray[2] . "<br/>";        // 'another entry of February';
      echo $mixedTypeArray['2'] . "<br/>";      // 'another entry of February';
      
      $mixedTypeArray[2.8] = '2.8 will round down to 2';
      // this assignment will replace the value of key=2 of the array
      echo $mixedTypeArray[2] . "<br/>";        // 2.8 will round down to 2
      
      $mixedTypeArray['2.8'] = 'Huh??';
      echo $mixedTypeArray['2.8'] . "<br/>";    // Huh?? 
      
      echo $mixedTypeArray[1] . " : " . $mixedTypeArray[true] . " <br/>";     // April : April 
      
      $mixedTypeArray[1] = 'true equals to 1 in PHP';
      
      echo "$mixedTypeArray[1] <br/>";          // true equals to 1 in PHP
      
      $mixedTypeArray[4] = 'another entry of February';
      
      var_dump($mixedTypeArray);                  
      // array(6) { ["jan"]=> string(7) "January" [2]=> string(24) "2.8 will round down to 2" 
                    [3]=> string(5) "March" [1]=> string(23) "true equals to 1 in PHP" 
                    ["2.8"]=> string(5) "Huh??" [4]=> string(25) "another entry of February" }   

  • To create an array
    • Use the assignment operation
      $states[0] = "Virginia";
      $states[] = "Georgia";   // implicit key = the array's current key + 1
      $capitals['VA'] = "Richmond";
      $matrix[7][11] = 2.718;   
    • Use the Array construct
      // specify values without keys  
      // PHP interpreter will furnish the numeric keys 0, 1, 2       
      $list = Array(17, 24, 30);  
                                      
      // specify values with keys                                
      $agelist = Array("Joe" => 17, "Mary" => 24, "Ann" => 30);  

  • To access array elements
    $list[2] = 34;
    $agelist['Mary'] = 44;  

  • To traverse array
    for ($i=0; $i<count($months); $i++)
    {
       // use the current $i on each iteration, $months[$i] to access an element in the array
    }
    
    for ($i=0; $i<sizeof($months); $i++)
    {
       // use the current $i on each iteration, $months[$i] to access an element in the array
    }
    
    foreach ($months as $value)      
    {
       // use the current $value on each iteration 
    }
     
    foreach ($months as $key => $value)
    {
       // use the current $key and $value on each iteration 
    } 

  • To join elements of an array with a string
    $arr = Array ("A", "E", "I", "O", "U");
    $str = implode("-", $arr);  // join array elements with "-" 
                                // the resulting string $str will be "A-E-I-O-U")  
  • To split a string by a specified string into pieces; i.e., breaking a string into an array
    $str = "A E I O U";
    $arr = explode(" ", $str);  // split a given string based on a " " separator 
                                // and put the pieces in array 
                                // this results in 
                                // Array([0]=>"A", [1]=>"E", [2]=>"I", [3]=>"O", [4]=>"U")  

  • To slice an array
    $days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    $workdays = array_slice($days, 1, 5);      // array_slice(array_to_slice, start_index, length)  

  • To sort array
    • Ascending alphanumeric order
      • sort() function — sort by value discarding the original key
      • asort() function — sort by value retaining the original key
      • ksort() function — sort by key
    • Descending alphanumeric order
      • rsort() function — sort by value discarding the original key
      • arsort() function — sort by value retaining the original key
      • krsort() function — sort by key

  • Multi-dimensional array
    $letters = array('A', 'B', 'C');
    $numbers = array(1, 2, 3);
    $matrix = array('Letter' => $letters, 'Number' => $numbers);
       
    // access individual item
    echo $matrix['Letter'][0];
       
    // To use an array variable as part of a mixed string,  
    // if an array variable uses quoted keys,
    // the array variable must be enclosed within curly braces  
    echo "(mix with string) Element value is {$matrix['Letter'][0]}";
        
    // To traverse 
    foreach ($matrix as $matrix_key => $matrix_value)
    {
       foreach ($matrix_value as $key => $value)
       echo $matrix_key .'[' . $key .'] = '. $matrix_value[$key] .'<br />';
    } 

    $user = array( 'info' => array ('name' => 'Duh',
                                    'age' => 32, 
                                    'location' => 'USA', ...  )
                   'education_level' => ... 
                 );
    echo "I live in $user['info']['location'] <br/>";
    echo "My latest education level is $user['info']['education_level'] <br/>";  
Example: array-example.php (text version)

Comparisons


Operator Compative test
== Equality (compare values)
!= Inequality
=== Identity (compare values and types)
!== Non-identically
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<=> Spaceship (compare values)
  • Return 1 when the left operand is greater than the right
  • Return -1 when the left operand is less than the right
  • Return 0 when the operands are equal

Example: comparisons.php (text version)

Conditions

( test-expression ) ? result-if-true : result-if-false ;

The conditional operator first evaluates an expression for a true or false Boolean value, then returns one of two specified results depending on the evaluation.
$parity = ( $number % 2 == 0 ) ? "Even" : "Odd" ;
echo "$number is $parity";   
To check if a variable is NULL, a null coalescing operator (??) can be used to traverse a number of opearands, from left to right, and return the value of the first operand that is not NULL. If none of the operands have a value (i.e., they are not NULL), the ?? operator will itself return a NULL result.
$a = NULL; $b = "xyz"; $c = 123;
$result = $a ?? $b ?? $c; 
echo "abc : $result"; 
Example: conditions.php (text version)

Control structures

  • Selection statements
    if ($num > 0)  
       $pos_count++; 
    elseif ($num < 0)
       $neg_count++; 
    else { 
       $zero_count++;
    } 

  • Loop statements
    $loop = 5;
    while (--$loop) {
       switch ($loop % 2) {
          case 0: 
             echo "Even<br />\n";
             break;
          case 1;
             echo "Odd<br />\n";
             break;
       }
    }   

    $fact = 1;
    $count = 1;
    while ($count < $n)  {  
       $count++;
       $fact *= $count;
    }  

    $count = 1;
    $sum = 0;
    do {  
       $sum += $count++;
       $count++;
    } while ($count <= 100);   

    for ($count = 1, $fact = 1; $count < $n; $count++)  
    {
       $fact *= $count;
    }   

    $students = array("Jack", "Jill", John", "Jane");  
    foreach ($students as $student) 
    {   
       echo $student . "<br/>";
    }

    $students = array("Jack" => array("age" => 20, "favorite_color" => "blue"), 
                      "Jill" => array("age" => 20, "favorite_color" => "green"), ... 
                     );  
    foreach ($students as $name => $info) 
    {   
       echo $name . "'s " . $info['age'] . "years old <br/>";
    }

  • Switch statements
    $letter = 'B';
    switch ($letter) {
       case 'A': echo 'Letter is A'; break;
       case 'B': echo 'Letter is B'; break;
       case 'C': echo 'Letter is C'; break;
       case 'D': echo 'Letter is D'; break;
       default: echo 'Default letter'; break;
    }   

Output statements

  • echo $myVar;
  • print "Hello World!";
  • printf("Your total bill is %5.2f", $price);
    note: examples on formatting
    %10s — a character string field of 10 characters
    %6d — an integer field of six digits
    %5.2f — a float or double field of five spaces, with two digits to the right of the decimal point, the decimal point, and two digits to the left
  • String concatenation uses .
    print "Hello, ".$_POST['name'];

Functions

  Predefined functions  

  • Some predefined functions that operate on numeric values
    • floor(0.60);    // returns 0
    • ceil(0.60);    // returns 1
    • round(0.60);    // returns 1
    • rand();    // returns random number
      rand(10, 100);    // returns random number between 10 and 100
    • abs(-6.7);    // returns 6.7
    • min(2,8,6,4,10);    // returns 2
      min(Array(2,8,6,4,10));    // returns 2
    • max(2,8,6,4,10);    // returns 10
      max(Array(2,8,6,4,10));    // returns 10

  • Some predefined functions that operate on string values
    • strlen("Hello");    // returns 5
    • strcmp("Hello world!","Hello world!");    // returns 0 (two strings are equal)
    • strpos("Hello world!", "world");    // returns 6
    • substr("Hello world!", 6, 1);    // returns w
    • chop("Hello world!","world!");    // returns Hello
    • trim(" Hello world! ");    // returns Hello world!

  User-defined functions  

  • Defining functions
    function name([parameters]) 
    {
       ...
    }   

  • Passing arguments (by value, by reference)
    function modify($val, &$ref) 
    { 
       ...  // $val is passed by value, $ref is passed by reference
            // The ampersand in the parameter declaration indicates   
            // that the parameter will be passed by reference.
    }   
    • Passing by value is similar to passing a copy of value. Thus, any change to the parameter will not affect the original variable. Unlike passing by reference, any change to the parameter will be a change to the original variable.
    • It is best to avoid passing a variable by reference to a function to avoid altering the application's state outside of the function.

  • Returning values
    • Functions can returns a single item to the caller. A return statement can include an expression to be evaluated so its single result will be returned to the caller. If the return statement is omitted, a function will return a NULL value.

  • Anonymous functions (functions without identifiers)
    function ([parameters]) 
    {
       ... 
    }  
    Two ways to call an anonymous function:
    • Immediately invoke
      // (assume we want to display the return value of the function)
      echo (function ([parameters]) 
      {
         ... 
      })([value_of_parameters]);  
    • Call through a variable of type function
      // (assume we want to display the return value of the function)
      $myVar = function ([parameters]) 
      {
         ... 
      };
      echo $myVal([value_of_parameters]);   

  • Varying parameters
    • A function that provides default string values to its parameters
      function drink($tmp='hot', $flavor='tea') 
      { 
         ...  
      }  
      // Call the function without passing parameters
      drink();
      
      // Call the function with some parameter passing (ordering)
      drink('iced'); 
      
      // Call the function with parameter passing (ordering)
      drink('cold', 'lemonade'); 

    • A function can accept multiple arguments
      // A function that accepts multiple integer arguments 
      // and display their total value
      function add(...$numbers)
      {
         $total = 0;
         foreach ($numbers as $num) 
         {
            $total += $num;
            echo "<hr />Total: $total";
         }
      }
      // Call the function and pass three values 
      add(1, 2, 3);  

  • Variables created outside a function have "global" scope, but are not normally accesssible from within any function block.
  • Variables created inside a function have "local" scope so are only accessible from within the particular function block.
  • To use a global variable inside a function, the declaration must include the global keyword (i.e., refer to a global variable defined outside). Note: Be careful when using global variables.
  • Local variables lose their values when the program scope leaves the function.
  • Static local variables retain their values when the program scope leaves the function. To ensure the updated value stored in a static variable is recognized on each function call (for instance, when writing a recursive function), use the static keyword when defining a variable.
Examples: Function examples

Handling data from the client

  • A web application is designed to handle and return a response for each request, leading to a request-response cycle.
  • Hypertext Transfer Protocol (HTTP) is the most commonly used protocol for communication between the client and the server.

The request-response cycle


HTTP response status

Category Status
Successful 2xx  200 OK
Redirection 3xx  301 Moved Permanently
302 Found
Client Error 4xx  400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
Server Error 5xx  500 Internal Server Error
503 Service Unavailable
504 Gateway Timeout


When a form is submitted to the server, form variables (or form data) are submitted with the request. The form data are stored in implicit arrays.
  • $_GET['form_input_name']
         // The form data are sent with the HTTP GET method.
  • $_POST['form_input_name']
         // The form data are sent with the HTTP POST method.
  • $_SERVER['PHP_SELF'];
         // PHP super global variable which holds information about headers, paths, environment variables, other data set by the web server, and script locations. Returns the filename of the currently executing script

<?php
// isSet() return true if $_POST['submit'] is not NULL or empty, 
// otherwise return false
if (isSet($_POST['submit']))     
{
   print "Hello, ".$_POST['name'];       
} 
else  
{           
?>
   <form method="post" action="<?php $_SERVER['PHP_SELF'] ?>" >
      Your name: <input type="text" name="name"> <br />
      <input type="submit" name="submit">
   </form>
<?php 
}
?>   

Another example of form handler
// check if the form is submitted with a POST method
if ($_SERVER['REQUEST_METHOD'] == 'POST')  
{
   // check if a specified parameter is empty
   if (empty($_POST['name']))   
      // do something
      ...
   }  
   ...
}
Examples: Form handling examples

Working with files

Getting a directory listing

To determine if a file or directory exists
  • is_file($path): returns true if $path exists and is a file
  • is_dir($path): returns true if $path exists and is a directory
  • file_exists($path): returns true if $path exists and is either file or a directory
To get the current directory
  • getcwd(): returns a string that specifies the current working directory
A constant that contains the correct path separator
  • DIRECTORY_SEPARATOR: a backslash on Windows or a forward slash on Mac and Linux
To get a directory listing
  • scandir($path): returns an array containing a list of the files and directories in $path if $path is a valid directory name; returns false otherwise

// Display a directory listing 
$path = getcwd(); 
$items = scandir($path);

echo "Contents of $path <br/>";
echo "<ul>";
foreach ($items as $item)
{
   echo "<li>$item</li>";
}
echo "</ul>"; 

// Display the files from a directory listing
$path = getcwd();
$items = scandir($path);

$files = array();
foreach ($items as $item)
{
   $item_path = $path . DIRECTORY_SEPARATOR . $item;
   if (is_file($item_path))
   {
      $files[] = $item;
   }
}
echo "Files in $path <br/>";
echo "<ul>";
foreach ($files as $file)
{
   echo "<li>" . $file . "</li>";
}
echo "</ul>";    

Reading and writing an entire file

To read an entire file
  • file($filename): returns an array with each element containing one line from the file
  • file_get_contents($filename): returns the contents of the file as a string
  • readfile($filename): reads a file and echoes it to the screen
$content = file_get_contents('sample-data.txt');

// htmlspecialchars converts special characters to HTML entities
$content = htmlspecialchars($content);

echo "<p>$content</p>";   

To write text to a file
  • file_put_contents($filename, $data): writes the specified data string to the specified filename
$sometext = "This is line 1.\nThis is line 2.\n";

// Replace the file content with value of $sometext
// (this is similiar to open a file with a "write" mode)
file_put_contents('sample-data2.txt', $sometext);   
// If the file does not exist, create one, then write the content.

// If file_put_contents results in permission denied, 
// check the directory permission. 
// Run chmod to set a "write" permission   

To read a file into an array
$list_of_content = file('sample-data.txt');
foreach ($list_of_content as $content)
{
   echo $content . "<br/>";
}    

To write an array to a file
$friends = array("Duh", "Huh", "Wacky");
$content = implode("\n", $friends);    //  join elements of an array with a \n

file_put_contents("sample-data3.txt", $content);   

Reading and writing part of a file

Modes used when opening a file with the fopen() function
Mode Description
rb or r Opens the file for reading. If the file does not exist, fopen() returns FALSE.
wb or w Opens the file for writing. If the file exists, the existing data is deleted. If the file does not exist, create one.
ab or a Opens the file for writing. If the file exists, the new data is appended. If the file does not exist, create one.
xb or x Create a new file for writing. If the file exists, fopen() returns FALSE.


To open and close a file
  • fopen($file, $mode): opens the specified file (in the specified location, i.e., path) with the specified opening mode and returns a file handle
  • feof($file): returns TRUE when the end of thespecified file is reached
  • fclose($file): closes the specified file

To read from and write to a file
  • fread($file, $length): returns data from the specified file at the specified length
  • fgets($file): returns a line from the specified file
  • fputs($file, $string): writes the contents of string to a file
  • fwrite($file, $string): writes the contents of string to a file

<?php
$file = fopen("infilename.txt", "r");      // r: read only
while ( !feof($file) ) {
   echo fgets($file), "<br />";
}
fclose($file);
?>  

<?php
$file = fopen("outfilename.txt", "a");     // a: write only, append
fputs($file, "Hello world"."\n");
fclose($file);
?>   

<?php
$file = fopen("outfilename.txt","w");      // w: write only
fputs($file, "Hello world"."\n");
fclose($file);
?> 

Reading and writing CSV data

To read tabular data from a CSV file
  • fgetcsv($file): reads in a line of comma-separated values and returns them in an array
$file = fopen('sample-data.csv', 'rb');
$scores = array();
while (!feof($file))
{
   $score = fgetcsv($file);
   if ($score !== false)
   {
      $scores[] = $score;
      
      echo "<div>$score[0] | $score[1] | $score[2] | $score[3] | $score[4] | $score[5] </div>";
   }
}   
To write tabular data to a CSV file
  • fputcsv($file, $array): writes the specified array to the specified file as a line of comma-separated values
$scores = array(array(90, 100, 100, 100, 95, 95),
                array(100, 100, 97, 100, 95, 100));
$file = fopen('sample-data1.csv', 'wb');
foreach ($scores as $score)
{
   fputcsv($file, $score);
}
fclose($file);   

Copying, renaming, and Deleting a file

To copy a file
  • copy($old_filename, $new_filename): copies the file with the old filename to file with the new filename. If successful, returns TRUE
$fname1 = "datafile1.txt";
$fname2 = "datafile2.txt";

if (file_exists($fname1))
{
   $copy_success = copy($fname1, $fname2);
   if ($copy_success)
      echo "<div>File was copied</div>";
}   

To rename a file
  • rename($old_filename, $new_filename): renames the file with the old filename to the new filename. If successful, returns TRUE
$fname2 = "datafile2.txt";
$fname_newname = "datafile_newname.txt";

if (file_exists($fname2))
{
   $rename_success = rename($fname2, $fname_newname);
   if ($rename_success)
      echo "<div>File was renamed</div>";   	
}   

To delete a file
  • unlink($fname): deletes the specified file. If successful, returns TRUE
$fname3 = "datafile3.txt";

if (file_exists($fname3))
{
   $delete_success = unlink($fname3);
   if ($delete_success)
      echo "<div>File was deleted</div>";
}  
Examples: File examples

Sessions

  • Session data are accessible from an implicit $_SESSION global array variable after a call is made to the session_start() function.
  • The implicit $_SESSION global array variable stores session data (names/values) in an associative array of keys and values.
  • By default, PHP will not start the session automatically. That is, no session ID will be generated; the cookie header (to be stored on the client such that the session can be identified) will not be set with the session ID value. The session_start() function must be explicitly called to initialize the session.
  • Once the session_start() is called, the session ID stored in the PHPSESSID variable (default name) will be loaded from the cookie request header. If the PHPSESSID does not exist, a fresh session will be started and the session ID will be sent back to the client with the current response in the header.
  • Each session has a unique session ID number, which can be seen using session_id() function.
  • When an HTML form is submitted to the server using the post (or get) method, its field data is automatically assigned to the implicit $_POST (or $_GET) global array variable. PHP script can check for the presence of individual submission fields using a built-in isset() function to seek an element of a specified HTML field name. When this confirms the field is present, its name and value can usually be stored in a session object. This might be used to stored username and password details to be used across a web application (or website).

  • To start a session, call a session_start() at the beginning of the PHP file
    session_start(); 

  • To check for the presence of individual submission fields, use a built-in isset() function to seek an element of a specified HTML field name.
    if (isset($_POST['user']))
    {
       // do something
    }  

  • To store data in a $_SESSION object for later used.
    $_SESSION['user'] = $user;       // assign value of $user to a $_SESSION object
                                     // (associative array) key = 'user', value = $user  

  • To retrieve data stored in a $_SESSION object,
    if (isset($_SESSION['user']))    // checks for the presence of individual field 
    {
       $myuser = $_SESSION['user'];  // access the $_SESSION array with a specified key              
       ...
    }  

  • To remove a specific element from $_SESSION, specify its name to the unset() function.
    unset($_SESSION['user']);

  • To completely terminate a session, call the session_destroy() function
    session_destroy();
  • Sessions are invisible to the users; users cannot disable the usage of server-side sessions.
Examples: Session examples

Cookies

  • Cookies are accessible from an implicit $_COOKIE global array variable
  • $_COOKIE contains all the cookie data stored in the browser, The cookie data are stored by the same host, through the response headers or JavaScript.
  • Since HTTP is stateless, using cookies is one way to keep track of the user session in a web application.
  • When an HTML form is submitted to the server using the post (or get) method, its field data is automatically assigned to the implicit $_POST (or $_GET) global array variable. PHP script can check for the presence of individual submission fields using a built-in isset() function to seek an element of a specified HTML field name. When this confirms the field is present, its name and value can usually be stored in a cookie. This might be used to stored username and password details to be used across a web application (or website).

  • To store data (as name/value pair) in a $_COOKIE object, use a setcookie() function.
    setcookie(name, value, expiration-time)
        
    // Example
    setcookie('user', $user, time()+3600);    // 1 hour = 60minutes * 60seconds       
    setcookie('pwd', password_hash($pwd, PASSWORD_DEFAULT), time()+3600);
    // Create a hash conversion of password values using password_hash() function
    // with the default hash algorithm (the default algorithm may change over time)
    
    // setcookie('pwd', password_hash($pwd, PASSWORD_BCRYPT), time()+3600);
    // Create a hash conversion of password values using password_hash() function
    // with the bcrypt hash algorithm 
    
    // setcookie('pwd', md5($pwd), time()+3600);
    // Create a hash conversion of password values using md5() function.
    // Using md5 is not recommended due to the weakness of the algorithm.  

  • To retrieve data stored in a $_COOKIE object,
    if (isset($_COOKIE['user']))    // checks for the presence of individual field 
    {
       $myuser = $_COOKIE['user'];  // access the $_COOKIE array with a specified key              
       ...
    }   

  • To remove data in a $_COOKIE object, set the expiration-time in the setcookie() to be in the past
    setcookie('user', 'value-does-not-matter', time()-3600);    // expired 1 hour ago

  • Cookies are invisible on the screen but are visible to the browser users; the users can access the file containing cookies on their machine. The users can clear, modify, or disable cookies.
  • If a user disables cookies, we may lose control of the application. That is, we will not be able to use cookies to maintain state of the application or share data throughout the application.
Examples: Cookies examples