CART 351 INTRODUCTION TO PHP

Introduction::

PHP: Originally stood for Personal Home Page and is now referred to as Hyper Text Preprocessor. Originally created by Rasmus Lerdorf in 1995, it is a server side scripting language originally designed for web development – making it possible to implement dynamic web pages. Generally speaking PHP is used to add functionality to a webpage that HTML alone cannot do. Listed below are only a few of PHP’s capabilities:

  • With PHP one can perform calculations: (i.e. finding the current date, performing mathematical equations etc..)
  • With PHP one can collect and process user information: i.e process information from an input form.
  • With PHP, one can interact with SQL databases: This ability allows for true dynamic pages. One can create pages based on retrieving data from a database, input information from the user into a database, implement search facilities etc…

HTTP is a communication protocol standard that governs the requests and responses between the browser running on a end users machine and the web server. The web server has the responsibility of accepting a request from a client and reply to this request in a meaningful way (usually by serving a requested webpage).

The Basic Request/Response Procedure

  • The user enters a url in the browser
  • The browser looks up the IP address for the url (communicates with the Internet service called The Domain Name Service).
  • The browser issues a request for the home page
  • The request is sent to the server
  • The server receives and accepts the request – looks for the web page on its hard drive
  • The server retrieves the page and sends it to the browser
  • The browser displays the page

The Request/Response Procedure Extended

For dynamic pages the Request & Response Procedure is more complex as it may include PHP and MySQL:

  • Once the web server receives the request, and finds the page on its hard drive, the server may notice that the page contains PHP code and will pass the page to the PHP Interpreter
  • The PHP interpreter executes the PHP code
  • If the PHP code contains SQL statements, the PHP interpreter passes these statements to the SQL database engine.
  • The database returns the results back to PHP
  • The PHP interpreter returns the results of the PHP code, along with any SQL results.
  • The web server returns the page to the client, which displays it

PHP syntax and including php functionality in a website::

In this section we look at the rules that must be followed to write properly structured and executable code.
PHP syntax + semantics are similar to other programming languages (JAVA, C…) – but php code is contained within a specific tag:

<?php //all php code goes in here…?>
PHP code can be placed within a normal html page / called within an html page. But, when you have php code inserted within your html file: you must save the file with a .php extension. The extension tells the server how to interpret the file: so that the php code gets sent to the php processor on the web server.

A first php example:

** If you are working on a Windows machine you will first need to install php – please follow: HOW TO LINK . The link is rather old and refers to php 5 – you will install php 7 (the steps are the same).
Please note: we have so far in this class been using the Atom Live server option for testing our webpages. As we are now going to be using php -> we can downlaod another package for Atom which enables us to run a php server from localhost. This is useful as then for testing purposes we do not need to upload files to hybrid.concordia.ca in order to view any changes.

  • In Atom: navigate to Packages-> Settings View -> Install Packages/Themes
  • Search for php-server and then install
  • Create a new project folder, create a new file, save as index.php and save it in this new folder
  • Copy and paste the following hello world example:
1
2
3
4
5
6
7
8
9
10
11
<html> 
<head> 
<title>Hello world example in php</title> 
</head> 
<body>
<?php 
echo "Hello World!";  
echo phpinfo();
?>
</body>
</html>

In this example the php tags (<? php …. ?>) are open and closed within the <body> tag.
To view php: we need to start the php server in Atom (very similar to Live Server) -> go to Packages -> PHP Server -> start in project root. You should now have the page running in the browser…

  • Specific syntax in the statement <?php echo “Hello World!”; ?>:
  • There must be a semicolon after every statement to signify the end of a statement. Otherwise the code will not be parsed correctly.
  • echo is a special php command, whose function is to send the response to the request made the client. In this case it responds with a hello world msg that results as normal text being displayed in the browser.
  • Like in html, white space is ignored within php code. Replace the following php statements and reload the page in your browser to verify that white space is in fact ignored…
    1
    2
    3
    4
    5
    6
    7
    8
    
    <?php 
    echo "Hello World!";  
     
    echo "Hello World Again!";  
     
    // has the same output as:
    echo "Hello World!";echo "Hello World Again!";  
    ?>

More on php echo command:
Importantly, the echo command is also be used to output HTML formatted statements.
For example: if we wanted to write “Hello world in header tags” to the browser within html “h2 tags”, then we would write the following statement in php:

1
2
3
<?php
echo "<br> <h2> Hello World in header tags </br> </h2>";
?>

If you now reload the page: you will see that the html has been written correctly to the page.
As well, if you view the page source: the html is written correctly to the file…
In the example we just executed, the php statement is embedded within a “normal” html page.

We can also choose to specify any CSS (style+layout code) as we would normally in an html page:
For example, if we defined a style for a generic <div> HTML element, we would define the style using the (style) tags in the (head) section of the html page (or by linking an external style sheet) and then generate our div tag dynamically using the php echo command.
Replace your current code in the “index.php” with the following code – and reload the page:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html> 
<head> 
<title>Hello world example in php</title> 
<style>
div
{
  width: 200px;
  height: 200px;
  margin: 2px;
  padding: 4px;
  border-width:2px;
  border-style:solid;
  border-color:#ccc;
  background-color:#98bf21;
  font-size:14px;
  color:#111111;
  font-family:arial;
 
}
</style>
</head> 
<body>
<?php 
echo "<div> Hello World in div tags </div>";
?>
</body>
</html>

As a second example:
If we had a second style definition which was not for a generic div tag, but rather for a specific div tag: then by using the id of the div tag we would need to change our echo statement to include the id attribute.
Copy the following style into the <style> section of the html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#divWithSpecificStyle
{
  width: 200px;
  height: 200px;
  margin: 2px;
  padding: 4px;
  border-width:2px;
  border-style:solid;
  border-color:#ccc;
  background-color:#3ad7ff;
  font-size:14px;
  color:#333333;
  font-family:arial;
 }

Now specify the following echo command in the php:

1
echo "<div id ='divWithSpecificStyle'> Hello World in div tags using a <strong>specific</strong> style </div>";

When you reload the page: you will now successfully see two div tags: one with the generic div style and the other with the more specific: specified by the id of the div.
** Be careful when using HTML code or any other string that includes double quotes!
echo uses double quotes to define the beginning and end of the string, so you must use one of the following tactics if your string contains quotations:

  • Don’t use double quotes inside your string
  • Escape your double quotes that are within the string with a backslash. To escape a double quote just place a backslash directly before the quotation mark, i.e. \”
  • Use single quotes (apostrophes) for quotes inside your string (as we did with the “id” attribute in the former example.
  • Examples for the right and wrong uses of echo:
  • This won’t work because of the double quotes around divWithSpecificStyle:
    (If you put the above code into your php – you will see that the resulting page will generate an error…)

    1
    2
    3
    
    <?php
    echo "<div id="divWithSpecificStyle">Hello World in div tags using a <strong>specific</strong> style </div>";
    ?>
  • This option is OK: because the double quotes have been escaped:
    1
    2
    3
    
    <?php
    echo "<div id= \"divWithSpecificStyle\"> Hello World in div tags using a <strong>specific</strong> style </div>";
    ?>
  • This option is also OK: because single quotes are used -NOT double quotes:
    1
    2
    3
    
    <?php
    echo "<div id ='divWithSpecificStyle'> Hello World in div tags using a <strong>specific</strong> style </div>";
    ?>

We can also link to an external style sheet (is preferable) as one normally would in a conventionally HTML-marked Up page. Let’s quickly run through an example:

  • Create a new file and save it as testStyle.css in your project directory.
  • Copy the following style into your testStyle.css file:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
    #divWithExtStyle
    {
      width: 200px;
      height: 200px;
      margin: 2px;
      padding: 4px;
      border-width:2px;
      border-style:solid;
      border-color:#ccc;
      background-color:rgba(149, 0, 153,0.95);
      font-size:14px;
      color:#ffffff;
      font-family:arial;
     }
  • Next: put an HTML link tag referring to your new style sheet in the HTML head section of the helloWorld.php page:
    1
    
    <link rel="stylesheet" type="text/css" href="testStyle.css">
  • Finally: lets define a div tag (using the echo command) that has the required id to reference the entry in our external style sheet.
    Place the following within the php tags:

    1
    
    echo "<div id ='divWithExtStyle'> Hello World in div tags using an <strong>external</strong> style </div>";

php comments:
Use comments! – It really helps for others and you to understand your code…
mulitline: /* */
single line: //

Variables & Data:

Storing data so we can use it later is one of the most important purposes for writing code. Fortunately, PHP can do this… If it couldn’t, it’d be rather useless…
Definition: A variable is a means for storing a value, such as text string “Hello World!” or the integer value ‘5’. A variable can be reused throughout the code, instead of having to type out the actual value over and over again.
So: how and when do we create variables ?

  • We start by declaring the variable – which means to give the variable a name: i.e surname.
  • In php you must place $ in front of all variables. i.e. $surname
  • Next: once we have our variable name we need to assign it an initial value:
    We do this by using the following syntax: $surname = value –where “value” can be an number or a text-string etc…
  • Now that the variable called $surname exists and is given an initial value, we can refer to this variable by its name and use it and even change it within our php code.

Lets try some basic examples of declaring, assigning and using variables. Clean out all the echo commands in the index.php page. Now, within the php tags: declare and initialize the following variables:

1
2
3
4
5
// declare some variables ...
$firstName = "Maria";
$lastName = "Smith";
$age =22;
$occupation ="Receptionist";

Now if you save and reload the page – you should see no difference – why? Because we have not “used” the variables… lets echo them to the page – place the following after the variable declarations:

1
2
3
4
5
6
// use them by writing them to the browser using the echo command.
echo"<h3> the original assignments to our variables::</h3>";
echo $firstName."<br \>";
echo $lastName."<br \>";
echo $age."<br \>";
echo $occupation."<br \>";

Now if we load the page – we have used our variables by echoing them to the page…
The next thing is that we can now change the values of these variables through the process of reassignment:
In your php – after the echo commands – type the following:

1
2
3
4
5
// now change the variables and echo again::
$firstName = "Sarah";
$lastName = "Keene";
$age =24;
$occupation ="Graphic Designer";

When you reload the page – again we do not see a change… why?
Because PHP executes code top-down: meaning that since the new variable assignments are written after our initial echo commands – the echo commands will use the original variable declarations.

However – if we write some more echo commands after the re initialization statements:

1
2
3
4
5
6
// use them again by writing them to the browser using the echo command.
echo"<h3> the variables reassigned::</h3>";
echo $firstName."<br \>";
echo $lastName."<br \>";
echo $age."<br \>";
echo $occupation."<br \>";

Now – the second set of echo commands will use the reinitialized variable values… and if these variables were never again re-assigned in the php – then these would be the values whenever we wanted to refer to the specific variable names.
Note:: we can also apply styles and formatting to our variable values – much the same way as we were doing before.

For example, lets put the output of the variables into a div tag that has a style applied to it. Assuming that the external style sheet that we used before still exists copy the following into your php tags:

1
2
3
4
5
6
7
8
echo "<div id ='divWithExtStyle'>";
// use them by writing them to the browser using the echo command.
echo"<h3> the new assignments to our variables::</h3>";
echo $firstName."<br \>";
echo $lastName."<br \>";
echo $age."<br \>";
echo $occupation."<br \>";
echo  "</div>";

What has changed? We just added the necessary echo commands in order to create and style our div tag…

We can have more than one set of php tags within the html markup: in fact you can have as many sets as you want – and a small warning it can become very hard to read your markup.
For example:
Add in a normal div tag within your html markup (anywhere):

1
<div id ='divWithSpecificStyle'> TEST DIV </div>

Now : if we want to output the value of the php variable $firstName in this div – then you could simply put:

1
<div id ='divWithSpecificStyle'> TEST DIV <?php echo $firstName; ?> </div>

Basically be aware that every time you open and close php tags you are running a script …

  • Variable Naming Conventions:
  • PHP variables must start with a letter or underscore “_”.
  • PHP variables may only be comprised of alpha-numeric characters and underscores. a-z, A-Z, 0-9, or _ .
  • Variables with more than one word should be separated with underscores. $my_variable
  • Variables with more than one word can also be distinguished with capitalization. $myVariable
  • Different types of variable assignment:
  • Declare and assign values to variables:
    1
    2
    3
    4
    
    $numYear = 2014;
    $numDay =4;
    $month ="February";
    $stringDay = "Tuesday";
  • Just echo the values of all the variables. Note: when using echo to print the value of a variable, there is no need to use double quotes – only necessary if one is displaying a literal string.
    1
    2
    3
    4
    5
    6
    
    echo "<br />";
    echo $stringDay;
    echo $numDay;
    echo $month;
    echo $numYear;
    echo "<br />";
  • echo the values of all variables as a concatenated string – (with the dot)
    1
    
      echo $stringDay .$numDay .$month .$numYear;
  • echo the values of all variables with spaces and with new line chars.
    1
    2
    
     echo "<br />";
     echo $stringDay." ".$numDay ." ". $month ." ".$numYear."<br />";
  • Same as (4) – but everything in double quotes:- access the values of the variables in the same way.
    1
    
     echo "$stringDay  $numDay $month $numYear <br />";
  • The next line will NOT give the same output: will interpret as a literal string.
    1
    
    echo '$stringDay  $numDay $month $numYear <br />';

Why does the last one output like that?
Well because what we are actually “echoing” are the names of the variables and NOT the values associated with the variables.
Be careful::
Use double quotes to print out the values of the variables when using the “echo” command

Very Brief Intro to PHP operators:

As is the case in all programming languages, operators are used to manipulate or perform operations on variables and values. We have already used string concatenation operator “.” and the assignment operator “=”. There exist the following operator categories, and in this section, their usage will be explained at a very high level. You are encouraged to look on the web for the many resources available that will explain these in detail.

  • Assignment Operators
  • Arithmetic Operators(+,-,* …)
  • Comparison Operators(<,>, !=, == ) – returns true or false
  • String Operators (.)
  • Combination Arithmetic & Assignment Operators (++, += …)

Operator Example 1:

1
2
3
4
5
6
7
8
// Define a variable called $addingNumbers and assign it an expression which adds 2 values together:
 $addingNumbers =  27 + 32;
 // same output
 echo "Perform addition: 27 + 32 = ".$addingNumbers."<br />"; 
 echo "Perform addition: 27 + 32 = $addingNumbers <br />"; 
 echo "Perform addition: 27+32 =". (27+32) ."<br />";
 // will not work - is interpreted as a string literal
 echo "Perform addition: 27+32 = (27+32) <br />";

The next class of operators depends on a very important component of programming:

Boolean logic:
Defined as: given a mathematical expression, the goal is to determine whether the result is a boolean value: TRUE or FALSE. Boolean logic is used extensively in order to make decisions in code.
We have the following operators to perform such comparisons:

  • Equality: if we wanted to find out whether two values are equal, use the == operator. i.e “15.234 == 16.234” – would be equated to false.
  • InEquality: if we wanted to find out whether two values are not equal, use the != operator. i.e “15.234 != 16.234” – would be equated to true.
  • Greater Than: if we wanted to find out whether the left value is greater than the right value, use the > operator. i.e “15.234 > 16.234” – would be equated to false.
  • Less Than: if we wanted to find out whether the left value is less than the right value, use the < operator. i.e “15.234 < 16.234” – would be equated to true.
  • Combined Comparisons: if we wanted to find out whether the left value is less than or equal the right value, use the <= operator. i.e “15.234 <=16.234” – would be equated to true.(Note the same idea applies to the greater than or equal comparison)

So given the small introduction to boolean expressions – how can these be used in the process of decision making?

IF Statements

There are a few different conditionals that you might want to use, but we’ll just focus the one used most commonly: the if construct.
It is very simple: if some boolean expression (the condition) is true then run a block of code.

You can also supply more code to be run if the condition is not true, and supply additional conditions and blocks of code to optionally be run. These forms are called if-else, as you’ll see below.
The most simple if statement looks something like this:
if (10 > 5) {
// Run the code in here
}

The code between the braces – “{” and “}” – is called a block, and this one is linked to the if statement. It’s only run if the conditional (between the parentheses) is true.::: 10 is indeed greater than 5, so the code in the block would run.

The if-else form of the if construct is used to run an alternative piece of code if the conditional is not true. The code in the if block below will be ignored, for example – only the code in the else block will be run.
if (43 < 2) {
// Run the code in here
} else {
// Run a different bit of code
}

We are ready to implement such decision making in php: so copy the following into your php code: what is the output?
Operator Example 2:

1
2
3
4
5
6
7
8
9
10
11
12
$valOne =34;
$valTwo =50;
// use if /else construct to execute the correct statement
// condition test using less than operator
if ($valOne<$valTwo)
{
  echo "$valOne is less than $valTwo <br />";
}
else
{
  echo "$valOne is greater than $valTwo <br />";
}

An Alternative to the if/else clause is the switch statement:
The switch statement is used to select one of many blocks of code to be executed. The syntax for this construct is the following:

switch (n) {
case label1:
// code to be executed if n=label1;
break;
case label2:
//code to be executed if n=label2;
break;
case label3:
// code to be executed if n=label3;
break;

default:
//code to be executed if n is different from all labels;
}

How the switch statement works:

  • One has a single expression n (most often a variable), that is evaluated once.
  • The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed.
  • The break keyword is used to prevent the code from running into the next case automatically.
  • The default statement is used if no match is found.

This construct is very useful in cases where you have an expression which will equate to > 2 values. In the previous if/else example we only had 2 possible outcomes: if the expression was TRUE, the if clause would be executed and if the expression was FALSE then the else clause is executed. We can rewrite the previous example using the switch case:

1
2
3
4
5
6
7
8
9
10
11
12
13
$valOne =75;
$valTwo =50;
switch($valOne>$valTwo){
  case true:
       echo "switch construct says: $valOne is greater than $valTwo <br />";
       break;
  case false:
       echo "switch construct says: $valOne is less than $valTwo <br />";
       break;
  default:
       echo "switch case constructs says:: the expression equates to something else than t or f <br />";
 
}

The next example will illustrate a case where the variable is a variable has a value between 1 and 10 and theerefore there are 10 possible outcomes:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
// select a random number between 1 and 10
 $myRandomNum = rand(1,10);
 switch($myRandomNum){
  case 1:
    echo "the value is 1 <br />";
    break;
  case 2:
    echo "the value is 2 <br />";
    break;
  case 3:
    echo "the value is 3 <br />";
   break;
  case 4:
    echo "the value is 4 <br />";
    break;
  case 5:
    echo "the value is 5 <br />";
    break;
  case 6:
    echo "the value is 6 <br />";
    break;
  case 7:
    echo "the value is 7 <br />";
    break;
  case 8:
    echo "the value is 8 <br />";
    break;
  case 9:
    echo "the value is 9 <br />";
   break;
  case 10:
    echo "the value is 10 <br />";
    break;
  default:
  echo " the value is not between 1 and 10 ...";
}

Note:: The above code can also be done with an if/else statement, but it would be a bit more typing and not seem as straightforward….

Array Review and Associative Arrays:

So far we have only used variables that were either text strings or numbers – but in the more involved examples in PHP and next week when we get into SQL, we will make use of a popular type of data structure known as: an Associative Array. First, let’s quickly review basic arrays:

An array in general is seen as a list of any kind of data type (numbers, text-strings …).
An array therefore is able to store multiple values in one single variable:

1
2
$shoppingList=array('Milk', 'Bread', 'Beans');
echo "I need " . $shoppingList[0] . ", " . $shoppingList[1] . " and " . $shoppingList[2] . ".";

If you put the following example in your php – and reload the page you will see that we have created one variable called $shoppingList, which holds 3 values.
Consequently, we can print out each item in the list by referencing its position in the list (i.e “Milk” is at position 0, “Bread” is at position 1 etc…).
Note:: positions always start at 0 – not 1!.
We can also change the value in an array by accessing the position of the value and then reassigning a new value to that position:

1
2
$shoppingList[1] ="Crackers";
echo "<br /> I need now: " . $shoppingList[0] . ", " . $shoppingList[1] . " and " . $shoppingList[2] . ".";

We can also access specific properties of an array – for example the count() function returns the number of elements in the array.
We can also add new items to an array: once again by assigning a value at a given position in the array. The next example illustrates these two concepts:

1
2
3
4
echo "<br /> Current Array length: ". count($shoppingList);
$shoppingList[3] ="Oranges";
echo "<br /> Final Shopping list: " . $shoppingList[0] . ", " . $shoppingList[1] . " and " . $shoppingList[2] ." and ".$shoppingList[3] .".";
echo "<br /> New Array length: ". count($shoppingList);

There are instances where one may want to access a value in array but NOT by the numerical position.
For example: if you wanted to store the MATH 201 final grades of particular students in an array, an array with numerical positions would not be the best choice.
Instead, one could use the students names as the keys in our associative array, and the value would be their respective grade.
Here the keys are instead of the numerical positions in a normal array – and therefore need to be manually assigned.
The following example will create an associative array called $mathGrades.
Since we don’t want to use numerical positions – as we add to the array – we give each entry in the list a “key” – which we will use to reference later.

Copy the following code into your php page – does it make sense?

1
2
3
4
5
6
7
8
9
10
// fill the array with the values
$math201grades["Mary"] = "B";
$math201grades["John"] = "A-";
$math201grades["Steve"] = "B+";
$math201grades["Gina"] = "B-";
// output
echo "Mary's MATH 201 final grade: " . $math201grades["Mary"] . "<br />";
echo "John's MATH 201 final grade: " . $math201grades["John"] . "<br />";
echo "Steve's MATH 201 final grade: " . $math201grades["Steve"] . "<br />";
echo "Gina's MATH 201 final grade: ". $math201grades["Gina"] ."<br />";

What if we want to find out the values of the keys in our associative array? Use the array_keys() function. This function will return an array, where each element is a key:
array_keys(array,value,strict);
array: the array that we want the keys from.
value: (Optional). You can specify a value, then only the keys with this value are returned.
strict: (Optional). Used with the value parameter.
The Possible values are:
true – Returns the keys with the specified value, depending on type: the number 5 is not the same as the string “5”.
false – Default value. Not depending on type, the number 5 is the same as the string “5”.

A similar function to return the values associated with each key is the array_values() function. The syntax is:
array_values(array);
This function works in a similar manner in that it returns an array, where in this case each element is an associated value.
The next example demonstrates how these functions are used:

1
2
3
4
5
6
7
8
$keys = array_keys($math201grades);
// var_dump() function outputs the contents of the array to the screen...
var_dump($keys);
echo "<br />";
 
$values = array_values($math201grades);
var_dump($values);
echo "<br />";

These functions prove highly useful when you want to iterate over an associative array using the conventional numerical indexes.

Review of Looping Constructs:

Loops offer the functionality to repeat the same block of code for a finite number of times. They’re incredibly useful, and are used, for example, to carry out an action on every item in an array (if we need to access every item in an array and do something). Two of the most common loops are called while loops and for loops.

THE FOR LOOP:
consists of 3 parts which are separated by semi colons:

  • Initialization: A variable is declared and initialized for use within the body of the loop. This variable is most often used inside the loop as a counter.
  • Boolean Test: This is exactly the same as the boolean tests found in conditional statements. It can be any expression that evaluates to true or false.
  • Iteration Expression: The last part is an instruction that you want to happen with each loop cycle.

A for loop construct thus looks like this:

for($counter =0; $counter < 10; $counter= $counter+1){
// THE BODY OF THE LOOP
// process everything in here while the variable counter is less than 10.
}

Lets implement a basic example using a for loop: We will declare an array with values and then by using a for loop we will echo each element in the array to the browser:

1
2
3
4
5
6
7
8
9
<?php
// fill the array with values
$shoppingList = array("milk","bread", "butter", "eggs","chocolate","oranges","peppers","chicken","potatoes","cheese");
echo "Example using a for loop <br \>";
// now loop through the array
for($counter =0; $counter < count($shoppingList); $counter =$counter+1){
	echo $shoppingList[$counter]."<br \>";
}
?>

THE WHILE LOOP:
This construct is similar to a for loop – and can do exactly the same thing – but has a slightly different syntax: A while loop repeats a block of code while a condition is true. Like an if statement, the condition is found in parentheses:

while($expression is TRUE){
// THE BODY OF THE LOOP
// process everything in here while the the boolean expression is true
}

So, if we implement the same example using a while loop – it would look like this:: Question – Why do you think we need to increment the counter variable within the body of the loop?

1
2
3
4
5
6
7
// using a while loop
echo "Same example using a while loop <br \>";
$counter =0;
while($counter < count($shoppingList)){
	echo $shoppingList[$counter]."<br \>";
	$counter=$counter+1;
}

Now that we have used a for and while loop to iterate over a normal array – how can we iterate over an associative array?
The first option shown using a for loop is to use the array_keys() and then loop over this array and output the associated values:

1
2
3
4
5
$keysArr = array_keys($math201grades);
for($i=0; $i<count($keys); $i++)
{
  echo" the value at index: ". $i . " is " . $math201grades[$keysArr[$i]]. " for the key: ".$keysArr[$i]. "<br />";
}

Essentially we iterate through the keys array – in order to access each key, and then use this key to access the associated value in the math201grades array.
The second option: the foreach loop is much shorter, and an efficient way to access each associated value.

1
2
3
4
foreach($math201grades as $entry)
{
    echo("the value using an associative array:: ".$entry."<br />");   
}

Essentially – as the above example demonstrates – we loop over the math201grades array. On each iteration, the value of the current element is assigned to $entry and the internal array pointer is advanced by one (so on the next iteration, you’ll be looking at the next element).
If we really want to access the keys as well as the values, there is a second form of the foreach loop:

1
2
3
4
foreach ($math201grades as $key => $entry) 
{
    echo "Key: $key; Value: $entry<br />";
}

The second form will additionally assign the current element’s key to the $entry variable on each iteration.

include() and require()

You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.

  • The include() Function
  • The require() Function

These two functions are very powerful elements in PHP which help in creating functions, headers, footers, or elements that can be reused on multiple pages.

The include() Function:

The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.

Assume you want to create a header element for your website (to be included in multiple pages…).
Start with the example project folder called includeEx.
Step 1:
We create a file called header.php with the following content: – this currently a repeating element in all 3 pages …

1
2
<!-- the header file -->
<h1> This is a common header in out cart 351 php example </h1>

Step 2:
We can now remove this content from each of the pages and then put instead (in each page):

1
2
3
<?php
include('header.php');
?>

… Results when run are the same – however if we now want to update this common content we just do this once (inside header.php … ). Also – if you view the source of the page : note that everything within the php tags is NOT a part of the document mark up …

Ok – lets see what happens when we try and include a file that does not exist: change the include() in index.php to:

1
2
3
4
<?php
include('headers.php');
echo('<p style = "color:red;"> echo content here after the error</p>');
?>

Run the page – note how the php page generates warnings – but continues the execution of the php script…

The require() Function:

The require()function takes all the text in a specified file and copies it into the file that uses the require function. If there is any problem in loading a file then the require() function generates a fatal error and halts the execution of the script.

So we can do the same example again but this time using the require(): change the include() in index.php to:

1
2
3
<?php
require('header.php');
?>

See – same as before…
However: if we now generate an error inside index.php:

1
2
3
4
<?php
require('headers.php');
echo('<p style = "color:red;"> echo content here after the error</p>');
?>

Now – when you run the page – a fatal error is generated and the execution of the script stops…

So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed…

For practice:
Take the nav menu elements and make a new php file called menu.php and then require it in the relevent pages.

PREDEFINED VARIABLES

PHP provides a large number of predefined variables to any script which it runs. PHP also provides an additional set of predefined arrays containing variables from the web server the environment, and user input. These arrays are called superglobals. We will look at a couple of them – in this class: but it is recommended that you consult the php documentation for furthur explanations and details:

$_SERVER

$_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server.
There is no guarantee that every web server will provide any of these.
Create a new php file in your project root : and we will then go through a few of the $_SERVER vars:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<html>
<head>
<title>SUPER GLOBAL: SERVER</title>
</head>
<body>
<?php
echo("<h2>SUPER GLOBAL: _SERVER::</h2>");
//This is a string denoting the user agent (client browser) being which is accessing the page.
echo($_SERVER['HTTP_USER_AGENT']);
echo("<br>");
//Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.
echo($_SERVER['REQUEST_METHOD']);
echo("<br>");
//The filename of the currently executing php script, relative to the document root
echo($_SERVER['PHP_SELF']);
 
echo("<br>");
echo($_SERVER['REQUEST_TIME']);
//The timestamp of the start of the request.
//is a Unix timestamp: It is the number of seconds that have elapsed since Jan 1 1970
//in coordinated Universal time (UTC)
echo("<br>");
$utc = $_SERVER['REQUEST_TIME'];
//convert to a date/time object
$dt = new DateTime();
//give the time stamp
$dt->setTimeStamp($utc);
//set time zone (not all are supported - need to look at documentation)
$dt->setTimeZone(new DateTimeZone('America/New_York'));
//format -> see: https://www.w3schools.com/php/func_date_date_format.asp
echo $dt->format('l, F j, Y g:i a');
?>
</body>
</html>

Ok – so lets run the same php with some query variables: so append the following to your url:
?color=red&fruit=tomato
We do not currently have access to the query vars directly -> we can use 2 more variables to do so:

1
2
3
4
5
6
echo("<br>");
$request_uri = $_SERVER['REQUEST_URI']; // THE WHOLE URL (with queries)
echo($request_uri);
echo("<br>");
$query_str = $_SERVER['QUERY_STRING']; //is just a string not the key value pair ///
echo($query_str);

Now: you can see that we have access to the entire URI and the query string seperately ….
In the next section we will look at using the superglobals:$_GET, $_POST and $_FILES in order to be able to process data from user input (i.e. an HTML form)

PHP & HTML Forms

We now know how to deal with variables, make decisions and create/access arrays using PHP.
The next part of this lecture will then begin to answer these questions:
How can we get data from a user (client)?
How can we pass this data to the server?
How can we retrieve data from the server?
How can we store and/or process data?

The most conventional method for getting data from the user is via an HTML form.
In order to send data to the server, an HTTP request is made. We then have two different HTTP methods for packaging the data that we want sent as part of the HTTP request: POST and GET :

POST

The POST method is used to send data to a server to create/update a resource.
The data sent to the server with POST is stored in the request body of the HTTP request i.e.:
POST /test/demo_form.php HTTP/1.1
Host: hybrid.concordia.ca
name1=value1&name2=value2

GET

GET is used to request data from a specified resource.
GET is one of the most common HTTP methods.
GET passes parameters (i.e. query data) in the URL of the GET request i.e:
/test/demo_form.php?name1=value1&name2=value2

Main differences between POST and GET

  • A GET request encodes the form parameters in the URL, in what is called a query string.
    Whereas a POST request passes the form parameters in the body of the HTTP request, leaving the URL untouched.
  • With the GET method, we can send data ONLY in form of pairs (Key=>value).
    When data is sent from a form with the GET method: the data to be sent is visible to everyone (displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2048 ASCII characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. – Never send sensitive data using the GET protocol!
  • In contrast, data sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and there no limits on the amount of information to send.
  • Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server. Because the variables are not displayed in the URL, it is not possible to bookmark the page.

Next week we will look at POST and at uploading files via an HTML form. Today, we will look at how to send data via the GET method. We will start without incorporating AJAX (trying to keep things simple :))

Create the HTML Form and do Preliminary Processing:

First, we will focus on creating the form and doing some preliminary processing.
The purpose of this HTML form is to take the favorite color, animal and number, plus their name (or nickname).

CREATE THE HTML FORM
Let us start with a new PHP page .
Then, using the following example, create an HTML form that will let the user enter the required information.
This file should be saved as inputToGet.php in the project directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<html>
<head>
<title>INPUT to GET in php</title>
</head>
<style>
p{
  padding:2px;
  width:100%;
}
p label{
  display:inline-block;
  width:10%;
  color:rgba(149, 0, 153,0.85);
 
}
.wrapper{
  width:75%;
  margin-left:12%;
}
h2{
  color:rgba(149, 0, 153,0.85);
 
}
input{
  width:50%;
}
input[type=submit]{
  width:8%;
}
form{
  padding:10px;
  background:rgba(149, 0, 153,0.25);
}
</style>
<body>
 
<div class = "wrapper">
  <h2> CART 351: PROCESS FORM WITH GET </h2>
<form method="get" action="inputToGet.php">
  <p><label>Fav Animal:</label><input type = "text" size="24" maxlength = "40"  name = "fav_animal" required></p>
  <p><label>Fav Color:</label><input type = "text" size="24" maxlength = "40"  name = "fav_color" required></p>
  <p><label>Fav Number:</label><input type = "number" size="24" maxlength = "40"  name = "fav_num" min="1" max="100" required></p>
  <p><input type = "submit" name = "submit" value = "send" id =buttonS /></p>
</form>
</div>
</body>
</html>

We have implemented very rudimentary form validation by specifying the required attribute for all input fields. Adding the “required” attribute ensures that the user must input some sort of data in each field, in order for the submit button to function (send data to the server…)

The attributes in the form tag are very important: <form action=”inputToGet..php” method=”get”>:

  • action has the value for the url (inputToGet.php) – which is the page to which the data will be sent to (there will be php code within this page to deal with the “getted” data).
  • method is the protocol by which the data will be sent (in this case: GET).

Now the “html” (user input) section is complete, we will create the php script which will process the HTML form information.

PHP SCRIPT FOR PROCESSING I
In the same page: inputToGet.php, we first need to check if data has been posted to the server (by the user clicking the submit button) and if yes – then we want to process the data from the form.
Otherwise we do nothing until there is something posted.
There is one in-built PHP variable which allows us to check if there is data waiting:
$_SERVER: this is an associative array, which has a “key” called REQUEST_METHOD – which we saw before and will now use::
If the value associated with this key is equal to GET then we know that there is data to process.
So we use an if statement which will execute a block of code if the boolean expression equates to true.
The following code sets up this if statement: Place the following BEFORE the opening html tags (at top of the page… )

1
2
3
4
5
6
7
8
9
10
11
<?php
//check if there has been something posted to the server to be processed
if($_SERVER['REQUEST_METHOD'] == 'GET')
{
// need to process
echo("inside get request<br>");
$request = $_SERVER['REQUEST_URI']; // THE WHOLE URL (with queries)
echo("the request: ".$request);
 
}
?>

So – if you now ran the page (without filling out the form) – you will see that this IF clause is true … why? because every time a client makes a request for a page – the server will see this as a GET request …
If you subsequently fill out the html form and press SUBMIT – you will see that the URI now also contains the query string …. we can use this …

PHP SCRIPT FOR PROCESSING II
We want to get the favorite color, animal and number inputs that are specified in the HTML form (by the name attribute of each input element).The inbuilt $_GET associative array will automatically contain the values of these input fields.
How?
When the submit my info button is clicked, the values for each of the input fields are stored automatically in this array, which is then submitted to the inputToGet.php web page. PHP has access to the submitted $_GET associative array.
The key for each value in the array is the value of the attribute called name specified in each form input field in the html form. Add the following within the initial IF statement:

1
2
3
if($_GET['fav_color']){
  echo("<br>form is being processed ");
}

We use the fav_color key within the $_GET array – to test if we need to process… and if you click on submit – you will now see that this clause is TRUE but if you just load the page without any query vars then this IF statement is FALSE…
Lastly – we can thus retrieve the values and then echo a message back to the page. Add the following code to retieve the values and store in variables. Place within the nested IF::

1
2
3
  $fcolor = $_GET['fav_color'];
  $fanimal = $_GET['fav_animal'];
  $fnum = $_GET['fav_num'];

Ok – let us do something with these values – first construct an IF statement based on the input:

1
2
3
4
5
6
7
8
9
// output something with these values::
 
  if(intval($fnum>60)){
    $theMessage = "You chose a number greater than 60";
  }
  else
  {
      $theMessage = "You chose a number less than 60";
  }

And be sure to also declare a default value at the top of the outeermost IF:

1
2
3
4
if($_SERVER['REQUEST_METHOD'] == 'GET')
{
$theMessage ="";
//....

Now where we put the ECHO statements MATTER – so we want to put it after the FORM – so append the following div to the wrapper div:

1
<div style = "background:rgba(149, 0, 153,0.75);color:white";><?php echo($theMessage)?> </div>

We are done – we have gotten user data – processed it and output a result …
Question: How do we clear the URL (when we click on refresh currently – the url STILL contains the query string) …
Solution:

  • Somehow store the data from the user
  • Reload the page
  • Get the data from storage and use it to display …

Well – we will do part two here …
After the else statement add the following:

1
  header("Location:inputToGet.php");

This will effectively redirect to the current page. – forcing a reload and the headers to be rewritten .. .
Note: you need to remove all echo statements….
So now – we have cleared the URL – BUT we have lost the value from the user…


NEXT week we will see how we can use SESSIONS to store the data between reloads … And finally we will use AJAX to most effectively process user input and communicate with the server, retrieve and display the results all without having to reload the page …